5 #include "iddcmjpeg.h" // for the 'LibIDO' Jpeg LossLess
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())
28 SetPixelDataSizeFromHeader();
31 gdcmFile::gdcmFile(const char * filename)
34 SetPixelDataSizeFromHeader();
39 * \brief calcule la longueur (in bytes) A ALLOUER pour recevoir les
41 * ou DES images dans le cas d'un multiframe
42 * ATTENTION : il ne s'agit PAS de la longueur du groupe des Pixels
43 * (dans le cas d'images compressees, elle n'a pas de sens).
45 * @return longueur a allouer
47 void gdcmFile::SetPixelDataSizeFromHeader(void) {
51 str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
52 if (str_nb == GDCM_UNFOUND ) {
55 nb = atoi(str_nb.c_str() );
58 lgrTotale = GetXSize() * GetYSize() * GetZSize() * (nb/8)* GetSamplesPerPixel();
59 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
60 if ( str_PhotometricInterpretation == "PALETTE COLOR " ) {
64 // see PS 3.3-2003 : C.7.6.3.2.1
74 // YBR_FULL_422 (no LUT, no Palette)
80 // ex : gdcm-US-ALOKA-16.dcm
81 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
82 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
83 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
85 // ex : US-PAL-8-10x-echo.dcm, 8BitsRunLengthColor.dcm
86 // 0028|1201 [OW] [Red Palette Color Lookup Table Data]
87 // 0028|1202 [OW] [Green Palette Color Lookup Table Data]
88 // 0028|1203 [OW] [Blue Palette Color Lookup Table Data]
90 // ex : OT-PAL-8-face.dcm
91 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
92 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
93 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
97 /////////////////////////////////////////////////////////////////
100 * \brief Returns the size (in bytes) of required memory to hold
101 * the pixel data represented in this file.
102 * @return The size of pixel data in bytes.
105 size_t gdcmFile::GetImageDataSize(void) {
110 /////////////////////////////////////////////////////////////////
113 * \brief Read pixel data from disk (optionaly decompressing) into the
114 * caller specified memory location.
115 * @param destination where the pixel data should be stored.
118 bool gdcmFile::ReadPixelData(void* destination) {
123 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
128 // ------------------------- Uncompressed File
131 IsImplicitVRLittleEndianTransferSyntax() ||
132 IsExplicitVRLittleEndianTransferSyntax() ||
133 IsExplicitVRBigEndianTransferSyntax() ||
134 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
136 size_t ItemRead = fread(destination, lgrTotale, 1, fp);
137 if ( ItemRead != 1 ) {
146 // ------------------------ Compressed File .
149 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
150 if (str_nb == GDCM_UNFOUND ) {
153 nb = atoi(str_nb.c_str() );
154 if (nb == 12) nb =16;
158 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
161 // ------------------------------- JPEG LossLess : call to Jpeg Libido
163 if (IsJPEGLossless() /*&& GetZSize() == 1*/) {
165 int ln; // Position on begining of Jpeg Pixels
166 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : Basic Offset Table Item
169 ln=SwapLong(ln); // Item length
170 fseek(fp,ln,SEEK_CUR); // skipping Basic Offset Table ('ln' bytes)
171 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : First fragment Item Tag
172 fread(&ln,4,1,fp); // First fragment length (just to know)
176 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
177 // (We use the LibIDO one :-(
182 int * dataJpg = jpg->DataImg;
187 unsigned short *dest = (unsigned short *)destination;
188 for (int i=0; i<taille; i++) {
189 *((unsigned char *)dest+i) = *(dataJpg +i);
196 unsigned short *dest = (unsigned short *)destination;
197 for (int i=0; i<taille; i++) {
198 *((unsigned short *)dest+i) = *(dataJpg +i);
203 _IdDcmJpegFree (jpg);
207 // ------------------------------- RLE
209 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
210 int res = (bool)gdcm_read_RLE_file (destination);
214 // ------------------------------- JPEG Lossy : call to IJG 6b
216 long fragmentBegining; // for ftell, fseek
217 bool b = gdcmHeader::IsJPEG2000();
220 guint16 ItemTagGr,ItemTagEl;
221 int ln; // Position on begining of Jpeg Pixels
223 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
224 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
226 ItemTagGr=SwapShort(ItemTagGr);
227 ItemTagEl=SwapShort(ItemTagEl);
231 ln=SwapLong(ln); // Basic Offset Table Item length
234 // What is it used for ?!?
235 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
236 fread(BasicOffsetTableItemValue,ln,1,fp);
239 // first Fragment initialisation
240 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
241 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
243 ItemTagGr=SwapShort(ItemTagGr);
244 ItemTagEl=SwapShort(ItemTagEl);
247 // parsing fragments until Sequence Delim. Tag found
248 //unsigned short *dest = (unsigned short *)destination;
250 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
253 ln=SwapLong(ln); // Fragment Item length
255 // FIXME : multi fragments
256 fragmentBegining=ftell(fp);
260 res = (bool)gdcm_read_JPEG2000_file (destination); // Reading Fragment pixels
262 else if (IsJPEGLossless()) {
263 // ------------- call to LibIDO Jpeg for each Frame/fragment
265 // Warning : Works only if there is one fragment per frame
266 // (Or a single fragment for the multiframe file)
267 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
268 // (We use the LibIDO one :-(
273 int * dataJpg = jpg->DataImg;
274 unsigned short *dest = (unsigned short *)destination;
278 for (int i=0; i<taille; i++) {
279 *((unsigned char *)dest+i) = *(dataJpg +i);
286 for (int i=0; i<taille; i++) {
287 *((unsigned short *)dest+i) = *(dataJpg +i);
292 _IdDcmJpegFree (jpg);
294 } // ------------------------------------- endif (IsJPEGLossless())
297 if (GetBitsStored() == 8) {
298 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
300 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
305 // FIXME : will work only when each fragment corresponds to a Frame :-(
307 destination = (char *)destination + taille * nBytes; // location in user's memory
308 // for next fragment (if any)
309 // TODO : find a suitable file (multifragment/single Frame Jpeg file) to check
311 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
312 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
314 ItemTagGr = ItemTagEl =0;
315 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
316 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
318 ItemTagGr=SwapShort(ItemTagGr);
319 ItemTagEl=SwapShort(ItemTagEl);
322 //(char *) destination += taille * nBytes;
323 //std::cout << "destination" << destination << std::endl;
331 * \brief Allocates necessary memory, copies the pixel data
332 * (image[s]/volume[s]) to newly allocated zone.
333 * @return Pointer to newly allocated pixel data.
334 * \ NULL if alloc fails
336 void * gdcmFile::GetImageData (void) {
337 PixelData = (void *) malloc(lgrTotale);
339 GetImageDataIntoVector(PixelData, lgrTotale);
345 * \brief Copies at most MaxSize bytes of pixel data to caller's
347 * @param destination Address (in caller's memory space) at which the
348 * pixel data should be copied
349 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
350 * is not sufficient to hold the pixel data the copy is not
351 * executed (i.e. no partial copy).
352 * @return On success, the number of bytes actually copied. Zero on
353 * failure e.g. MaxSize is lower than necessary.
356 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
358 int nb, nbu, highBit, signe;
359 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
361 if ( lgrTotale > MaxSize ) {
362 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
363 "than caller's expected MaxSize");
367 (void)ReadPixelData(destination);
369 // Nombre de Bits Alloues pour le stockage d'un Pixel
370 str_nb = GetPubElValByNumber(0x0028,0x0100);
371 if (str_nb == GDCM_UNFOUND ) {
374 nb = atoi(str_nb.c_str() );
377 // Nombre de Bits Utilises
378 str_nbu=GetPubElValByNumber(0x0028,0x0101);
379 if (str_nbu == GDCM_UNFOUND ) {
382 nbu = atoi(str_nbu.c_str() );
385 // Position du Bit de Poids Fort
386 str_highBit=GetPubElValByNumber(0x0028,0x0102);
387 if (str_highBit == GDCM_UNFOUND ) {
390 highBit = atoi(str_highBit.c_str() );
394 str_signe=GetPubElValByNumber(0x0028,0x0103);
395 if (str_signe == GDCM_UNFOUND ) {
398 signe = atoi(str_signe.c_str() );
401 // re arange bytes inside the integer
403 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
405 // re arange bits inside the bytes
407 int l = (int)lgrTotale / (nb/8);
409 guint16 mask = 0xffff;
410 mask = mask >> (nb-nbu);
411 guint16 *deb = (guint16 *)destination;
412 for(int i = 0; i<l; i++) {
413 *deb = (*deb >> (nbu-highBit-1)) & mask;
416 } else if (nb == 32 ) {
417 guint32 mask = 0xffffffff;
418 mask = mask >> (nb-nbu);
419 guint32 *deb = (guint32 *)destination;
420 for(int i = 0; i<l; i++) {
421 *deb = (*deb >> (nbu-highBit-1)) & mask;
425 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
430 // Just to 'see' was was actually read on disk :-(
431 // Some troubles expected
433 // *Try* to deal with the color
434 // ----------------------------
436 // Planar configuration = 0 : Pixels are already RGB
437 // Planar configuration = 1 : 3 planes : R, G, B
438 // Planar configuration = 2 : 1 gray Plane + 3 LUT
440 // Well ... supposed to be !
441 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,PhotometricInterpretation=PALETTE COLOR
442 // and heuristic has to be found :-(
444 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
446 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
447 || (str_PhotometricInterpretation == "MONOCHROME2 ")
448 || (str_PhotometricInterpretation == "RGB")) {
451 int planConf=GetPlanarConfiguration();
453 // Whatever Planar Configuration is, "PALETTE COLOR " implies that we deal with the palette.
454 if (str_PhotometricInterpretation == "PALETTE COLOR ")
459 // Pixels are already RGB
465 if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
467 // need to make RGB Pixels from Planes Y,cB,cR
468 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
469 // for code optimisation
471 int l = GetXSize()*GetYSize();
472 int nbFrames = GetZSize();
474 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
475 unsigned char *x = newDest;
476 unsigned char * a = (unsigned char *)destination;
477 unsigned char * b = a + l;
478 unsigned char * c = b + l;
482 // TODO : Replace by the 'well known'
483 // integer computation counterpart
484 for (int i=0;i<nbFrames;i++) {
485 for (int j=0;j<l; j++) {
486 R= 1.164 *( *a-16) + 1.596 *( *c -128) + 0.5;
487 G= 1.164 *( *a-16) - 0.813 *( *c -128) - 0.392 *(*b -128) + 0.5;
488 B= 1.164 *( *a-16) + 2.017 *( *b -128) + 0.5;
493 if (R>255.0) R=255.0;
494 if (G>255.0) G=255.0;
495 if (B>255.0) B=255.0;
497 *(x++) = (unsigned char)R;
498 *(x++) = (unsigned char)G;
499 *(x++) = (unsigned char)B;
503 memmove(destination,newDest,lgrTotale);
508 // need to make RGB Pixels from Planes R,G,B
510 int l = GetXSize()*GetYSize();
511 int nbFrames = GetZSize();
513 char * newDest = (char*) malloc(lgrTotale);
515 char * a = (char *)destination;
520 // any trick not to have to allocate temporary buffer is welcome ...
522 for (int i=0;i<nbFrames;i++) {
523 for (int j=0;j<l; j++) {
529 memmove(destination,newDest,lgrTotale);
533 // now, it's an RGB image
534 // Lets's write it in the Header
535 std::string spp = "3";
536 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
537 std::string rgb="RGB";
538 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
543 // from Lut R + Lut G + Lut B
545 // we no longer use gdcmHeader::GetLUTRGB
546 // since a lot of images have strange info
547 // in the Lookup Table Descriptors (0028,1101),...
549 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
550 unsigned char * a = (unsigned char *)destination;
552 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
553 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
554 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
556 if (lutR && lutG && lutB ) { // need to make RGB Pixels
558 // and Lut R,Lut G,Lut B
560 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
562 memmove(newDest, destination, l);// move Gray pixels to temp area
564 unsigned char * x = newDest;
567 // See PS 3.3-2003 C.11.1.1.2 p 619
570 if ( GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3
573 // if we get a black image, let's just remove the '+1'
575 // if it works, we shall have to check the 3 Palettes
576 // to see which byte is ==0 (first one, on second one)
578 for (int i=0;i<l; i++) {
579 j=newDest[i]*mult +1;
587 // now, it's an RGB image
588 std::string spp = "3";
589 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
590 std::string rgb="RGB";
591 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
593 } else { // need to make RGB Pixels (?)
594 // from grey Pixels (?!)
595 // and Gray Lut (!?!)
596 unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
597 // Well . I'll wait till I find such an image
607 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
612 * \brief Swap the bytes, according to swap code.
613 * \warning not end user intended
614 * @param im area to deal with
615 * @param swap swap code
616 * @param lgr Area Length
617 * @param nb Pixels Bit number
620 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
638 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
639 | ((((unsigned short int*)im)[i])<<8);
643 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
654 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
655 fort =((unsigned long int*)im)[i]>>16;
656 fort= (fort>>8) | (fort<<8);
657 faible=(faible>>8) | (faible<<8);
659 ((unsigned long int*)im)[i]=(s32<<16)|fort;
665 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
666 fort=((unsigned long int*)im)[i]>>16;
667 fort= (fort>>8) | (fort<<8);
668 faible=(faible>>8) | (faible<<8);
670 ((unsigned long int*)im)[i]=(s32<<16)|faible;
676 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
677 fort=((unsigned long int*)im)[i]>>16;
679 ((unsigned long int*)im)[i]=(s32<<16)|fort;
684 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
689 /////////////////////////////////////////////////////////////////
693 * \warning doit-etre etre publique ?
694 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
697 * @param ExpectedSize
699 * @return integer acts as a boolean
701 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
702 SetImageDataSize(ExpectedSize);
704 lgrTotale = ExpectedSize;
709 /////////////////////////////////////////////////////////////////
712 * \brief Sets the Pixel Area size in the Header
713 * --> not-for-rats function
715 * \warning WARNING doit-etre etre publique ?
716 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
718 * @param ImageDataSize new Pixel Area Size
719 * warning : nothing else is checked
722 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
723 std::string content1;
725 // Assumes ElValue (0x7fe0, 0x0010) exists ...
726 sprintf(car,"%d",ImageDataSize);
728 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
729 a->SetLength(ImageDataSize);
732 sprintf(car,"%d",ImageDataSize);
734 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
738 /////////////////////////////////////////////////////////////////
741 * \brief Ecrit sur disque les pixels d'UNE image
742 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
743 * Ca sera à l'utilisateur d'appeler son Reader correctement
744 * (Equivalent a IdImaWriteRawFile)
750 int gdcmFile::WriteRawData (std::string fileName) {
752 fp1 = fopen(fileName.c_str(),"wb");
754 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
757 fwrite (PixelData,lgrTotale, 1, fp1);
762 /////////////////////////////////////////////////////////////////
765 * \brief Ecrit sur disque UNE image Dicom
766 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
767 * Ca fonctionnera correctement (?) sur processeur Intel
768 * (Equivalent a IdDcmWrite)
771 * @return int acts as a boolean
774 int gdcmFile::WriteDcmImplVR (std::string fileName) {
775 return WriteBase(fileName, ImplicitVR);
778 /////////////////////////////////////////////////////////////////
783 * @return int acts as a boolean
786 int gdcmFile::WriteDcmImplVR (const char* fileName) {
787 return WriteDcmImplVR (std::string (fileName));
790 /////////////////////////////////////////////////////////////////
795 * @return int acts as a boolean
798 int gdcmFile::WriteDcmExplVR (std::string fileName) {
799 return WriteBase(fileName, ExplicitVR);
802 /////////////////////////////////////////////////////////////////
805 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
806 * (a l'attention des logiciels cliniques
807 * qui ne prennent en entrée QUE des images ACR ...
808 * \warning si un header DICOM est fourni en entree,
809 * les groupes < 0x0008 et les groupes impairs sont ignores)
810 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
811 * Ca fonctionnera correctement (?) sur processeur Intel
812 * (Equivalent a IdDcmWrite)
815 * @return int acts as a boolean
818 int gdcmFile::WriteAcr (std::string fileName) {
819 return WriteBase(fileName, ACR);
822 /////////////////////////////////////////////////////////////////
829 * @return int acts as a boolean
831 int gdcmFile::WriteBase (std::string FileName, FileType type) {
834 fp1 = fopen(FileName.c_str(),"wb");
836 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
840 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
842 // writing Dicom File Preamble
843 filePreamble=(char*)calloc(128,1);
844 fwrite(filePreamble,128,1,fp1);
845 fwrite("DICM",4,1,fp1);
848 // --------------------------------------------------------------
849 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
851 // if recognition code tells us we dealt with a LibIDO image
852 // we reproduce on disk the switch between lineNumber and columnNumber
853 // just before writting ...
855 std::string rows, columns;
856 if ( filetype == ACR_LIBIDO){
857 rows = GetPubElValByNumber(0x0028, 0x0010);
858 columns = GetPubElValByNumber(0x0028, 0x0011);
859 SetPubElValByNumber(columns, 0x0028, 0x0010);
860 SetPubElValByNumber(rows , 0x0028, 0x0011);
862 // ----------------- End of Special Patch ----------------
864 gdcmHeader::Write(fp1, type);
866 // --------------------------------------------------------------
867 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
869 // ...and we restore the Header to be Dicom Compliant again
870 // just after writting
872 if (filetype == ACR_LIBIDO){
873 SetPubElValByNumber(rows , 0x0028, 0x0010);
874 SetPubElValByNumber(columns, 0x0028, 0x0011);
876 // ----------------- End of Special Patch ----------------
878 fwrite(PixelData, lgrTotale, 1, fp1);