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();
60 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
61 if ( str_PhotometricInterpretation == "PALETTE COLOR "
62 || str_PhotometricInterpretation == "YBR_FULL") { // --> some more to be added !!
66 // see PS 3.3-2003 : C.7.6.3.2.1
76 // YBR_FULL_422 (no LUT, no Palette)
82 // ex : gdcm-US-ALOKA-16.dcm
83 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
84 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
85 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
87 // ex : US-PAL-8-10x-echo.dcm, 8BitsRunLengthColor.dcm
88 // 0028|1201 [OW] [Red Palette Color Lookup Table Data]
89 // 0028|1202 [OW] [Green Palette Color Lookup Table Data]
90 // 0028|1203 [OW] [Blue Palette Color Lookup Table Data]
92 // ex : OT-PAL-8-face.dcm
93 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
94 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
95 // 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 // ------------------------- Uncompressed File
133 IsImplicitVRLittleEndianTransferSyntax() ||
134 IsExplicitVRLittleEndianTransferSyntax() ||
135 IsExplicitVRBigEndianTransferSyntax() ||
136 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
138 size_t ItemRead = fread(destination, lgrTotale, 1, fp);
139 if ( ItemRead != 1 ) {
148 // ------------------------ Compressed File .
151 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
152 if (str_nb == GDCM_UNFOUND ) {
155 nb = atoi(str_nb.c_str() );
156 if (nb == 12) nb =16;
160 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
163 // ------------------------------- JPEG LossLess : call to Jpeg Libido
165 if (IsJPEGLossless() && GetZSize() == 1) {
167 int ln; // Position on begining of Jpeg Pixels
168 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : Basic Offset Table Item
171 ln=SwapLong(ln); // Item length
172 fseek(fp,ln,SEEK_CUR); // skipping Basic Offset Table ('ln' bytes)
173 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : First fragment Item Tag
174 fread(&ln,4,1,fp); // First fragment length (just to know)
178 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
179 // (We use the LibIDO one :-(
184 int * dataJpg = jpg->DataImg;
189 unsigned short *dest = (unsigned short *)destination;
190 for (int i=0; i<taille; i++) {
191 *((unsigned char *)dest+i) = *(dataJpg +i);
198 unsigned short *dest = (unsigned short *)destination;
199 for (int i=0; i<taille; i++) {
200 *((unsigned short *)dest+i) = *(dataJpg +i);
205 _IdDcmJpegFree (jpg);
209 // ------------------------------- RLE
211 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
212 int res = (bool)gdcm_read_RLE_file (destination);
216 // ------------------------------- JPEG Lossy : call to IJG 6b
218 long fragmentBegining; // for ftell, fseek
219 bool b = gdcmHeader::IsJPEG2000();
222 guint16 ItemTagGr,ItemTagEl;
223 int ln; // Position on begining of Jpeg Pixels
225 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
226 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
228 ItemTagGr=SwapShort(ItemTagGr);
229 ItemTagEl=SwapShort(ItemTagEl);
233 ln=SwapLong(ln); // Basic Offset Table Item length
236 // What is it used for ?!?
237 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
238 fread(BasicOffsetTableItemValue,ln,1,fp);
241 // first Fragment initialisation
242 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
243 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
245 ItemTagGr=SwapShort(ItemTagGr);
246 ItemTagEl=SwapShort(ItemTagEl);
249 // parsing fragments until Sequence Delim. Tag found
250 //unsigned short *dest = (unsigned short *)destination;
252 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
255 ln=SwapLong(ln); // Fragment Item length
257 // FIXME : multi fragments
258 fragmentBegining=ftell(fp);
262 res = (bool)gdcm_read_JPEG2000_file (destination); // Reading Fragment pixels
264 else if (IsJPEGLossless()) {
265 // ------------- call to LibIDO Jpeg for each Frame/fragment
267 // Warning : Works only if there is one fragment per frame
268 // (Or a single fragment for the multiframe file)
269 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
270 // (We use the LibIDO one :-(
275 int * dataJpg = jpg->DataImg;
276 unsigned short *dest = (unsigned short *)destination;
280 for (int i=0; i<taille; i++) {
281 *((unsigned char *)dest+i) = *(dataJpg +i);
288 for (int i=0; i<taille; i++) {
289 *((unsigned short *)dest+i) = *(dataJpg +i);
294 _IdDcmJpegFree (jpg);
296 } // ------------------------------------- endif (IsJPEGLossless())
299 if (GetBitsStored() == 8) {
300 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
302 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
307 // FIXME : will work only when each fragment corresponds to a Frame :-(
309 destination = (char *)destination + taille * nBytes; // location in user's memory
310 // for next fragment (if any)
311 // TODO : find a suitable file (multifragment/single Frame Jpeg file) to check
313 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
314 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
316 ItemTagGr = ItemTagEl =0;
317 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
318 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
320 ItemTagGr=SwapShort(ItemTagGr);
321 ItemTagEl=SwapShort(ItemTagEl);
324 //(char *) destination += taille * nBytes;
325 //std::cout << "destination" << destination << std::endl;
333 * \brief Allocates necessary memory, copies the pixel data
334 * (image[s]/volume[s]) to newly allocated zone.
335 * @return Pointer to newly allocated pixel data.
336 * \ NULL if alloc fails
338 void * gdcmFile::GetImageData (void) {
339 PixelData = (void *) malloc(lgrTotale);
341 GetImageDataIntoVector(PixelData, lgrTotale);
347 * \brief Copies at most MaxSize bytes of pixel data to caller's
349 * @param destination Address (in caller's memory space) at which the
350 * pixel data should be copied
351 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
352 * is not sufficient to hold the pixel data the copy is not
353 * executed (i.e. no partial copy).
354 * @return On success, the number of bytes actually copied. Zero on
355 * failure e.g. MaxSize is lower than necessary.
358 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
360 int nb, nbu, highBit, signe;
361 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
363 if ( lgrTotale > MaxSize ) {
364 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
365 "than caller's expected MaxSize");
369 (void)ReadPixelData(destination);
371 // Nombre de Bits Alloues pour le stockage d'un Pixel
372 str_nb = GetPubElValByNumber(0x0028,0x0100);
373 if (str_nb == GDCM_UNFOUND ) {
376 nb = atoi(str_nb.c_str() );
379 // Nombre de Bits Utilises
380 str_nbu=GetPubElValByNumber(0x0028,0x0101);
381 if (str_nbu == GDCM_UNFOUND ) {
384 nbu = atoi(str_nbu.c_str() );
387 // Position du Bit de Poids Fort
388 str_highBit=GetPubElValByNumber(0x0028,0x0102);
389 if (str_highBit == GDCM_UNFOUND ) {
392 highBit = atoi(str_highBit.c_str() );
396 str_signe=GetPubElValByNumber(0x0028,0x0103);
397 if (str_signe == GDCM_UNFOUND ) {
400 signe = atoi(str_signe.c_str() );
403 // re arange bytes inside the integer
405 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
407 // re arange bits inside the bytes
409 int l = (int)lgrTotale / (nb/8);
411 guint16 mask = 0xffff;
412 mask = mask >> (nb-nbu);
413 guint16 *deb = (guint16 *)destination;
414 for(int i = 0; i<l; i++) {
415 *deb = (*deb >> (nbu-highBit-1)) & mask;
418 } else if (nb == 32 ) {
419 guint32 mask = 0xffffffff;
420 mask = mask >> (nb-nbu);
421 guint32 *deb = (guint32 *)destination;
422 for(int i = 0; i<l; i++) {
423 *deb = (*deb >> (nbu-highBit-1)) & mask;
427 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
432 // *Try* to deal with the color
433 // --------------------------
435 std::string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
437 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
438 || (str_PhotometricInterpretation == "MONOCHROME2 ")
439 || (str_PhotometricInterpretation == "RGB")) {
442 int planConf=GetPlanarConfiguration();
444 if( str_PhotometricInterpretation!="PALETTE COLOR" && planConf == 0)
445 planConf=2; // Sorry, this is an heuristic
449 // Pixels are already RGB
453 // need to make RGB Pixels from Planes R,G,B
455 int l = lgrTotale/3 ;
457 char * a = (char *)destination;
460 char * newDest = (char*) malloc(lgrTotale);
462 // any trick not to have to allocate temporary buffer is welcome ...
464 for (int j=0;j<l; j++) {
469 memmove(destination,newDest,lgrTotale);
471 // now, it's an RGB image
472 std::string spp = "3";
473 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
474 std::string rgb="RGB";
475 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
480 // from Lut R + Lut G + Lut B
482 // we no longer use gdcmHeader::GetLUTRGB
483 // since a lot of images have wrong info
484 // in the Lookup Table Descriptors (0028,1101),...
486 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
487 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
488 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
490 if (lutR && lutG && lutB ) { // need to make RGB Pixels
492 // and Lut R,Lut G,Lut B
493 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
495 memmove(newDest, destination, l);// move Gray pixels to temp area
497 unsigned char * x = newDest;
498 unsigned char * a = (unsigned char *)destination;
500 for (int i=0;i<l; i++) {
501 j=newDest[i]*2; // Who can explain *why* we have to skip bytes
508 // now, it's an RGB image
509 std::string spp = "3";
510 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
511 std::string rgb="RGB";
512 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
514 } else { // need to make RGB Pixels (?)
515 // from grey Pixels (?!)
516 // and Gray Lut (!?!)
517 unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
518 // Well . I'll wait till I find such an image
528 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
533 * \brief Swap the bytes, according to swap code.
534 * \warning not end user intended
535 * @param im area to deal with
536 * @param swap swap code
537 * @param lgr Area Length
538 * @param nb Pixels Bit number
541 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
559 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
560 | ((((unsigned short int*)im)[i])<<8);
564 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
575 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
576 fort =((unsigned long int*)im)[i]>>16;
577 fort= (fort>>8) | (fort<<8);
578 faible=(faible>>8) | (faible<<8);
580 ((unsigned long int*)im)[i]=(s32<<16)|fort;
586 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
587 fort=((unsigned long int*)im)[i]>>16;
588 fort= (fort>>8) | (fort<<8);
589 faible=(faible>>8) | (faible<<8);
591 ((unsigned long int*)im)[i]=(s32<<16)|faible;
597 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
598 fort=((unsigned long int*)im)[i]>>16;
600 ((unsigned long int*)im)[i]=(s32<<16)|fort;
605 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
610 /////////////////////////////////////////////////////////////////
614 * \warning doit-etre etre publique ?
615 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
618 * @param ExpectedSize
620 * @return integer acts as a boolean
622 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
623 SetImageDataSize(ExpectedSize);
625 lgrTotale = ExpectedSize;
630 /////////////////////////////////////////////////////////////////
633 * \brief Sets the Pixel Area size in the Header
634 * --> not-for-rats function
636 * \warning WARNING doit-etre etre publique ?
637 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
639 * @param ImageDataSize new Pixel Area Size
640 * warning : nothing else is checked
643 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
644 std::string content1;
646 // Assumes ElValue (0x7fe0, 0x0010) exists ...
647 sprintf(car,"%d",ImageDataSize);
649 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
650 a->SetLength(ImageDataSize);
653 sprintf(car,"%d",ImageDataSize);
655 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
659 /////////////////////////////////////////////////////////////////
662 * \brief Ecrit sur disque les pixels d'UNE image
663 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
664 * Ca sera à l'utilisateur d'appeler son Reader correctement
665 * (Equivalent a IdImaWriteRawFile)
671 int gdcmFile::WriteRawData (std::string fileName) {
673 fp1 = fopen(fileName.c_str(),"wb");
675 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
678 fwrite (PixelData,lgrTotale, 1, fp1);
683 /////////////////////////////////////////////////////////////////
686 * \brief Ecrit sur disque UNE image Dicom
687 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
688 * Ca fonctionnera correctement (?) sur processeur Intel
689 * (Equivalent a IdDcmWrite)
692 * @return int acts as a boolean
695 int gdcmFile::WriteDcmImplVR (std::string fileName) {
696 return WriteBase(fileName, ImplicitVR);
699 /////////////////////////////////////////////////////////////////
704 * @return int acts as a boolean
707 int gdcmFile::WriteDcmImplVR (const char* fileName) {
708 return WriteDcmImplVR (std::string (fileName));
711 /////////////////////////////////////////////////////////////////
716 * @return int acts as a boolean
719 int gdcmFile::WriteDcmExplVR (std::string fileName) {
720 return WriteBase(fileName, ExplicitVR);
723 /////////////////////////////////////////////////////////////////
726 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
727 * (a l'attention des logiciels cliniques
728 * qui ne prennent en entrée QUE des images ACR ...
729 * \warning si un header DICOM est fourni en entree,
730 * les groupes < 0x0008 et les groupes impairs sont ignores)
731 * \warning 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::WriteAcr (std::string fileName) {
740 return WriteBase(fileName, ACR);
743 /////////////////////////////////////////////////////////////////
750 * @return int acts as a boolean
752 int gdcmFile::WriteBase (std::string FileName, FileType type) {
755 fp1 = fopen(FileName.c_str(),"wb");
757 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
761 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
763 // writing Dicom File Preamble
764 filePreamble=(char*)calloc(128,1);
765 fwrite(filePreamble,128,1,fp1);
766 fwrite("DICM",4,1,fp1);
769 // --------------------------------------------------------------
770 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
772 // if recognition code tells us we dealt with a LibIDO image
773 // we reproduce on disk the switch between lineNumber and columnNumber
774 // just before writting ...
776 std::string rows, columns;
777 if ( filetype == ACR_LIBIDO){
778 rows = GetPubElValByNumber(0x0028, 0x0010);
779 columns = GetPubElValByNumber(0x0028, 0x0011);
780 SetPubElValByNumber(columns, 0x0028, 0x0010);
781 SetPubElValByNumber(rows , 0x0028, 0x0011);
783 // ----------------- End of Special Patch ----------------
785 gdcmHeader::Write(fp1, type);
787 // --------------------------------------------------------------
788 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
790 // ...and we restore the Header to be Dicom Compliant again
791 // just after writting
793 if (filetype == ACR_LIBIDO){
794 SetPubElValByNumber(rows , 0x0028, 0x0010);
795 SetPubElValByNumber(columns, 0x0028, 0x0011);
797 // ----------------- End of Special Patch ----------------
799 fwrite(PixelData, lgrTotale, 1, fp1);