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) {
52 str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
53 if (str_nb == GDCM_UNFOUND ) {
56 nb = atoi(str_nb.c_str() );
59 lgrTotale = GetXSize() * GetYSize() * GetZSize()
60 * (nb/8)* GetSamplesPerPixel();
61 std::string str_PhotometricInterpretation =
62 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
63 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 : OT-PAL-8-face.dcm
90 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
91 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
92 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
95 /////////////////////////////////////////////////////////////////
98 * \brief Returns the size (in bytes) of required memory to hold
99 * the pixel data represented in this file.
100 * @return The size of pixel data in bytes.
103 size_t gdcmFile::GetImageDataSize(void) {
108 /////////////////////////////////////////////////////////////////
111 * \brief Read pixel data from disk (optionaly decompressing) into the
112 * caller specified memory location.
113 * @param destination where the pixel data should be stored.
116 bool gdcmFile::ReadPixelData(void* destination) {
121 if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
127 // ---------------------- Compacted File (12 Bits Per Pixel)
129 /* unpack 12 Bits pixels into 16 Bits pixels */
130 /* 2 pixels 12bit = [0xABCDEF] */
131 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
133 if (GetBitsAllocated()==12) {
134 int nbPixels = GetXSize()*GetYSize();
135 unsigned char b0, b1, b2;
137 unsigned short int* pdestination = (unsigned short int*)destination;
138 for(int p=0;p<nbPixels;p+=2) {
142 //Two steps is necessary to please VC++
143 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
144 /* A */ /* B */ /* D */
145 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
146 /* F */ /* C */ /* E */
148 // Troubles expected on Big-Endian processors ?
153 // ---------------------- Uncompressed File
156 IsImplicitVRLittleEndianTransferSyntax() ||
157 IsExplicitVRLittleEndianTransferSyntax() ||
158 IsExplicitVRBigEndianTransferSyntax() ||
159 IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
161 size_t ItemRead = fread(destination, GetPixelAreaLength(), 1, fp);
163 if ( ItemRead != 1 ) {
172 // ---------------------- Run Length Encoding
174 if (gdcmHeader::IsRLELossLessTransferSyntax()) {
175 int res = (bool)gdcm_read_RLE_file (destination);
179 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
182 std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
183 if (str_nb == GDCM_UNFOUND ) {
186 nb = atoi(str_nb.c_str() );
187 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
191 int taille = GetXSize() * GetYSize() * GetSamplesPerPixel();
192 long fragmentBegining; // for ftell, fseek
194 bool jpg2000 = IsJPEG2000();
195 bool jpgLossless = IsJPEGLossless();
198 guint16 ItemTagGr,ItemTagEl;
201 // Position on begining of Jpeg Pixels
203 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
204 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
206 ItemTagGr=SwapShort(ItemTagGr);
207 ItemTagEl=SwapShort(ItemTagEl);
211 ln=SwapLong(ln); // Basic Offset Table Item length
214 // What is it used for ?!?
215 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
216 fread(BasicOffsetTableItemValue,ln,1,fp);
219 // first Fragment initialisation
220 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
221 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
223 ItemTagGr=SwapShort(ItemTagGr);
224 ItemTagEl=SwapShort(ItemTagEl);
227 // parsing fragments until Sequence Delim. Tag found
229 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
231 // --- for each Fragment
235 ln=SwapLong(ln); // Fragment Item length
237 fragmentBegining=ftell(fp);
239 if (jpg2000) { // JPEG 2000 : call to ???
241 res = (bool)gdcm_read_JPEG2000_file (destination); // Not Yet written
243 } // ------------------------------------- endif (JPEG2000)
245 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
247 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
248 (unsigned short *)destination,
249 GetPixelSize()*8* GetSamplesPerPixel(),
251 res=1; // in order not to break the loop
253 } // ------------------------------------- endif (JPEGLossless)
255 else { // JPEG Lossy : call to IJG 6b
257 if (GetBitsStored() == 8) {
258 res = (bool)gdcm_read_JPEG_file (destination); // Reading Fragment pixels
260 res = (bool)gdcm_read_JPEG_file12 (destination);// Reading Fragment pixels
262 } // ------------------------------------- endif (JPEGLossy)
266 destination = (char *)destination + taille * nBytes; // location in user's memory
267 // for next fragment (if any)
269 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
270 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
272 ItemTagGr = ItemTagEl =0;
273 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
274 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
276 ItemTagGr=SwapShort(ItemTagGr);
277 ItemTagEl=SwapShort(ItemTagEl);
280 } // endWhile parsing fragments until Sequence Delim. Tag found
287 * \brief Allocates necessary memory, copies the pixel data
288 * (image[s]/volume[s]) to newly allocated zone.
289 * @return Pointer to newly allocated pixel data.
290 * \ NULL if alloc fails
292 void * gdcmFile::GetImageData (void) {
293 PixelData = (void *) malloc(lgrTotale);
295 GetImageDataIntoVector(PixelData, lgrTotale);
301 * \brief Copies at most MaxSize bytes of pixel data to caller's
303 * \warning This function was designed to avoid people that want to build
304 * a volume from an image stack to need first to get the image pixels
305 * and then move them to the volume area.
306 * It's absolutely useless for VTK users since vtk chooses
307 * to invert the lines of an image, that is the last line comes first
308 * (for some axis related reasons?). Hence he will have
309 * to load the image line by line, starting from the end.
310 * VTK users hace to call GetImageData
312 * @param destination Address (in caller's memory space) at which the
313 * pixel data should be copied
314 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
315 * is not sufficient to hold the pixel data the copy is not
316 * executed (i.e. no partial copy).
317 * @return On success, the number of bytes actually copied. Zero on
318 * failure e.g. MaxSize is lower than necessary.
321 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
323 int nb, nbu, highBit, signe;
324 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
326 if ( lgrTotale > MaxSize ) {
327 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
328 "than caller's expected MaxSize");
332 (void)ReadPixelData(destination);
334 // Nombre de Bits Alloues pour le stockage d'un Pixel
335 str_nb = GetPubElValByNumber(0x0028,0x0100);
336 if (str_nb == GDCM_UNFOUND ) {
339 nb = atoi(str_nb.c_str() );
342 // Nombre de Bits Utilises
343 str_nbu=GetPubElValByNumber(0x0028,0x0101);
344 if (str_nbu == GDCM_UNFOUND ) {
347 nbu = atoi(str_nbu.c_str() );
350 // Position du Bit de Poids Fort
351 str_highBit=GetPubElValByNumber(0x0028,0x0102);
352 if (str_highBit == GDCM_UNFOUND ) {
355 highBit = atoi(str_highBit.c_str() );
360 str_signe=GetPubElValByNumber(0x0028,0x0103);
361 if (str_signe == GDCM_UNFOUND ) {
362 signe = 0; // default is unsigned
364 signe = atoi(str_signe.c_str() );
367 // re arange bytes inside the integer
369 SwapZone(destination, GetSwapCode(), lgrTotale, nb);
371 // to avoid pb with some xmedcon breakers images
372 if (nb==16 && nbu<nb && signe==0) {
373 int l = (int)lgrTotale / (nb/8);
374 guint16 *deb = (guint16 *)destination;
375 for(int i = 0; i<l; i++) {
382 // re arange bits inside the bytes
384 int l = (int)lgrTotale / (nb/8);
386 guint16 mask = 0xffff;
387 mask = mask >> (nb-nbu);
388 guint16 *deb = (guint16 *)destination;
389 for(int i = 0; i<l; i++) {
390 *deb = (*deb >> (nbu-highBit-1)) & mask;
393 } else if (nb == 32 ) {
394 guint32 mask = 0xffffffff;
395 mask = mask >> (nb-nbu);
396 guint32 *deb = (guint32 *)destination;
397 for(int i = 0; i<l; i++) {
398 *deb = (*deb >> (nbu-highBit-1)) & mask;
402 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
407 // Just to 'see' what was actually read on disk :-(
408 // Some troubles expected
410 // f2 = fopen("SpuriousFile.raw","wb");
411 // fwrite(destination,lgrTotale,1,f2);
414 // Deal with the color
415 // -------------------
417 std::string str_PhotometricInterpretation =
418 gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
420 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
421 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
425 // Planar configuration = 0 : Pixels are already RGB
426 // Planar configuration = 1 : 3 planes : R, G, B
427 // Planar configuration = 2 : 1 gray Plane + 3 LUT
429 // Well ... supposed to be !
430 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
431 // PhotometricInterpretation=PALETTE COLOR
432 // and heuristic has to be found :-(
434 int planConf=GetPlanarConfiguration(); // 0028,0006
436 // Whatever Planar Configuration is,
437 // "PALETTE COLOR " implies that we deal with the palette.
438 if (str_PhotometricInterpretation == "PALETTE COLOR ")
443 // Pixels are already RGB
449 if (str_PhotometricInterpretation == "YBR_FULL") {
451 // Warning : YBR_FULL_422 acts as RGB
452 // need to make RGB Pixels from Planes Y,cB,cR
453 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
454 // for code optimisation
456 int l = GetXSize()*GetYSize();
457 int nbFrames = GetZSize();
459 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
460 unsigned char *x = newDest;
461 unsigned char * a = (unsigned char *)destination;
462 unsigned char * b = a + l;
463 unsigned char * c = b + l;
467 // TODO : Replace by the 'well known'
468 // integer computation counterpart
469 for (int i=0;i<nbFrames;i++) {
470 for (int j=0;j<l; j++) {
471 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
472 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
473 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
478 if (R>255.0) R=255.0;
479 if (G>255.0) G=255.0;
480 if (B>255.0) B=255.0;
482 *(x++) = (unsigned char)R;
483 *(x++) = (unsigned char)G;
484 *(x++) = (unsigned char)B;
488 memmove(destination,newDest,lgrTotale);
493 // need to make RGB Pixels from Planes R,G,B
494 // (all the Frames at a time)
496 int l = GetXSize()*GetYSize()*GetZSize();
498 char * newDest = (char*) malloc(lgrTotale);
500 char * a = (char *)destination;
504 for (int j=0;j<l; j++) {
510 memmove(destination,newDest,lgrTotale);
518 // from Lut R + Lut G + Lut B
521 unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
522 unsigned char * a = (unsigned char *)destination;
524 unsigned char * lutRGBA = (unsigned char *) GetLUTRGBA();
528 memmove(newDest, destination, l);// move Gray pixels to temp area
530 for (int i=0;i<l; i++) { // Build RGB Pixels
539 // need to make RGB Pixels (?)
540 // from grey Pixels (?!)
541 // and Gray Lut (!?!)
542 // or Segmented Green Palette Color Lookup Table Data and so on
544 // Well . I'll wait till I find such an image
546 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
547 // No idea how to manage it
548 // It seems that *no Dicom Viewer* has any idea :-(
549 // Segmented xxx Palette Color are *more* than 65535 long ?!?
551 // WARNING : quick and dirty trick to produce
552 // a single plane Grey image
553 // See also gdcmHeaderHelper::GetNumberOfScalarComponents()
556 // end of dirty trick
561 // now, it's an RGB image
562 // Lets's write it in the Header
564 // CreateOrReplaceIfExist ?
566 std::string spp = "3"; // Samples Per Pixel
567 gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
568 std::string rgb="RGB "; // Photometric Interpretation
569 gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
570 std::string planConfig = "0"; // Planar Configuration
571 gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
573 // TODO : Drop Palette Color out of the Header?
581 * \brief Swap the bytes, according to swap code.
582 * \warning not end user intended
583 * @param im area to deal with
584 * @param swap swap code
585 * @param lgr Area Length
586 * @param nb Pixels Bit number
589 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
607 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
608 | ((((unsigned short int*)im)[i])<<8);
612 printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
623 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
624 fort =((unsigned long int*)im)[i]>>16;
625 fort= (fort>>8) | (fort<<8);
626 faible=(faible>>8) | (faible<<8);
628 ((unsigned long int*)im)[i]=(s32<<16)|fort;
634 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
635 fort=((unsigned long int*)im)[i]>>16;
636 fort= (fort>>8) | (fort<<8);
637 faible=(faible>>8) | (faible<<8);
639 ((unsigned long int*)im)[i]=(s32<<16)|faible;
645 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
646 fort=((unsigned long int*)im)[i]>>16;
648 ((unsigned long int*)im)[i]=(s32<<16)|fort;
653 printf(" SWAP value (32 bits) not allowed : %d\n", swap);
658 /////////////////////////////////////////////////////////////////
662 * \warning doit-etre etre publique ?
663 * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
666 * @param ExpectedSize
668 * @return integer acts as a boolean
670 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
671 SetImageDataSize(ExpectedSize);
673 lgrTotale = ExpectedSize;
678 /////////////////////////////////////////////////////////////////
681 * \brief Sets the Pixel Area size in the Header
682 * --> not-for-rats function
684 * \warning WARNING doit-etre etre publique ?
685 * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
687 * @param ImageDataSize new Pixel Area Size
688 * warning : nothing else is checked
691 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
692 std::string content1;
694 // Assumes ElValue (0x7fe0, 0x0010) exists ...
695 sprintf(car,"%d",ImageDataSize);
697 gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
698 a->SetLength(ImageDataSize);
701 sprintf(car,"%d",ImageDataSize);
703 SetPubElValByNumber(content1, 0x7fe0, 0x0000);
707 /////////////////////////////////////////////////////////////////
710 * \brief Ecrit sur disque les pixels d'UNE image
711 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
712 * Ca sera à l'utilisateur d'appeler son Reader correctement
713 * (Equivalent a IdImaWriteRawFile)
719 int gdcmFile::WriteRawData (std::string fileName) {
721 fp1 = fopen(fileName.c_str(),"wb");
723 printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
726 fwrite (PixelData,lgrTotale, 1, fp1);
731 /////////////////////////////////////////////////////////////////
734 * \brief Ecrit sur disque UNE image Dicom
735 * Aucun test n'est fait sur l'"Endiannerie" du processeur.
736 * Ca fonctionnera correctement (?) sur processeur Intel
737 * (Equivalent a IdDcmWrite)
740 * @return int acts as a boolean
743 int gdcmFile::WriteDcmImplVR (std::string fileName) {
744 return WriteBase(fileName, ImplicitVR);
747 /////////////////////////////////////////////////////////////////
752 * @return int acts as a boolean
755 int gdcmFile::WriteDcmImplVR (const char* fileName) {
756 return WriteDcmImplVR (std::string (fileName));
759 /////////////////////////////////////////////////////////////////
764 * @return int acts as a boolean
767 int gdcmFile::WriteDcmExplVR (std::string fileName) {
768 return WriteBase(fileName, ExplicitVR);
771 /////////////////////////////////////////////////////////////////
774 * \brief Ecrit au format ACR-NEMA sur disque l'entete et les pixels
775 * (a l'attention des logiciels cliniques
776 * qui ne prennent en entrée QUE des images ACR ...
777 * \warning si un header DICOM est fourni en entree,
778 * les groupes < 0x0008 et les groupes impairs sont ignores)
779 * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
780 * Ca fonctionnera correctement (?) sur processeur Intel
781 * (Equivalent a IdDcmWrite)
784 * @return int acts as a boolean
787 int gdcmFile::WriteAcr (std::string fileName) {
788 return WriteBase(fileName, ACR);
791 /////////////////////////////////////////////////////////////////
798 * @return int acts as a boolean
800 int gdcmFile::WriteBase (std::string FileName, FileType type) {
803 fp1 = fopen(FileName.c_str(),"wb");
805 printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
809 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
811 // writing Dicom File Preamble
812 filePreamble=(char*)calloc(128,1);
813 fwrite(filePreamble,128,1,fp1);
814 fwrite("DICM",4,1,fp1);
817 // --------------------------------------------------------------
818 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
820 // if recognition code tells us we dealt with a LibIDO image
821 // we reproduce on disk the switch between lineNumber and columnNumber
822 // just before writting ...
824 std::string rows, columns;
825 if ( filetype == ACR_LIBIDO){
826 rows = GetPubElValByNumber(0x0028, 0x0010);
827 columns = GetPubElValByNumber(0x0028, 0x0011);
828 SetPubElValByNumber(columns, 0x0028, 0x0010);
829 SetPubElValByNumber(rows , 0x0028, 0x0011);
831 // ----------------- End of Special Patch ----------------
833 gdcmHeader::Write(fp1, type);
835 // --------------------------------------------------------------
836 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
838 // ...and we restore the Header to be Dicom Compliant again
839 // just after writting
841 if (filetype == ACR_LIBIDO){
842 SetPubElValByNumber(rows , 0x0028, 0x0010);
843 SetPubElValByNumber(columns, 0x0028, 0x0011);
845 // ----------------- End of Special Patch ----------------
847 fwrite(PixelData, lgrTotale, 1, fp1);