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() );
359 str_signe=GetPubElValByNumber(0x0028,0x0103);
360 if (str_signe == GDCM_UNFOUND ) {
361 signe = 0; // default is unsigned
363 signe = atoi(str_signe.c_str() );
366 // re arange bytes inside the integer
368 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
370 // to avoid pb with some xmedcon breakers images
371 if (nb==16 && nbu<nb && signe==0) {
372 int l = (int)lgrTotale / (nb/8);
373 guint16 *deb = (guint16 *)destination;
374 for(int i = 0; i<l; i++) {
381 // re arange bits inside the bytes
383 int l = (int)lgrTotale / (nb/8);
385 guint16 mask = 0xffff;
386 mask = mask >> (nb-nbu);
387 guint16 *deb = (guint16 *)destination;
388 for(int i = 0; i<l; i++) {
389 *deb = (*deb >> (nbu-highBit-1)) & mask;
392 } else if (nb == 32 ) {
393 guint32 mask = 0xffffffff;
394 mask = mask >> (nb-nbu);
395 guint32 *deb = (guint32 *)destination;
396 for(int i = 0; i<l; i++) {
397 *deb = (*deb >> (nbu-highBit-1)) & mask;
401 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
407 // Just to 'see' was was actually read on disk :-(
408 // Some troubles expected
410 // *Try* to deal with the color
411 // ----------------------------
413 std::string str_PhotometricInterpretation =
414 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
416 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
417 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
421 // Planar configuration = 0 : Pixels are already RGB
422 // Planar configuration = 1 : 3 planes : R, G, B
423 // Planar configuration = 2 : 1 gray Plane + 3 LUT
425 // Well ... supposed to be !
426 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
427 // PhotometricInterpretation=PALETTE COLOR
428 // and heuristic has to be found :-(
430 int planConf=GetPlanarConfiguration(); // 0028,0006
432 // Whatever Planar Configuration is,
433 // "PALETTE COLOR " implies that we deal with the palette.
434 if (str_PhotometricInterpretation == "PALETTE COLOR ")
439 // Pixels are already RGB
445 if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
447 // need to make RGB Pixels from Planes Y,cB,cR
448 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
449 // for code optimisation
451 int l = GetXSize()*GetYSize();
452 int nbFrames = GetZSize();
454 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
455 unsigned char *x = newDest;
456 unsigned char * a = (unsigned char *)destination;
457 unsigned char * b = a + l;
458 unsigned char * c = b + l;
462 // TODO : Replace by the 'well known'
463 // integer computation counterpart
464 for (int i=0;i<nbFrames;i++) {
465 for (int j=0;j<l; j++) {
466 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
467 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
468 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
473 if (R>255.0) R=255.0;
474 if (G>255.0) G=255.0;
475 if (B>255.0) B=255.0;
477 *(x++) = (unsigned char)R;
478 *(x++) = (unsigned char)G;
479 *(x++) = (unsigned char)B;
483 memmove(destination,newDest,lgrTotale);
488 // need to make RGB Pixels from Planes R,G,B
490 int l = GetXSize()*GetYSize();
491 int nbFrames = GetZSize();
493 char * newDest = (char*) malloc(lgrTotale);
495 char * a = (char *)destination;
500 // any trick not to have to allocate temporary buffer is welcome ...
502 for (int i=0;i<nbFrames;i++) {
503 for (int j=0;j<l; j++) {
509 memmove(destination,newDest,lgrTotale);
517 // from Lut R + Lut G + Lut B
519 // we no longer use gdcmHeader::GetLUTRGB
520 // since a lot of images have strange info
521 // in the Lookup Table Descriptors (0028,1101),...
523 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
524 unsigned char * a = (unsigned char *)destination;
526 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
527 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
528 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
530 if (lutR && lutG && lutB ) { // need to make RGB Pixels
532 // and Lut R,Lut G,Lut B
534 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
536 memmove(newDest, destination, l);// move Gray pixels to temp area
539 // See PS 3.3-2003 C.11.1.1.2 p 619
542 if (GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3
545 // if we get a black image, let's just remove the '+1'
547 // if it works, we shall have to check the 3 Palettes
548 // to see which byte is ==0 (first one, or second one)
550 for (int i=0;i<l; i++) {
551 j=newDest[i]*mult +1;
560 // need to make RGB Pixels (?)
561 // from grey Pixels (?!)
562 // and Gray Lut (!?!)
563 //unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
565 // Well . I'll wait till I find such an image
567 // or Segmented Green Palette Color Lookup Table Data and so on
569 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
570 // No idea how to manage it :-(
571 // Segmented xxx Palette Color are *more* than 65535 long ?!?
573 // WARNING : quick and dirty trick to produce a single plane Grey image
574 // See also gdcmHeaderHelper::GetNumberOfScalarComponents()
577 // end of dirty trick
583 // now, it's an RGB image
584 // Lets's write it in the Header
586 // CreateOrReplaceIfExist ?
588 std::string spp = "3"; // Samples Per Pixel
589 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
590 std::string rgb="RGB "; // Photometric Interpretation
591 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
592 std::string planConfig = "0"; // Planar Configuration
593 gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
595 // + Drop Palette Color ?
601 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
606 * \brief Swap the bytes, according to swap code.
607 * \warning not end user intended
608 * @param im area to deal with
609 * @param swap swap code
610 * @param lgr Area Length
611 * @param nb Pixels Bit number
614 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
632 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
633 | ((((unsigned short int*)im)[i])<<8);
637 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
648 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
649 fort =((unsigned long int*)im)[i]>>16;
650 fort= (fort>>8) | (fort<<8);
651 faible=(faible>>8) | (faible<<8);
653 ((unsigned long int*)im)[i]=(s32<<16)|fort;
659 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
660 fort=((unsigned long int*)im)[i]>>16;
661 fort= (fort>>8) | (fort<<8);
662 faible=(faible>>8) | (faible<<8);
664 ((unsigned long int*)im)[i]=(s32<<16)|faible;
670 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
671 fort=((unsigned long int*)im)[i]>>16;
673 ((unsigned long int*)im)[i]=(s32<<16)|fort;
678 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
683 /////////////////////////////////////////////////////////////////
687 * \warning doit-etre etre publique ?
688 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
691 * @param ExpectedSize
693 * @return integer acts as a boolean
695 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
696 SetImageDataSize(ExpectedSize);
698 lgrTotale = ExpectedSize;
703 /////////////////////////////////////////////////////////////////
706 * \brief Sets the Pixel Area size in the Header
707 * --> not-for-rats function
709 * \warning WARNING doit-etre etre publique ?
710 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
712 * @param ImageDataSize new Pixel Area Size
713 * warning : nothing else is checked
716 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
717 std::string content1;
719 // Assumes ElValue (0x7fe0, 0x0010) exists ...
720 sprintf(car,"%d",ImageDataSize);
722 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
723 a->SetLength(ImageDataSize);
726 sprintf(car,"%d",ImageDataSize);
728 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
732 /////////////////////////////////////////////////////////////////
735 * \brief Ecrit sur disque les pixels d'UNE image
736 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
737 * Ca sera à l'utilisateur d'appeler son Reader correctement
738 * (Equivalent a IdImaWriteRawFile)
744 int gdcmFile::WriteRawData (std::string fileName) {
746 fp1 = fopen(fileName.c_str(),"wb");
748 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
751 fwrite (PixelData,lgrTotale, 1, fp1);
756 /////////////////////////////////////////////////////////////////
759 * \brief Ecrit sur disque UNE image Dicom
760 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
761 * Ca fonctionnera correctement (?) sur processeur Intel
762 * (Equivalent a IdDcmWrite)
765 * @return int acts as a boolean
768 int gdcmFile::WriteDcmImplVR (std::string fileName) {
769 return WriteBase(fileName, ImplicitVR);
772 /////////////////////////////////////////////////////////////////
777 * @return int acts as a boolean
780 int gdcmFile::WriteDcmImplVR (const char* fileName) {
781 return WriteDcmImplVR (std::string (fileName));
784 /////////////////////////////////////////////////////////////////
789 * @return int acts as a boolean
792 int gdcmFile::WriteDcmExplVR (std::string fileName) {
793 return WriteBase(fileName, ExplicitVR);
796 /////////////////////////////////////////////////////////////////
799 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
800 * (a l'attention des logiciels cliniques
801 * qui ne prennent en entrée QUE des images ACR ...
802 * \warning si un header DICOM est fourni en entree,
803 * les groupes < 0x0008 et les groupes impairs sont ignores)
804 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
805 * Ca fonctionnera correctement (?) sur processeur Intel
806 * (Equivalent a IdDcmWrite)
809 * @return int acts as a boolean
812 int gdcmFile::WriteAcr (std::string fileName) {
813 return WriteBase(fileName, ACR);
816 /////////////////////////////////////////////////////////////////
823 * @return int acts as a boolean
825 int gdcmFile::WriteBase (std::string FileName, FileType type) {
828 fp1 = fopen(FileName.c_str(),"wb");
830 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
834 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
836 // writing Dicom File Preamble
837 filePreamble=(char*)calloc(128,1);
838 fwrite(filePreamble,128,1,fp1);
839 fwrite("DICM",4,1,fp1);
842 // --------------------------------------------------------------
843 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
845 // if recognition code tells us we dealt with a LibIDO image
846 // we reproduce on disk the switch between lineNumber and columnNumber
847 // just before writting ...
849 std::string rows, columns;
850 if ( filetype == ACR_LIBIDO){
851 rows = GetPubElValByNumber(0x0028, 0x0010);
852 columns = GetPubElValByNumber(0x0028, 0x0011);
853 SetPubElValByNumber(columns, 0x0028, 0x0010);
854 SetPubElValByNumber(rows , 0x0028, 0x0011);
856 // ----------------- End of Special Patch ----------------
858 gdcmHeader::Write(fp1, type);
860 // --------------------------------------------------------------
861 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
863 // ...and we restore the Header to be Dicom Compliant again
864 // just after writting
866 if (filetype == ACR_LIBIDO){
867 SetPubElValByNumber(rows , 0x0028, 0x0010);
868 SetPubElValByNumber(columns, 0x0028, 0x0011);
870 // ----------------- End of Special Patch ----------------
872 fwrite(PixelData, lgrTotale, 1, fp1);