5 #include "iddcmjpeg.h" // for the 'LibIDO' Jpeg LossLess
6 #include "jpeg/ljpg/jpegless.h"
8 /////////////////////////////////////////////////////////////////
11 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
12 * file (see SetFileName, SetDcmTag and Write)
13 * Opens (in read only and when possible) an existing file and checks
14 * for DICOM compliance. Returns NULL on failure.
15 * \Note the in-memory representation of all available tags found in
16 * the DICOM header is post-poned to first header information access.
17 * This avoid a double parsing of public part of the header when
18 * one sets an a posteriori shadow dictionary (efficiency can be
19 * seen as a side effect).
21 * @param filename file to be opened for parsing
26 gdcmFile::gdcmFile(std::string & filename)
27 :gdcmHeader(filename.c_str())
30 SetPixelDataSizeFromHeader();
33 gdcmFile::gdcmFile(const char * filename)
37 SetPixelDataSizeFromHeader();
42 * \brief calcule la longueur (in bytes) A ALLOUER pour recevoir les
44 * ou DES images dans le cas d'un multiframe
45 * ATTENTION : il ne s'agit PAS de la longueur du groupe des Pixels
46 * (dans le cas d'images compressees, elle n'a pas de sens).
48 * @return longueur a allouer
50 void gdcmFile::SetPixelDataSizeFromHeader(void) {
54 str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
55 if (str_nb == GDCM_UNFOUND ) {
58 nb = atoi(str_nb.c_str() );
61 lgrTotale = GetXSize() * GetYSize() * GetZSize() * (nb/8)* GetSamplesPerPixel();
62 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
63 if ( str_PhotometricInterpretation == "PALETTE COLOR " ) {
67 // see PS 3.3-2003 : C.7.6.3.2.1
77 // YBR_FULL_422 (no LUT, no Palette)
83 // ex : gdcm-US-ALOKA-16.dcm
84 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
85 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
86 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
88 // ex : US-PAL-8-10x-echo.dcm, 8BitsRunLengthColor.dcm
89 // 0028|1201 [OW] [Red Palette Color Lookup Table Data]
90 // 0028|1202 [OW] [Green Palette Color Lookup Table Data]
91 // 0028|1203 [OW] [Blue Palette Color Lookup Table Data]
93 // ex : OT-PAL-8-face.dcm
94 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
95 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
96 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
99 /////////////////////////////////////////////////////////////////
102 * \brief Returns the size (in bytes) of required memory to hold
103 * the pixel data represented in this file.
104 * @return The size of pixel data in bytes.
107 size_t gdcmFile::GetImageDataSize(void) {
112 /////////////////////////////////////////////////////////////////
115 * \brief Read pixel data from disk (optionaly decompressing) into the
116 * caller specified memory location.
117 * @param destination where the pixel data should be stored.
120 bool gdcmFile::ReadPixelData(void* destination) {
125 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
130 // ------------------------- Compacted File (12 Bits Per Pixel)
132 /* unpack 12 Bits pixels into 16 Bits pixels */
133 /* 2 pixels 12bit = [0xABCDEF] */
134 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
136 if (GetBitsAllocated()==12) {
137 int nbPixels = GetXSize()*GetYSize();
138 unsigned char b0, b1, b2;
140 for(int p=0;p<nbPixels;p+=2) {
144 *((unsigned short int*)destination)++ =
145 ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
146 /* A */ /* B */ /* D */
147 *((unsigned short int*)destination)++ =
148 ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
149 /* F */ /* C */ /* E */
151 // Troubles expected on Big-Endian processors ?
157 // ------------------------- Uncompressed File
160 IsImplicitVRLittleEndianTransferSyntax() ||
161 IsExplicitVRLittleEndianTransferSyntax() ||
162 IsExplicitVRBigEndianTransferSyntax() ||
163 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
165 size_t ItemRead = fread(destination, lgrTotale, 1, fp);
166 if ( ItemRead != 1 ) {
176 // ------------------------- Run Length Encoding
178 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
179 int res = (bool)gdcm_read_RLE_file (destination);
185 // ----------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
188 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
189 if (str_nb == GDCM_UNFOUND ) {
192 nb = atoi(str_nb.c_str() );
193 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
197 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
198 long fragmentBegining; // for ftell, fseek
200 bool jpg2000 = IsJPEG2000();
201 bool jpgLossless = IsJPEGLossless();
204 guint16 ItemTagGr,ItemTagEl;
207 // Position on begining of Jpeg Pixels
209 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
210 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
212 ItemTagGr=SwapShort(ItemTagGr);
213 ItemTagEl=SwapShort(ItemTagEl);
217 ln=SwapLong(ln); // Basic Offset Table Item length
220 // What is it used for ?!?
221 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
222 fread(BasicOffsetTableItemValue,ln,1,fp);
225 // first Fragment initialisation
226 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
227 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
229 ItemTagGr=SwapShort(ItemTagGr);
230 ItemTagEl=SwapShort(ItemTagEl);
233 // parsing fragments until Sequence Delim. Tag found
235 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
237 // --- for each Fragment
241 ln=SwapLong(ln); // Fragment Item length
243 fragmentBegining=ftell(fp);
245 if (jpg2000) { // JPEG 2000 : call to ???
247 res = (bool)gdcm_read_JPEG2000_file (destination); // Not Yet written
249 } // ------------------------------------- endif (JPEG2000)
251 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
253 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
254 (unsigned short *)destination,
255 GetPixelSize()*8* GetSamplesPerPixel(),
257 res=1; // in order not to break the loop
259 } // ------------------------------------- endif (JPEGLossless)
261 else { // JPEG Lossy : call to IJG 6b
263 if (GetBitsStored() == 8) {
264 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
266 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
268 } // ------------------------------------- endif (JPEGLossy)
272 destination = (char *)destination + taille * nBytes; // location in user's memory
273 // for next fragment (if any)
275 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
276 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
278 ItemTagGr = ItemTagEl =0;
279 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
280 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
282 ItemTagGr=SwapShort(ItemTagGr);
283 ItemTagEl=SwapShort(ItemTagEl);
286 } // endWhile parsing fragments until Sequence Delim. Tag found
293 * \brief Allocates necessary memory, copies the pixel data
294 * (image[s]/volume[s]) to newly allocated zone.
295 * @return Pointer to newly allocated pixel data.
296 * \ NULL if alloc fails
298 void * gdcmFile::GetImageData (void) {
299 PixelData = (void *) malloc(lgrTotale);
301 GetImageDataIntoVector(PixelData, lgrTotale);
307 * \brief Copies at most MaxSize bytes of pixel data to caller's
309 * @param destination Address (in caller's memory space) at which the
310 * pixel data should be copied
311 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
312 * is not sufficient to hold the pixel data the copy is not
313 * executed (i.e. no partial copy).
314 * @return On success, the number of bytes actually copied. Zero on
315 * failure e.g. MaxSize is lower than necessary.
318 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
320 int nb, nbu, highBit, signe;
321 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
323 if ( lgrTotale > MaxSize ) {
324 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
325 "than caller's expected MaxSize");
329 (void)ReadPixelData(destination);
331 // Nombre de Bits Alloues pour le stockage d'un Pixel
332 str_nb = GetPubElValByNumber(0x0028,0x0100);
333 if (str_nb == GDCM_UNFOUND ) {
336 nb = atoi(str_nb.c_str() );
339 // Nombre de Bits Utilises
340 str_nbu=GetPubElValByNumber(0x0028,0x0101);
341 if (str_nbu == GDCM_UNFOUND ) {
344 nbu = atoi(str_nbu.c_str() );
347 // Position du Bit de Poids Fort
348 str_highBit=GetPubElValByNumber(0x0028,0x0102);
349 if (str_highBit == GDCM_UNFOUND ) {
352 highBit = atoi(str_highBit.c_str() );
356 str_signe=GetPubElValByNumber(0x0028,0x0103);
357 if (str_signe == GDCM_UNFOUND ) {
360 signe = atoi(str_signe.c_str() );
363 // re arange bytes inside the integer
365 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
367 // re arange bits inside the bytes
369 int l = (int)lgrTotale / (nb/8);
371 guint16 mask = 0xffff;
372 mask = mask >> (nb-nbu);
373 guint16 *deb = (guint16 *)destination;
374 for(int i = 0; i<l; i++) {
375 *deb = (*deb >> (nbu-highBit-1)) & mask;
378 } else if (nb == 32 ) {
379 guint32 mask = 0xffffffff;
380 mask = mask >> (nb-nbu);
381 guint32 *deb = (guint32 *)destination;
382 for(int i = 0; i<l; i++) {
383 *deb = (*deb >> (nbu-highBit-1)) & mask;
387 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
392 // Just to 'see' was was actually read on disk :-(
393 // Some troubles expected
395 // *Try* to deal with the color
396 // ----------------------------
398 std::string str_PhotometricInterpretation =
399 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
401 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
402 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
406 // Planar configuration = 0 : Pixels are already RGB
407 // Planar configuration = 1 : 3 planes : R, G, B
408 // Planar configuration = 2 : 1 gray Plane + 3 LUT
410 // Well ... supposed to be !
411 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
412 // PhotometricInterpretation=PALETTE COLOR
413 // and heuristic has to be found :-(
415 int planConf=GetPlanarConfiguration();
417 // Whatever Planar Configuration is,
418 // "PALETTE COLOR " implies that we deal with the palette.
419 if (str_PhotometricInterpretation == "PALETTE COLOR ")
424 // Pixels are already RGB
430 if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
432 // need to make RGB Pixels from Planes Y,cB,cR
433 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
434 // for code optimisation
436 int l = GetXSize()*GetYSize();
437 int nbFrames = GetZSize();
439 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
440 unsigned char *x = newDest;
441 unsigned char * a = (unsigned char *)destination;
442 unsigned char * b = a + l;
443 unsigned char * c = b + l;
447 // TODO : Replace by the 'well known'
448 // integer computation counterpart
449 for (int i=0;i<nbFrames;i++) {
450 for (int j=0;j<l; j++) {
451 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
452 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
453 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
458 if (R>255.0) R=255.0;
459 if (G>255.0) G=255.0;
460 if (B>255.0) B=255.0;
462 *(x++) = (unsigned char)R;
463 *(x++) = (unsigned char)G;
464 *(x++) = (unsigned char)B;
468 memmove(destination,newDest,lgrTotale);
473 // need to make RGB Pixels from Planes R,G,B
475 int l = GetXSize()*GetYSize();
476 int nbFrames = GetZSize();
478 char * newDest = (char*) malloc(lgrTotale);
480 char * a = (char *)destination;
485 // any trick not to have to allocate temporary buffer is welcome ...
487 for (int i=0;i<nbFrames;i++) {
488 for (int j=0;j<l; j++) {
494 memmove(destination,newDest,lgrTotale);
502 // from Lut R + Lut G + Lut B
504 // we no longer use gdcmHeader::GetLUTRGB
505 // since a lot of images have strange info
506 // in the Lookup Table Descriptors (0028,1101),...
508 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
509 unsigned char * a = (unsigned char *)destination;
511 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
512 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
513 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
515 if (lutR && lutG && lutB ) { // need to make RGB Pixels
517 // and Lut R,Lut G,Lut B
519 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
521 memmove(newDest, destination, l);// move Gray pixels to temp area
524 // See PS 3.3-2003 C.11.1.1.2 p 619
527 if ( GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3
530 // if we get a black image, let's just remove the '+1'
532 // if it works, we shall have to check the 3 Palettes
533 // to see which byte is ==0 (first one, or second one)
535 for (int i=0;i<l; i++) {
536 j=newDest[i]*mult +1;
544 } else { // need to make RGB Pixels (?)
545 // from grey Pixels (?!)
546 // and Gray Lut (!?!)
547 unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
548 // Well . I'll wait till I find such an image
554 // now, it's an RGB image
555 // Lets's write it in the Header
557 // CreateOrReplaceIfExist ?
559 std::string spp = "3"; // Samples Per Pixel
560 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
561 std::string rgb="RGB "; // Photometric Interpretation
562 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
563 std::string planConfig = "0"; // Planar Configuration
564 gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
566 // + Drop Palette Color ?
572 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
577 * \brief Swap the bytes, according to swap code.
578 * \warning not end user intended
579 * @param im area to deal with
580 * @param swap swap code
581 * @param lgr Area Length
582 * @param nb Pixels Bit number
585 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
603 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
604 | ((((unsigned short int*)im)[i])<<8);
608 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
619 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
620 fort =((unsigned long int*)im)[i]>>16;
621 fort= (fort>>8) | (fort<<8);
622 faible=(faible>>8) | (faible<<8);
624 ((unsigned long int*)im)[i]=(s32<<16)|fort;
630 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
631 fort=((unsigned long int*)im)[i]>>16;
632 fort= (fort>>8) | (fort<<8);
633 faible=(faible>>8) | (faible<<8);
635 ((unsigned long int*)im)[i]=(s32<<16)|faible;
641 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
642 fort=((unsigned long int*)im)[i]>>16;
644 ((unsigned long int*)im)[i]=(s32<<16)|fort;
649 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
654 /////////////////////////////////////////////////////////////////
658 * \warning doit-etre etre publique ?
659 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
662 * @param ExpectedSize
664 * @return integer acts as a boolean
666 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
667 SetImageDataSize(ExpectedSize);
669 lgrTotale = ExpectedSize;
674 /////////////////////////////////////////////////////////////////
677 * \brief Sets the Pixel Area size in the Header
678 * --> not-for-rats function
680 * \warning WARNING doit-etre etre publique ?
681 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
683 * @param ImageDataSize new Pixel Area Size
684 * warning : nothing else is checked
687 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
688 std::string content1;
690 // Assumes ElValue (0x7fe0, 0x0010) exists ...
691 sprintf(car,"%d",ImageDataSize);
693 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
694 a->SetLength(ImageDataSize);
697 sprintf(car,"%d",ImageDataSize);
699 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
703 /////////////////////////////////////////////////////////////////
706 * \brief Ecrit sur disque les pixels d'UNE image
707 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
708 * Ca sera à l'utilisateur d'appeler son Reader correctement
709 * (Equivalent a IdImaWriteRawFile)
715 int gdcmFile::WriteRawData (std::string fileName) {
717 fp1 = fopen(fileName.c_str(),"wb");
719 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
722 fwrite (PixelData,lgrTotale, 1, fp1);
727 /////////////////////////////////////////////////////////////////
730 * \brief Ecrit sur disque UNE image Dicom
731 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
732 * Ca fonctionnera correctement (?) sur processeur Intel
733 * (Equivalent a IdDcmWrite)
736 * @return int acts as a boolean
739 int gdcmFile::WriteDcmImplVR (std::string fileName) {
740 return WriteBase(fileName, ImplicitVR);
743 /////////////////////////////////////////////////////////////////
748 * @return int acts as a boolean
751 int gdcmFile::WriteDcmImplVR (const char* fileName) {
752 return WriteDcmImplVR (std::string (fileName));
755 /////////////////////////////////////////////////////////////////
760 * @return int acts as a boolean
763 int gdcmFile::WriteDcmExplVR (std::string fileName) {
764 return WriteBase(fileName, ExplicitVR);
767 /////////////////////////////////////////////////////////////////
770 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
771 * (a l'attention des logiciels cliniques
772 * qui ne prennent en entrée QUE des images ACR ...
773 * \warning si un header DICOM est fourni en entree,
774 * les groupes < 0x0008 et les groupes impairs sont ignores)
775 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
776 * Ca fonctionnera correctement (?) sur processeur Intel
777 * (Equivalent a IdDcmWrite)
780 * @return int acts as a boolean
783 int gdcmFile::WriteAcr (std::string fileName) {
784 return WriteBase(fileName, ACR);
787 /////////////////////////////////////////////////////////////////
794 * @return int acts as a boolean
796 int gdcmFile::WriteBase (std::string FileName, FileType type) {
799 fp1 = fopen(FileName.c_str(),"wb");
801 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
805 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
807 // writing Dicom File Preamble
808 filePreamble=(char*)calloc(128,1);
809 fwrite(filePreamble,128,1,fp1);
810 fwrite("DICM",4,1,fp1);
813 // --------------------------------------------------------------
814 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
816 // if recognition code tells us we dealt with a LibIDO image
817 // we reproduce on disk the switch between lineNumber and columnNumber
818 // just before writting ...
820 std::string rows, columns;
821 if ( filetype == ACR_LIBIDO){
822 rows = GetPubElValByNumber(0x0028, 0x0010);
823 columns = GetPubElValByNumber(0x0028, 0x0011);
824 SetPubElValByNumber(columns, 0x0028, 0x0010);
825 SetPubElValByNumber(rows , 0x0028, 0x0011);
827 // ----------------- End of Special Patch ----------------
829 gdcmHeader::Write(fp1, type);
831 // --------------------------------------------------------------
832 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
834 // ...and we restore the Header to be Dicom Compliant again
835 // just after writting
837 if (filetype == ACR_LIBIDO){
838 SetPubElValByNumber(rows , 0x0028, 0x0010);
839 SetPubElValByNumber(columns, 0x0028, 0x0011);
841 // ----------------- End of Special Patch ----------------
843 fwrite(PixelData, lgrTotale, 1, fp1);