5 #include "iddcmjpeg.h" // for the 'LibIDO' Jpeg LossLess
8 #define str2num(str, typeNum) *((typeNum *)(str))
10 /////////////////////////////////////////////////////////////////
13 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
14 * file (see SetFileName, SetDcmTag and Write)
15 * Opens (in read only and when possible) an existing file and checks
16 * for DICOM compliance. Returns NULL on failure.
17 * \Note the in-memory representation of all available tags found in
18 * the DICOM header is post-poned to first header information access.
19 * This avoid a double parsing of public part of the header when
20 * one sets an a posteriori shadow dictionary (efficiency can be
21 * seen as a side effect).
23 * @param filename file to be opened for parsing
28 gdcmFile::gdcmFile(string & filename)
29 :gdcmHeader(filename.c_str())
31 SetPixelDataSizeFromHeader();
34 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();
63 string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
64 if ( str_PhotometricInterpretation == "PALETTE COLOR "
65 || str_PhotometricInterpretation == "YBR_FULL") { // --> some more to be added !!
69 // remaining to check :
70 // str_PhotometricInterpretation == "YBR_FULL"
71 // str_PhotometricInterpretation == "YBR_FULL_422" (no LUT, no Palette)
72 // -->and some more !!
75 /////////////////////////////////////////////////////////////////
78 * \brief Returns the size (in bytes) of required memory to hold
79 * the pixel data represented in this file.
80 * @return The size of pixel data in bytes.
82 size_t gdcmFile::GetImageDataSize(void) {
87 /////////////////////////////////////////////////////////////////
90 * \brief Parse pixel data from disk and *prints* the result
91 * \ For multi-fragment Jpeg files checking purpose *only*
92 * \ Allows to 'see' if the file *does* conform
93 * \ (some of them do not)
94 * \ with Dicom Part 3, Annex A (PS 3.5-2003, page 58)
97 bool gdcmFile::ParsePixelData(void) {
101 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
107 IsImplicitVRLittleEndianTransferSyntax() ||
108 IsExplicitVRLittleEndianTransferSyntax() ||
109 IsExplicitVRBigEndianTransferSyntax() ||
110 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
112 printf ("gdcmFile::ParsePixelData : non JPEG File\n");
117 string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
118 if (str_nb == "gdcm::Unfound" ) {
121 nb = atoi(str_nb.c_str() );
122 if (nb == 12) nb =16;
126 //int taille = GetXSize() * GetYSize() * GetZSize() * GetSamplesPerPixel();
127 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
129 printf ("Checking the Dicom-Jpeg/RLE Pixels\n");
131 // ------------------------------- for Parsing : Position on begining of Jpeg Pixels
132 guint16 ItemTagGr,ItemTagEl;
135 char * destination = NULL;
137 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Basic Offset Table Item Tag Gr
138 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Basic Offset Table Item Tag El
140 ItemTagGr=SwapShort(ItemTagGr);
141 ItemTagEl=SwapShort(ItemTagEl);
143 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
144 ftellRes,ItemTagGr,ItemTagEl );
148 ln=SwapLong(ln); // Basic Offset Table Item Lentgh
149 printf("at %x : Basic Offset Table Item Lentgh (??) %d x(%08x)\n",
152 // What is it used for ??
153 char * BasicOffsetTableItemValue= (char *)malloc(ln+1);
154 fread(BasicOffsetTableItemValue,ln,1,fp);
156 for (int i=0;i<ln;i+=4){
157 a=str2num(&BasicOffsetTableItemValue[i],guint32);
158 printf(" x(%08x) %d\n",a,a);
163 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
164 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
166 ItemTagGr=SwapShort(ItemTagGr);
167 ItemTagEl=SwapShort(ItemTagEl);
169 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
170 ftellRes,ItemTagGr,ItemTagEl );
172 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) { // Parse fragments
177 ln=SwapLong(ln); // length
178 printf(" at %x : fragment length %d x(%08x)\n",
181 destination += taille * nBytes; // location in user's memory
183 printf (" Destination will be x(%x) = %d \n",
184 destination,destination );
186 fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels
189 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
190 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
192 ItemTagGr=SwapShort(ItemTagGr);
193 ItemTagEl=SwapShort(ItemTagEl);
195 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
196 ftellRes,ItemTagGr,ItemTagEl );
203 /////////////////////////////////////////////////////////////////
206 * \brief Read pixel data from disk (optionaly decompressing) into the
207 * caller specified memory location.
208 * @param destination where the pixel data should be stored.
211 bool gdcmFile::ReadPixelData(void* destination) {
216 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
221 // ------------------------------- Uncompressed File
224 IsImplicitVRLittleEndianTransferSyntax() ||
225 IsExplicitVRLittleEndianTransferSyntax() ||
226 IsExplicitVRBigEndianTransferSyntax() ||
227 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
229 size_t ItemRead = fread(destination, lgrTotale, 1, fp);
230 if ( ItemRead != 1 ) {
239 // ----------------------------- JPEG Compressed File .
242 string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
243 if (str_nb == "gdcm::Unfound" ) {
246 nb = atoi(str_nb.c_str() );
247 if (nb == 12) nb =16;
251 //int taille = GetXSize() * GetYSize() * GetZSize() * GetSamplesPerPixel();
252 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
255 // ------------------------------- JPEG LossLess : call to Jpeg Libido
257 if (IsJPEGLossless() && GetZSize() == 1) {
259 int ln; // Position on begining of Jpeg Pixels
260 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : Basic Offset Table Item
263 ln=SwapLong(ln); // Item length
264 fseek(fp,ln,SEEK_CUR); // skipping Basic Offset Table ('ln' bytes)
265 fseek(fp,4,SEEK_CUR); // skipping (fffe,e000) : First fragment Item Tag
266 fread(&ln,4,1,fp); // First fragment length (just to know)
270 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
271 // (We use the LibIDO one :-(
276 int * dataJpg = jpg->DataImg;
281 unsigned short *dest = (unsigned short *)destination;
282 for (int i=0; i<taille; i++) {
283 *((unsigned char *)dest+i) = *(dataJpg +i);
290 unsigned short *dest = (unsigned short *)destination;
291 for (int i=0; i<taille; i++) {
292 *((unsigned short *)dest+i) = *(dataJpg +i);
297 _IdDcmJpegFree (jpg);
301 // ------------------------------- JPEG Lossy : call to IJG 6b
303 long fragmentBegining; // for ftell, fseek
307 a = gdcmHeader::IsRLELossLessTransferSyntax();
309 bool b = gdcmHeader::IsJPEG2000();
312 guint16 ItemTagGr,ItemTagEl;
313 int ln; // Position on begining of Jpeg Pixels
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);
323 ln=SwapLong(ln); // Basic Offset Table Item length
326 // What is it used for ?!?
327 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
328 fread(BasicOffsetTableItemValue,ln,1,fp);
331 // first Fragment initialisation
332 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
333 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
335 ItemTagGr=SwapShort(ItemTagGr);
336 ItemTagEl=SwapShort(ItemTagEl);
339 // parsing fragments until Sequence Delim. Tag found
340 //unsigned short *dest = (unsigned short *)destination;
342 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
345 ln=SwapLong(ln); // Fragment Item length
347 // FIXME : multi fragments
348 fragmentBegining=ftell(fp);
351 res = (bool)gdcm_read_RLE_file (destination); // Reading Fragment pixels
353 res = (bool)gdcm_read_JPEG2000_file (destination); // Reading Fragment pixels
355 else if (IsJPEGLossless()) { // ------------- call to LibIDO Jpeg for each Frame/fragment
357 // Warning : Works only if there is one fragment per frame
358 // (Or a single fragment for the multiframe file)
359 ClbJpeg* jpg = _IdDcmJpegRead(fp); // TODO : find a 'full' one.
360 // (We use the LibIDO one :-(
365 int * dataJpg = jpg->DataImg;
366 unsigned short *dest = (unsigned short *)destination;
370 for (int i=0; i<taille; i++) {
371 *((unsigned char *)dest+i) = *(dataJpg +i);
378 for (int i=0; i<taille; i++) {
379 *((unsigned short *)dest+i) = *(dataJpg +i);
384 _IdDcmJpegFree (jpg);
386 } // ------------------------------------- endif (IsJPEGLossless())
389 if (GetBitsStored() == 8) {
390 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
392 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
397 // FIXME : will work only when each fragment corresponds to a Frame :-(
399 (char *) destination += taille * nBytes; // location in user's memory
400 // for next fragment (if any)
401 // TODO : find a suitable file (multifragment/single Frame Jpeg file) to check
403 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
404 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
406 ItemTagGr = ItemTagEl =0;
407 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
408 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
410 ItemTagGr=SwapShort(ItemTagGr);
411 ItemTagEl=SwapShort(ItemTagEl);
414 //(char *) destination += taille * nBytes;
415 //cout << "destination" << destination << "\n";
423 * \brief Allocates necessary memory, copies the pixel data
424 * (image[s]/volume[s]) to newly allocated zone.
425 * @return Pointer to newly allocated pixel data.
426 * \ NULL if alloc fails
428 void * gdcmFile::GetImageData (void) {
429 PixelData = (void *) malloc(lgrTotale);
431 GetImageDataIntoVector(PixelData, lgrTotale);
437 * \brief Copies at most MaxSize bytes of pixel data to caller's
439 * @param destination Address (in caller's memory space) at which the
440 * pixel data should be copied
441 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
442 * is not sufficient to hold the pixel data the copy is not
443 * executed (i.e. no partial copy).
444 * @return On success, the number of bytes actually copied. Zero on
445 * failure e.g. MaxSize is lower than necessary.
448 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
450 int nb, nbu, highBit, signe;
451 string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
453 if ( lgrTotale > MaxSize ) {
454 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
455 "than caller's expected MaxSize");
459 (void)ReadPixelData(destination);
461 // Nombre de Bits Alloues pour le stockage d'un Pixel
462 str_nb = GetPubElValByNumber(0x0028,0x0100);
463 if (str_nb == "gdcm::Unfound" ) {
466 nb = atoi(str_nb.c_str() );
469 // Nombre de Bits Utilises
470 str_nbu=GetPubElValByNumber(0x0028,0x0101);
471 if (str_nbu == "gdcm::Unfound" ) {
474 nbu = atoi(str_nbu.c_str() );
477 // Position du Bit de Poids Fort
478 str_highBit=GetPubElValByNumber(0x0028,0x0102);
479 if (str_highBit == "gdcm::Unfound" ) {
482 highBit = atoi(str_highBit.c_str() );
486 str_signe=GetPubElValByNumber(0x0028,0x0103);
487 if (str_signe == "gdcm::Unfound" ) {
490 signe = atoi(str_signe.c_str() );
493 // re arange bytes inside the integer
495 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
497 // re arange bits inside the bytes
499 int l = (int)lgrTotale / (nb/8);
501 guint16 mask = 0xffff;
502 mask = mask >> (nb-nbu);
503 guint16 *deb = (guint16 *)destination;
504 for(int i = 0; i<l; i++) {
505 *deb = (*deb >> (nbu-highBit-1)) & mask;
508 } else if (nb == 32 ) {
509 guint32 mask = 0xffffffff;
510 mask = mask >> (nb-nbu);
511 guint32 *deb = (guint32 *)destination;
512 for(int i = 0; i<l; i++) {
513 *deb = (*deb >> (nbu-highBit-1)) & mask;
517 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
522 // Try to deal with the color
523 // --------------------------
525 string str_PhotometricInterpretation = gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
527 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
528 || (str_PhotometricInterpretation == "MONOCHROME2 ")
529 || (str_PhotometricInterpretation == "RGB")) {
533 switch ( GetPlanarConfiguration() ) {
535 // Pixels are already RGB
539 // need to make RGB Pixels from Planes R,G,B
541 int l = lgrTotale/3 ;
543 char * a = (char *)destination;
546 char * newDest = (char*) malloc(lgrTotale);
548 // any trick not to have to allocate temporary buffer is welcome ...
550 for (int j=0;j<l; j++) {
555 memmove(destination,newDest,lgrTotale);
557 // now, it's an RGB image
559 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
561 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
566 // from Lut R + Lut G + Lut B
568 // we no longer use gdcmHeader::GetLUTRGB
569 // since a lot of images have wrong info
570 // in the Lookup Table Descriptors (0028,1101),...
572 unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
573 unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
574 unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
576 if (lutR && lutG && lutB ) { // need to make RGB Pixels
578 // and Lut R,Lut G,Lut B
579 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
581 memmove(newDest, destination, l);// move Gray pixels to temp area
583 unsigned char * x = newDest;
584 unsigned char * a = (unsigned char *)destination;
586 for (int i=0;i<l; i++) {
587 j=newDest[i]*2; // Who can explain *why* we have to skip bytes
594 // now, it's an RGB image
596 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
598 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
600 } else { // need to make RGB Pixels (?)
601 // from grey Pixels (?!)
602 // and Gray Lut (!?!)
603 unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
604 // Well . I'll wait till I find such an image
614 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
619 * \brief Swap the bytes, according to swap code.
620 * \warning not end user intended
621 * @param im area to deal with
622 * @param swap swap code
623 * @param lgr Area Length
624 * @param nb Pixels Bit number
627 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
645 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
646 | ((((unsigned short int*)im)[i])<<8);
650 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
661 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
662 fort =((unsigned long int*)im)[i]>>16;
663 fort= (fort>>8) | (fort<<8);
664 faible=(faible>>8) | (faible<<8);
666 ((unsigned long int*)im)[i]=(s32<<16)|fort;
672 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
673 fort=((unsigned long int*)im)[i]>>16;
674 fort= (fort>>8) | (fort<<8);
675 faible=(faible>>8) | (faible<<8);
677 ((unsigned long int*)im)[i]=(s32<<16)|faible;
683 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
684 fort=((unsigned long int*)im)[i]>>16;
686 ((unsigned long int*)im)[i]=(s32<<16)|fort;
691 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
696 /////////////////////////////////////////////////////////////////
700 * \warning doit-etre etre publique ?
701 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
704 * @param ExpectedSize
706 * @return integer acts as a boolean
708 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
709 SetImageDataSize(ExpectedSize);
711 lgrTotale = ExpectedSize;
716 /////////////////////////////////////////////////////////////////
719 * \brief Sets the Pixel Area size in the Header
720 * --> not-for-rats function
722 * \warning WARNING doit-etre etre publique ?
723 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
725 * @param ImageDataSize new Pixel Area Size
726 * warning : nothing else is checked
729 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
732 // Assumes ElValue (0x7fe0, 0x0010) exists ...
733 sprintf(car,"%d",ImageDataSize);
735 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
736 a->SetLength(ImageDataSize);
739 sprintf(car,"%d",ImageDataSize);
741 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
745 /////////////////////////////////////////////////////////////////
748 * \brief Ecrit sur disque les pixels d'UNE image
749 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
750 * Ca sera à l'utilisateur d'appeler son Reader correctement
751 * (Equivalent a IdImaWriteRawFile)
757 int gdcmFile::WriteRawData (string fileName) {
759 fp1 = fopen(fileName.c_str(),"wb");
761 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
764 fwrite (PixelData,lgrTotale, 1, fp1);
769 /////////////////////////////////////////////////////////////////
772 * \brief Ecrit sur disque UNE image Dicom
773 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
774 * Ca fonctionnera correctement (?) sur processeur Intel
775 * (Equivalent a IdDcmWrite)
778 * @return int acts as a boolean
781 int gdcmFile::WriteDcmImplVR (string fileName) {
782 return WriteBase(fileName, ImplicitVR);
785 /////////////////////////////////////////////////////////////////
790 * @return int acts as a boolean
793 int gdcmFile::WriteDcmImplVR (const char* fileName) {
794 return WriteDcmImplVR (string (fileName));
797 /////////////////////////////////////////////////////////////////
802 * @return int acts as a boolean
805 int gdcmFile::WriteDcmExplVR (string fileName) {
806 return WriteBase(fileName, ExplicitVR);
809 /////////////////////////////////////////////////////////////////
812 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
813 * (a l'attention des logiciels cliniques
814 * qui ne prennent en entrée QUE des images ACR ...
815 * \warning si un header DICOM est fourni en entree,
816 * les groupes < 0x0008 et les groupes impairs sont ignores)
817 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
818 * Ca fonctionnera correctement (?) sur processeur Intel
819 * (Equivalent a IdDcmWrite)
822 * @return int acts as a boolean
825 int gdcmFile::WriteAcr (string fileName) {
826 return WriteBase(fileName, ACR);
829 /////////////////////////////////////////////////////////////////
836 * @return int acts as a boolean
838 int gdcmFile::WriteBase (string FileName, FileType type) {
841 fp1 = fopen(FileName.c_str(),"wb");
843 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
847 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
849 // writing Dicom File Preamble
850 filePreamble=(char*)calloc(128,1);
851 fwrite(filePreamble,128,1,fp1);
852 fwrite("DICM",4,1,fp1);
855 gdcmHeader::Write(fp1, type);
856 fwrite(PixelData, lgrTotale, 1, fp1);