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 ) {
175 // ------------------------ Compressed File .
178 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
179 if (str_nb == GDCM_UNFOUND ) {
182 nb = atoi(str_nb.c_str() );
183 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
187 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
191 // ---------------- RLE
193 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
194 int res = (bool)gdcm_read_RLE_file (destination);
198 // ----------------- SingleFrame/Multiframe JPEG
200 long fragmentBegining; // for ftell, fseek
202 bool b = gdcmHeader::IsJPEG2000();
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);
247 res = (bool)gdcm_read_JPEG2000_file (destination); // Not Yet written
249 else if (IsJPEGLossless()) { // JPEG LossLess : call to xmedcom JPEG
251 JPEGLosslessDecodeImage (fp,
252 (unsigned short *)destination,
253 GetPixelSize()*8* GetSamplesPerPixel(),
256 res=1; // in order not to break the loop
258 } // ------------------------------------- endif (IsJPEGLossless())
260 else { // JPEG Lossy : call to xmedcon JPEG
261 // (just to see if it works) --> it does NOT !
263 JPEGLosslessDecodeImage (fp,
264 (unsigned short *)destination,
265 GetPixelSize()*8* GetSamplesPerPixel(),
269 // JPEG Lossy : call to IJG 6b
271 if (GetBitsStored() == 8) {
272 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
274 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
282 destination = (char *)destination + taille * nBytes; // location in user's memory
283 // for next fragment (if any)
285 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
286 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
288 ItemTagGr = ItemTagEl =0;
289 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
290 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
292 ItemTagGr=SwapShort(ItemTagGr);
293 ItemTagEl=SwapShort(ItemTagEl);
296 } // endWhile parsing fragments until Sequence Delim. Tag found
303 * \brief Allocates necessary memory, copies the pixel data
304 * (image[s]/volume[s]) to newly allocated zone.
305 * @return Pointer to newly allocated pixel data.
306 * \ NULL if alloc fails
308 void * gdcmFile::GetImageData (void) {
309 PixelData = (void *) malloc(lgrTotale);
311 GetImageDataIntoVector(PixelData, lgrTotale);
317 * \brief Copies at most MaxSize bytes of pixel data to caller's
319 * @param destination Address (in caller's memory space) at which the
320 * pixel data should be copied
321 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
322 * is not sufficient to hold the pixel data the copy is not
323 * executed (i.e. no partial copy).
324 * @return On success, the number of bytes actually copied. Zero on
325 * failure e.g. MaxSize is lower than necessary.
328 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
330 int nb, nbu, highBit, signe;
331 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
333 if ( lgrTotale > MaxSize ) {
334 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
335 "than caller's expected MaxSize");
339 (void)ReadPixelData(destination);
341 // Nombre de Bits Alloues pour le stockage d'un Pixel
342 str_nb = GetPubElValByNumber(0x0028,0x0100);
343 if (str_nb == GDCM_UNFOUND ) {
346 nb = atoi(str_nb.c_str() );
349 // Nombre de Bits Utilises
350 str_nbu=GetPubElValByNumber(0x0028,0x0101);
351 if (str_nbu == GDCM_UNFOUND ) {
354 nbu = atoi(str_nbu.c_str() );
357 // Position du Bit de Poids Fort
358 str_highBit=GetPubElValByNumber(0x0028,0x0102);
359 if (str_highBit == GDCM_UNFOUND ) {
362 highBit = atoi(str_highBit.c_str() );
366 str_signe=GetPubElValByNumber(0x0028,0x0103);
367 if (str_signe == GDCM_UNFOUND ) {
370 signe = atoi(str_signe.c_str() );
373 // re arange bytes inside the integer
375 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
377 // re arange bits inside the bytes
379 int l = (int)lgrTotale / (nb/8);
381 guint16 mask = 0xffff;
382 mask = mask >> (nb-nbu);
383 guint16 *deb = (guint16 *)destination;
384 for(int i = 0; i<l; i++) {
385 *deb = (*deb >> (nbu-highBit-1)) & mask;
388 } else if (nb == 32 ) {
389 guint32 mask = 0xffffffff;
390 mask = mask >> (nb-nbu);
391 guint32 *deb = (guint32 *)destination;
392 for(int i = 0; i<l; i++) {
393 *deb = (*deb >> (nbu-highBit-1)) & mask;
397 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
402 // Just to 'see' was was actually read on disk :-(
403 // Some troubles expected
405 // *Try* to deal with the color
406 // ----------------------------
408 // Planar configuration = 0 : Pixels are already RGB
409 // Planar configuration = 1 : 3 planes : R, G, B
410 // Planar configuration = 2 : 1 gray Plane + 3 LUT
412 // Well ... supposed to be !
413 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,PhotometricInterpretation=PALETTE COLOR
414 // and heuristic has to be found :-(
416 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
418 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
419 || (str_PhotometricInterpretation == "MONOCHROME2 ")
420 || (str_PhotometricInterpretation == "RGB")) {
423 int planConf=GetPlanarConfiguration();
425 // Whatever Planar Configuration is, "PALETTE COLOR " implies that we deal with the palette.
426 if (str_PhotometricInterpretation == "PALETTE COLOR ")
431 // Pixels are already RGB
437 if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
439 // need to make RGB Pixels from Planes Y,cB,cR
440 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
441 // for code optimisation
443 int l = GetXSize()*GetYSize();
444 int nbFrames = GetZSize();
446 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
447 unsigned char *x = newDest;
448 unsigned char * a = (unsigned char *)destination;
449 unsigned char * b = a + l;
450 unsigned char * c = b + l;
454 // TODO : Replace by the 'well known'
455 // integer computation counterpart
456 for (int i=0;i<nbFrames;i++) {
457 for (int j=0;j<l; j++) {
458 R= 1.164 *( *a-16) + 1.596 *( *c -128) + 0.5;
459 G= 1.164 *( *a-16) - 0.813 *( *c -128) - 0.392 *(*b -128) + 0.5;
460 B= 1.164 *( *a-16) + 2.017 *( *b -128) + 0.5;
465 if (R>255.0) R=255.0;
466 if (G>255.0) G=255.0;
467 if (B>255.0) B=255.0;
469 *(x++) = (unsigned char)R;
470 *(x++) = (unsigned char)G;
471 *(x++) = (unsigned char)B;
475 memmove(destination,newDest,lgrTotale);
480 // need to make RGB Pixels from Planes R,G,B
482 int l = GetXSize()*GetYSize();
483 int nbFrames = GetZSize();
485 char * newDest = (char*) malloc(lgrTotale);
487 char * a = (char *)destination;
492 // any trick not to have to allocate temporary buffer is welcome ...
494 for (int i=0;i<nbFrames;i++) {
495 for (int j=0;j<l; j++) {
501 memmove(destination,newDest,lgrTotale);
505 // now, it's an RGB image
506 // Lets's write it in the Header
507 std::string spp = "3";
508 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
509 std::string rgb="RGB";
510 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
515 // from Lut R + Lut G + Lut B
517 // we no longer use gdcmHeader::GetLUTRGB
518 // since a lot of images have strange info
519 // in the Lookup Table Descriptors (0028,1101),...
521 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
522 unsigned char * a = (unsigned char *)destination;
524 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
525 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
526 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
528 if (lutR && lutG && lutB ) { // need to make RGB Pixels
530 // and Lut R,Lut G,Lut B
532 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
534 memmove(newDest, destination, l);// move Gray pixels to temp area
537 // See PS 3.3-2003 C.11.1.1.2 p 619
540 if ( GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3
543 // if we get a black image, let's just remove the '+1'
545 // if it works, we shall have to check the 3 Palettes
546 // to see which byte is ==0 (first one, or second one)
548 //unsigned char * x = newDest;
550 for (int i=0;i<l; i++) {
551 j=newDest[i]*mult +1;
559 // now, it's an RGB image
560 std::string spp = "3";
561 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
562 std::string rgb="RGB";
563 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
565 } else { // need to make RGB Pixels (?)
566 // from grey Pixels (?!)
567 // and Gray Lut (!?!)
568 unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
569 // Well . I'll wait till I find such an image
579 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
584 * \brief Swap the bytes, according to swap code.
585 * \warning not end user intended
586 * @param im area to deal with
587 * @param swap swap code
588 * @param lgr Area Length
589 * @param nb Pixels Bit number
592 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
610 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
611 | ((((unsigned short int*)im)[i])<<8);
615 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
626 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
627 fort =((unsigned long int*)im)[i]>>16;
628 fort= (fort>>8) | (fort<<8);
629 faible=(faible>>8) | (faible<<8);
631 ((unsigned long int*)im)[i]=(s32<<16)|fort;
637 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
638 fort=((unsigned long int*)im)[i]>>16;
639 fort= (fort>>8) | (fort<<8);
640 faible=(faible>>8) | (faible<<8);
642 ((unsigned long int*)im)[i]=(s32<<16)|faible;
648 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
649 fort=((unsigned long int*)im)[i]>>16;
651 ((unsigned long int*)im)[i]=(s32<<16)|fort;
656 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
661 /////////////////////////////////////////////////////////////////
665 * \warning doit-etre etre publique ?
666 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
669 * @param ExpectedSize
671 * @return integer acts as a boolean
673 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
674 SetImageDataSize(ExpectedSize);
676 lgrTotale = ExpectedSize;
681 /////////////////////////////////////////////////////////////////
684 * \brief Sets the Pixel Area size in the Header
685 * --> not-for-rats function
687 * \warning WARNING doit-etre etre publique ?
688 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
690 * @param ImageDataSize new Pixel Area Size
691 * warning : nothing else is checked
694 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
695 std::string content1;
697 // Assumes ElValue (0x7fe0, 0x0010) exists ...
698 sprintf(car,"%d",ImageDataSize);
700 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
701 a->SetLength(ImageDataSize);
704 sprintf(car,"%d",ImageDataSize);
706 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
710 /////////////////////////////////////////////////////////////////
713 * \brief Ecrit sur disque les pixels d'UNE image
714 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
715 * Ca sera à l'utilisateur d'appeler son Reader correctement
716 * (Equivalent a IdImaWriteRawFile)
722 int gdcmFile::WriteRawData (std::string fileName) {
724 fp1 = fopen(fileName.c_str(),"wb");
726 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
729 fwrite (PixelData,lgrTotale, 1, fp1);
734 /////////////////////////////////////////////////////////////////
737 * \brief Ecrit sur disque UNE image Dicom
738 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
739 * Ca fonctionnera correctement (?) sur processeur Intel
740 * (Equivalent a IdDcmWrite)
743 * @return int acts as a boolean
746 int gdcmFile::WriteDcmImplVR (std::string fileName) {
747 return WriteBase(fileName, ImplicitVR);
750 /////////////////////////////////////////////////////////////////
755 * @return int acts as a boolean
758 int gdcmFile::WriteDcmImplVR (const char* fileName) {
759 return WriteDcmImplVR (std::string (fileName));
762 /////////////////////////////////////////////////////////////////
767 * @return int acts as a boolean
770 int gdcmFile::WriteDcmExplVR (std::string fileName) {
771 return WriteBase(fileName, ExplicitVR);
774 /////////////////////////////////////////////////////////////////
777 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
778 * (a l'attention des logiciels cliniques
779 * qui ne prennent en entrée QUE des images ACR ...
780 * \warning si un header DICOM est fourni en entree,
781 * les groupes < 0x0008 et les groupes impairs sont ignores)
782 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
783 * Ca fonctionnera correctement (?) sur processeur Intel
784 * (Equivalent a IdDcmWrite)
787 * @return int acts as a boolean
790 int gdcmFile::WriteAcr (std::string fileName) {
791 return WriteBase(fileName, ACR);
794 /////////////////////////////////////////////////////////////////
801 * @return int acts as a boolean
803 int gdcmFile::WriteBase (std::string FileName, FileType type) {
806 fp1 = fopen(FileName.c_str(),"wb");
808 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
812 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
814 // writing Dicom File Preamble
815 filePreamble=(char*)calloc(128,1);
816 fwrite(filePreamble,128,1,fp1);
817 fwrite("DICM",4,1,fp1);
820 // --------------------------------------------------------------
821 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
823 // if recognition code tells us we dealt with a LibIDO image
824 // we reproduce on disk the switch between lineNumber and columnNumber
825 // just before writting ...
827 std::string rows, columns;
828 if ( filetype == ACR_LIBIDO){
829 rows = GetPubElValByNumber(0x0028, 0x0010);
830 columns = GetPubElValByNumber(0x0028, 0x0011);
831 SetPubElValByNumber(columns, 0x0028, 0x0010);
832 SetPubElValByNumber(rows , 0x0028, 0x0011);
834 // ----------------- End of Special Patch ----------------
836 gdcmHeader::Write(fp1, type);
838 // --------------------------------------------------------------
839 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
841 // ...and we restore the Header to be Dicom Compliant again
842 // just after writting
844 if (filetype == ACR_LIBIDO){
845 SetPubElValByNumber(rows , 0x0028, 0x0010);
846 SetPubElValByNumber(columns, 0x0028, 0x0011);
848 // ----------------- End of Special Patch ----------------
850 fwrite(PixelData, lgrTotale, 1, fp1);