5 #include "jpeg/ljpg/jpegless.h"
7 /////////////////////////////////////////////////////////////////
10 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
11 * file (see SetFileName, SetDcmTag and Write)
12 * Opens (in read only and when possible) an existing file and checks
13 * for DICOM compliance. Returns NULL on failure.
14 * \Note the in-memory representation of all available tags found in
15 * the DICOM header is post-poned to first header information access.
16 * This avoid a double parsing of public part of the header when
17 * one sets an a posteriori shadow dictionary (efficiency can be
18 * seen as a side effect).
20 * @param filename file to be opened for parsing
25 gdcmFile::gdcmFile(std::string & filename)
26 :gdcmHeader(filename.c_str())
29 SetPixelDataSizeFromHeader();
32 gdcmFile::gdcmFile(const char * filename)
36 SetPixelDataSizeFromHeader();
41 * \brief calcule la longueur (in bytes) A ALLOUER pour recevoir les
42 * pixels de l'image ou DES images dans le cas d'un multiframe
44 * ATTENTION : il ne s'agit PAS de la longueur du groupe des Pixels
45 * (dans le cas d'images compressees, elle n'a pas de sens).
47 * @return longueur a allouer
49 void gdcmFile::SetPixelDataSizeFromHeader(void) {
53 str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
54 if (str_nb == GDCM_UNFOUND ) {
57 nb = atoi(str_nb.c_str() );
60 lgrTotale = GetXSize() * GetYSize() * GetZSize()
61 * (nb/8)* GetSamplesPerPixel();
62 std::string str_PhotometricInterpretation =
63 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
64 if ( str_PhotometricInterpretation == "PALETTE COLOR " ) {
68 // see PS 3.3-2003 : C.7.6.3.2.1
78 // YBR_FULL_422 (no LUT, no Palette)
84 // ex : gdcm-US-ALOKA-16.dcm
85 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
86 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
87 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
89 // ex : US-PAL-8-10x-echo.dcm, 8BitsRunLengthColor.dcm
90 // 0028|1201 [OW] [Red Palette Color Lookup Table Data]
91 // 0028|1202 [OW] [Green Palette Color Lookup Table Data]
92 // 0028|1203 [OW] [Blue Palette Color Lookup Table Data]
94 // ex : OT-PAL-8-face.dcm
95 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
96 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
97 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
100 /////////////////////////////////////////////////////////////////
103 * \brief Returns the size (in bytes) of required memory to hold
104 * the pixel data represented in this file.
105 * @return The size of pixel data in bytes.
108 size_t gdcmFile::GetImageDataSize(void) {
113 /////////////////////////////////////////////////////////////////
116 * \brief Read pixel data from disk (optionaly decompressing) into the
117 * caller specified memory location.
118 * @param destination where the pixel data should be stored.
121 bool gdcmFile::ReadPixelData(void* destination) {
126 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
131 // ------------------------- Compacted File (12 Bits Per Pixel)
133 /* unpack 12 Bits pixels into 16 Bits pixels */
134 /* 2 pixels 12bit = [0xABCDEF] */
135 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
137 if (GetBitsAllocated()==12) {
138 int nbPixels = GetXSize()*GetYSize();
139 unsigned char b0, b1, b2;
141 for(int p=0;p<nbPixels;p+=2) {
145 *((unsigned short int*)destination)++ =
146 ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
147 /* A */ /* B */ /* D */
148 *((unsigned short int*)destination)++ =
149 ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
150 /* F */ /* C */ /* E */
152 // Troubles expected on Big-Endian processors ?
158 // ------------------------- Uncompressed File
161 IsImplicitVRLittleEndianTransferSyntax() ||
162 IsExplicitVRLittleEndianTransferSyntax() ||
163 IsExplicitVRBigEndianTransferSyntax() ||
164 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
166 size_t ItemRead = fread(destination, lgrTotale, 1, fp);
167 if ( ItemRead != 1 ) {
177 // ------------------------- Run Length Encoding
179 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
180 int res = (bool)gdcm_read_RLE_file (destination);
186 // ----------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
189 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
190 if (str_nb == GDCM_UNFOUND ) {
193 nb = atoi(str_nb.c_str() );
194 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
198 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
199 long fragmentBegining; // for ftell, fseek
201 bool jpg2000 = IsJPEG2000();
202 bool jpgLossless = IsJPEGLossless();
205 guint16 ItemTagGr,ItemTagEl;
208 // Position on begining of Jpeg Pixels
210 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
211 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
213 ItemTagGr=SwapShort(ItemTagGr);
214 ItemTagEl=SwapShort(ItemTagEl);
218 ln=SwapLong(ln); // Basic Offset Table Item length
221 // What is it used for ?!?
222 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
223 fread(BasicOffsetTableItemValue,ln,1,fp);
226 // first Fragment initialisation
227 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
228 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
230 ItemTagGr=SwapShort(ItemTagGr);
231 ItemTagEl=SwapShort(ItemTagEl);
234 // parsing fragments until Sequence Delim. Tag found
236 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
238 // --- for each Fragment
242 ln=SwapLong(ln); // Fragment Item length
244 fragmentBegining=ftell(fp);
246 if (jpg2000) { // JPEG 2000 : call to ???
248 res = (bool)gdcm_read_JPEG2000_file (destination); // Not Yet written
250 } // ------------------------------------- endif (JPEG2000)
252 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
254 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
255 (unsigned short *)destination,
256 GetPixelSize()*8* GetSamplesPerPixel(),
258 res=1; // in order not to break the loop
260 } // ------------------------------------- endif (JPEGLossless)
262 else { // JPEG Lossy : call to IJG 6b
264 if (GetBitsStored() == 8) {
265 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
267 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
269 } // ------------------------------------- endif (JPEGLossy)
273 destination = (char *)destination + taille * nBytes; // location in user's memory
274 // for next fragment (if any)
276 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
277 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
279 ItemTagGr = ItemTagEl =0;
280 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
281 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
283 ItemTagGr=SwapShort(ItemTagGr);
284 ItemTagEl=SwapShort(ItemTagEl);
287 } // endWhile parsing fragments until Sequence Delim. Tag found
294 * \brief Allocates necessary memory, copies the pixel data
295 * (image[s]/volume[s]) to newly allocated zone.
296 * @return Pointer to newly allocated pixel data.
297 * \ NULL if alloc fails
299 void * gdcmFile::GetImageData (void) {
300 PixelData = (void *) malloc(lgrTotale);
302 GetImageDataIntoVector(PixelData, lgrTotale);
308 * \brief Copies at most MaxSize bytes of pixel data to caller's
310 * @param destination Address (in caller's memory space) at which the
311 * pixel data should be copied
312 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
313 * is not sufficient to hold the pixel data the copy is not
314 * executed (i.e. no partial copy).
315 * @return On success, the number of bytes actually copied. Zero on
316 * failure e.g. MaxSize is lower than necessary.
319 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
321 int nb, nbu, highBit, signe;
322 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
324 if ( lgrTotale > MaxSize ) {
325 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
326 "than caller's expected MaxSize");
330 (void)ReadPixelData(destination);
332 // Nombre de Bits Alloues pour le stockage d'un Pixel
333 str_nb = GetPubElValByNumber(0x0028,0x0100);
334 if (str_nb == GDCM_UNFOUND ) {
337 nb = atoi(str_nb.c_str() );
340 // Nombre de Bits Utilises
341 str_nbu=GetPubElValByNumber(0x0028,0x0101);
342 if (str_nbu == GDCM_UNFOUND ) {
345 nbu = atoi(str_nbu.c_str() );
348 // Position du Bit de Poids Fort
349 str_highBit=GetPubElValByNumber(0x0028,0x0102);
350 if (str_highBit == GDCM_UNFOUND ) {
353 highBit = atoi(str_highBit.c_str() );
357 str_signe=GetPubElValByNumber(0x0028,0x0103);
358 if (str_signe == GDCM_UNFOUND ) {
361 signe = atoi(str_signe.c_str() );
364 // re arange bytes inside the integer
366 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
368 // re arange bits inside the bytes
370 int l = (int)lgrTotale / (nb/8);
372 guint16 mask = 0xffff;
373 mask = mask >> (nb-nbu);
374 guint16 *deb = (guint16 *)destination;
375 for(int i = 0; i<l; i++) {
376 *deb = (*deb >> (nbu-highBit-1)) & mask;
379 } else if (nb == 32 ) {
380 guint32 mask = 0xffffffff;
381 mask = mask >> (nb-nbu);
382 guint32 *deb = (guint32 *)destination;
383 for(int i = 0; i<l; i++) {
384 *deb = (*deb >> (nbu-highBit-1)) & mask;
388 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
393 // Just to 'see' was was actually read on disk :-(
394 // Some troubles expected
396 // *Try* to deal with the color
397 // ----------------------------
399 std::string str_PhotometricInterpretation =
400 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
402 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
403 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
407 // Planar configuration = 0 : Pixels are already RGB
408 // Planar configuration = 1 : 3 planes : R, G, B
409 // Planar configuration = 2 : 1 gray Plane + 3 LUT
411 // Well ... supposed to be !
412 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
413 // PhotometricInterpretation=PALETTE COLOR
414 // and heuristic has to be found :-(
416 int planConf=GetPlanarConfiguration(); // 0028,0006
418 // Whatever Planar Configuration is,
419 // "PALETTE COLOR " implies that we deal with the palette.
420 if (str_PhotometricInterpretation == "PALETTE COLOR ")
425 // Pixels are already RGB
431 if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
433 // need to make RGB Pixels from Planes Y,cB,cR
434 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
435 // for code optimisation
437 int l = GetXSize()*GetYSize();
438 int nbFrames = GetZSize();
440 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
441 unsigned char *x = newDest;
442 unsigned char * a = (unsigned char *)destination;
443 unsigned char * b = a + l;
444 unsigned char * c = b + l;
448 // TODO : Replace by the 'well known'
449 // integer computation counterpart
450 for (int i=0;i<nbFrames;i++) {
451 for (int j=0;j<l; j++) {
452 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
453 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
454 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
459 if (R>255.0) R=255.0;
460 if (G>255.0) G=255.0;
461 if (B>255.0) B=255.0;
463 *(x++) = (unsigned char)R;
464 *(x++) = (unsigned char)G;
465 *(x++) = (unsigned char)B;
469 memmove(destination,newDest,lgrTotale);
474 // need to make RGB Pixels from Planes R,G,B
476 int l = GetXSize()*GetYSize();
477 int nbFrames = GetZSize();
479 char * newDest = (char*) malloc(lgrTotale);
481 char * a = (char *)destination;
486 // any trick not to have to allocate temporary buffer is welcome ...
488 for (int i=0;i<nbFrames;i++) {
489 for (int j=0;j<l; j++) {
495 memmove(destination,newDest,lgrTotale);
503 // from Lut R + Lut G + Lut B
505 // we no longer use gdcmHeader::GetLUTRGB
506 // since a lot of images have strange info
507 // in the Lookup Table Descriptors (0028,1101),...
509 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
510 unsigned char * a = (unsigned char *)destination;
512 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
513 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
514 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
516 if (lutR && lutG && lutB ) { // need to make RGB Pixels
518 // and Lut R,Lut G,Lut B
520 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
522 memmove(newDest, destination, l);// move Gray pixels to temp area
525 // See PS 3.3-2003 C.11.1.1.2 p 619
528 if (GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3
531 // if we get a black image, let's just remove the '+1'
533 // if it works, we shall have to check the 3 Palettes
534 // to see which byte is ==0 (first one, or second one)
536 for (int i=0;i<l; i++) {
537 j=newDest[i]*mult +1;
546 // need to make RGB Pixels (?)
547 // from grey Pixels (?!)
548 // and Gray Lut (!?!)
549 //unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
551 // Well . I'll wait till I find such an image
553 // or Segmented Green Palette Color Lookup Table Data and so on
555 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
556 // No idea how to manage it :-(
557 // Segmented xxx Palette Color are *more* than 65535 long ?!?
559 // WARNING : quick and dirty trick to produce a single plane Grey image
560 // See also gdcmHeaderHelper::GetNumberOfScalarComponents()
563 // end of dirty trick
569 // now, it's an RGB image
570 // Lets's write it in the Header
572 // CreateOrReplaceIfExist ?
574 std::string spp = "3"; // Samples Per Pixel
575 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
576 std::string rgb="RGB "; // Photometric Interpretation
577 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
578 std::string planConfig = "0"; // Planar Configuration
579 gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
581 // + Drop Palette Color ?
587 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
592 * \brief Swap the bytes, according to swap code.
593 * \warning not end user intended
594 * @param im area to deal with
595 * @param swap swap code
596 * @param lgr Area Length
597 * @param nb Pixels Bit number
600 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
618 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
619 | ((((unsigned short int*)im)[i])<<8);
623 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
634 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
635 fort =((unsigned long int*)im)[i]>>16;
636 fort= (fort>>8) | (fort<<8);
637 faible=(faible>>8) | (faible<<8);
639 ((unsigned long int*)im)[i]=(s32<<16)|fort;
645 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
646 fort=((unsigned long int*)im)[i]>>16;
647 fort= (fort>>8) | (fort<<8);
648 faible=(faible>>8) | (faible<<8);
650 ((unsigned long int*)im)[i]=(s32<<16)|faible;
656 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
657 fort=((unsigned long int*)im)[i]>>16;
659 ((unsigned long int*)im)[i]=(s32<<16)|fort;
664 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
669 /////////////////////////////////////////////////////////////////
673 * \warning doit-etre etre publique ?
674 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
677 * @param ExpectedSize
679 * @return integer acts as a boolean
681 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
682 SetImageDataSize(ExpectedSize);
684 lgrTotale = ExpectedSize;
689 /////////////////////////////////////////////////////////////////
692 * \brief Sets the Pixel Area size in the Header
693 * --> not-for-rats function
695 * \warning WARNING doit-etre etre publique ?
696 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
698 * @param ImageDataSize new Pixel Area Size
699 * warning : nothing else is checked
702 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
703 std::string content1;
705 // Assumes ElValue (0x7fe0, 0x0010) exists ...
706 sprintf(car,"%d",ImageDataSize);
708 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
709 a->SetLength(ImageDataSize);
712 sprintf(car,"%d",ImageDataSize);
714 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
718 /////////////////////////////////////////////////////////////////
721 * \brief Ecrit sur disque les pixels d'UNE image
722 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
723 * Ca sera à l'utilisateur d'appeler son Reader correctement
724 * (Equivalent a IdImaWriteRawFile)
730 int gdcmFile::WriteRawData (std::string fileName) {
732 fp1 = fopen(fileName.c_str(),"wb");
734 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
737 fwrite (PixelData,lgrTotale, 1, fp1);
742 /////////////////////////////////////////////////////////////////
745 * \brief Ecrit sur disque UNE image Dicom
746 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
747 * Ca fonctionnera correctement (?) sur processeur Intel
748 * (Equivalent a IdDcmWrite)
751 * @return int acts as a boolean
754 int gdcmFile::WriteDcmImplVR (std::string fileName) {
755 return WriteBase(fileName, ImplicitVR);
758 /////////////////////////////////////////////////////////////////
763 * @return int acts as a boolean
766 int gdcmFile::WriteDcmImplVR (const char* fileName) {
767 return WriteDcmImplVR (std::string (fileName));
770 /////////////////////////////////////////////////////////////////
775 * @return int acts as a boolean
778 int gdcmFile::WriteDcmExplVR (std::string fileName) {
779 return WriteBase(fileName, ExplicitVR);
782 /////////////////////////////////////////////////////////////////
785 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
786 * (a l'attention des logiciels cliniques
787 * qui ne prennent en entrée QUE des images ACR ...
788 * \warning si un header DICOM est fourni en entree,
789 * les groupes < 0x0008 et les groupes impairs sont ignores)
790 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
791 * Ca fonctionnera correctement (?) sur processeur Intel
792 * (Equivalent a IdDcmWrite)
795 * @return int acts as a boolean
798 int gdcmFile::WriteAcr (std::string fileName) {
799 return WriteBase(fileName, ACR);
802 /////////////////////////////////////////////////////////////////
809 * @return int acts as a boolean
811 int gdcmFile::WriteBase (std::string FileName, FileType type) {
814 fp1 = fopen(FileName.c_str(),"wb");
816 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
820 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
822 // writing Dicom File Preamble
823 filePreamble=(char*)calloc(128,1);
824 fwrite(filePreamble,128,1,fp1);
825 fwrite("DICM",4,1,fp1);
828 // --------------------------------------------------------------
829 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
831 // if recognition code tells us we dealt with a LibIDO image
832 // we reproduce on disk the switch between lineNumber and columnNumber
833 // just before writting ...
835 std::string rows, columns;
836 if ( filetype == ACR_LIBIDO){
837 rows = GetPubElValByNumber(0x0028, 0x0010);
838 columns = GetPubElValByNumber(0x0028, 0x0011);
839 SetPubElValByNumber(columns, 0x0028, 0x0010);
840 SetPubElValByNumber(rows , 0x0028, 0x0011);
842 // ----------------- End of Special Patch ----------------
844 gdcmHeader::Write(fp1, type);
846 // --------------------------------------------------------------
847 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
849 // ...and we restore the Header to be Dicom Compliant again
850 // just after writting
852 if (filetype == ACR_LIBIDO){
853 SetPubElValByNumber(rows , 0x0028, 0x0010);
854 SetPubElValByNumber(columns, 0x0028, 0x0011);
856 // ----------------- End of Special Patch ----------------
858 fwrite(PixelData, lgrTotale, 1, fp1);