1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/09/23 10:17:26 $
7 Version: $Revision: 1.128 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.htm for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
20 #include "gdcmDebug.h"
21 #include "jpeg/ljpg/jpegless.h"
23 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
25 //-------------------------------------------------------------------------
26 // Constructor / Destructor
29 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
30 * file (gdcmHeader only deals with the ... header)
31 * Opens (in read only and when possible) an existing file and checks
32 * for DICOM compliance. Returns NULL on failure.
33 * It will be up to the user to load the pixels into memory
34 * (see GetImageData, GetImageDataRaw)
35 * \note the in-memory representation of all available tags found in
36 * the DICOM header is post-poned to first header information access.
37 * This avoid a double parsing of public part of the header when
38 * user sets an a posteriori shadow dictionary (efficiency can be
39 * seen as a side effect).
40 * @param header already built gdcmHeader
42 gdcmFile::gdcmFile(gdcmHeader *header)
51 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
52 * file (gdcmHeader only deals with the ... header)
53 * Opens (in read only and when possible) an existing file and checks
54 * for DICOM compliance. Returns NULL on failure.
55 * It will be up to the user to load the pixels into memory
56 * (see GetImageData, GetImageDataRaw)
57 * \note the in-memory representation of all available tags found in
58 * the DICOM header is post-poned to first header information access.
59 * This avoid a double parsing of public part of the header when
60 * one sets an a posteriori shadow dictionary (efficiency can be
61 * seen as a side effect).
62 * @param filename file to be opened for parsing
64 gdcmFile::gdcmFile(std::string const & filename )
66 Header = new gdcmHeader( filename );
73 * \brief canonical destructor
74 * \note If the gdcmHeader was created by the gdcmFile constructor,
75 * it is destroyed by the gdcmFile
85 DeleteInitialValues();
90 * \brief Sets some initial values for the Constructor
91 * \warning not end user intended
93 void gdcmFile::SaveInitialValues()
96 PixelRead = -1; // no ImageData read yet.
97 LastAllocatedPixelDataLength = 0;
102 InitialPlanConfig = "";
103 InitialBitsAllocated = "";
106 InitialRedLUTDescr = 0;
107 InitialGreenLUTDescr = 0;
108 InitialBlueLUTDescr = 0;
109 InitialRedLUTData = 0;
110 InitialGreenLUTData = 0;
111 InitialBlueLUTData = 0;
113 if ( Header->IsReadable() )
115 SetPixelDataSizeFromHeader();
117 // the following values *may* be modified
118 // by gdcmFile::GetImageDataIntoVectorRaw
119 // we save their initial value.
120 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
121 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
122 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
124 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
125 InitialHighBit = Header->GetEntryByNumber(0x0028,0x0102);
127 // the following entries *may* be removed from the H table
128 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
129 // we keep a pointer on them.
130 InitialRedLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1101);
131 InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
132 InitialBlueLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1103);
134 InitialRedLUTData = Header->GetDocEntryByNumber(0x0028,0x1201);
135 InitialGreenLUTData = Header->GetDocEntryByNumber(0x0028,0x1202);
136 InitialBlueLUTData = Header->GetDocEntryByNumber(0x0028,0x1203);
142 * \brief restores some initial values
143 * \warning not end user intended
145 void gdcmFile::RestoreInitialValues()
147 if ( Header->IsReadable() )
149 // the following values *may* have been modified
150 // by gdcmFile::GetImageDataIntoVectorRaw
151 // we restore their initial value.
152 if ( InitialSpp != "")
153 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
154 if ( InitialPhotInt != "")
155 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
156 if ( InitialPlanConfig != "")
158 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
159 if ( InitialBitsAllocated != "")
160 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
161 if ( InitialHighBit != "")
162 Header->SetEntryByNumber(InitialHighBit,0x0028,0x0102);
164 // the following entries *may* be have been removed from the H table
165 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
168 if (InitialRedLUTDescr)
169 Header->AddEntry(InitialRedLUTDescr);
170 if (InitialGreenLUTDescr)
171 Header->AddEntry(InitialGreenLUTDescr);
172 if (InitialBlueLUTDescr)
173 Header->AddEntry(InitialBlueLUTDescr);
175 if (InitialRedLUTData)
176 Header->AddEntry(InitialBlueLUTDescr);
177 if (InitialGreenLUTData)
178 Header->AddEntry(InitialGreenLUTData);
179 if (InitialBlueLUTData)
180 Header->AddEntry(InitialBlueLUTData);
186 * \brief delete initial values (il they were saved)
187 * of InitialLutDescriptors and InitialLutData
189 void gdcmFile::DeleteInitialValues()
192 // InitialLutDescriptors and InitialLutData
193 // will have to be deleted if the don't belong any longer
194 // to the Header H table when the header is deleted...
196 if ( InitialRedLUTDescr )
197 delete InitialRedLUTDescr;
199 if ( InitialGreenLUTDescr )
200 delete InitialGreenLUTDescr;
202 if ( InitialBlueLUTDescr )
203 delete InitialBlueLUTDescr;
205 if ( InitialRedLUTData )
206 delete InitialRedLUTData;
208 if ( InitialGreenLUTData != NULL)
209 delete InitialGreenLUTData;
211 if ( InitialBlueLUTData != NULL)
212 delete InitialBlueLUTData;
217 * \brief drop palette related initial values -if any-
218 * (InitialLutDescriptors and InitialLutData)
219 * out of header, to make it consistent with the Pixel_Data
220 * as it's loaded in memory
223 //FIXME : Should be nice, if we could let it here.
224 // will be moved to PixelData class
225 // Now, the job is done in gdcmHeader.cxx
228 void gdcmFile::DropInitialValues()
230 gdcmHeader* h=GetHeader();
231 if ( GetEntryByNumber(0x0028,0x0002).c_str()[0] == '3' )
233 // if SamplesPerPixel = 3, sure we don't need any LUT !
234 // Drop 0028|1101, 0028|1102, 0028|1103
235 // Drop 0028|1201, 0028|1202, 0028|1203
237 gdcmDocEntry* e = h->GetDocEntryByNumber(0x0028,0x01101);
240 h->RemoveEntryNoDestroy(e);
242 e = h->GetDocEntryByNumber(0x0028,0x1102);
245 h->RemoveEntryNoDestroy(e);
247 e = h->GetDocEntryByNumber(0x0028,0x1103);
250 h->RemoveEntryNoDestroy(e);
252 e = h->GetDocEntryByNumber(0x0028,0x01201);
255 h->RemoveEntryNoDestroy(e);
257 e = h->GetDocEntryByNumber(0x0028,0x1202);
260 h->RemoveEntryNoDestroy(e);
262 e = h->GetDocEntryByNumber(0x0028,0x1203);
265 h->RemoveEntryNoDestroy(e);
271 //-----------------------------------------------------------------------------
274 //-----------------------------------------------------------------------------
279 * \brief computes the length (in bytes) we must ALLOCATE to receive the
280 * image(s) pixels (multiframes taken into account)
281 * \warning : it is NOT the group 7FE0 length
282 * (no interest for compressed images).
283 * \warning : not end user intended ?
285 void gdcmFile::SetPixelDataSizeFromHeader()
287 // see PS 3.3-2003 : C.7.6.3.2.1
297 // YBR_FULL_422 (no LUT, no Palette)
303 // ex : gdcm-US-ALOKA-16.dcm
304 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
305 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
306 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
308 // ex : OT-PAL-8-face.dcm
309 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
310 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
311 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
313 // Number of "Bits Allocated"
315 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
317 if ( str_nb == GDCM_UNFOUND )
323 nb = atoi( str_nb.c_str() );
330 ImageDataSizeRaw = Header->GetXSize() * Header->GetYSize()
331 * Header->GetZSize() * (nb/8) * Header->GetSamplesPerPixel();
332 std::string str_PhotometricInterpretation =
333 Header->GetEntryByNumber(0x0028,0x0004);
335 // if ( str_PhotometricInterpretation == "PALETTE COLOR " ),
336 // pb when undealt Segmented Palette Color
338 if ( Header->HasLUT() )
346 * \brief - Allocates necessary memory,
347 * - Reads the pixels from disk (uncompress if necessary),
348 * - Transforms YBR pixels, if any, into RGB pixels
349 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
350 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
351 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
352 * @return Pointer to newly allocated pixel data.
353 * NULL if alloc fails
355 uint8_t* gdcmFile::GetImageData()
358 // I need to deallocate Pixel_Data before doing any allocation:
361 if ( LastAllocatedPixelDataLength != ImageDataSize )
364 Pixel_Data = new uint8_t[ImageDataSize];
368 LastAllocatedPixelDataLength = ImageDataSize;
370 // we load the pixels (and transform grey level + LUT into RGB)
371 GetImageDataIntoVector(Pixel_Data, ImageDataSize);
373 // We say the value *is* loaded.
374 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
375 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
377 // Will be 7fe0, 0010 in standard case
378 GetHeader()->SetEntryBinAreaByNumber( Pixel_Data,
379 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
381 PixelRead = 0; // no PixelRaw
389 * Read the pixels from disk (uncompress if necessary),
390 * Transforms YBR pixels, if any, into RGB pixels
391 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
392 * Transforms single Grey plane + 3 Palettes into a RGB Plane
393 * Copies at most MaxSize bytes of pixel data to caller allocated
395 * \warning This function allows people that want to build a volume
396 * from an image stack *not to* have, first to get the image pixels,
397 * and then move them to the volume area.
398 * It's absolutely useless for any VTK user since vtk chooses
399 * to invert the lines of an image, that is the last line comes first
400 * (for some axis related reasons?). Hence he will have
401 * to load the image line by line, starting from the end.
402 * VTK users have to call GetImageData
404 * @param destination Address (in caller's memory space) at which the
405 * pixel data should be copied
406 * @param maxSize Maximum number of bytes to be copied. When MaxSize
407 * is not sufficient to hold the pixel data the copy is not
408 * executed (i.e. no partial copy).
409 * @return On success, the number of bytes actually copied. Zero on
410 * failure e.g. MaxSize is lower than necessary.
412 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
414 GetImageDataIntoVectorRaw (destination, maxSize);
415 PixelRead = 0 ; // =0 : no ImageDataRaw
416 if ( !Header->HasLUT() )
418 return ImageDataSize;
421 // from Lut R + Lut G + Lut B
422 uint8_t *newDest = new uint8_t[ImageDataSize];
423 uint8_t *a = (uint8_t *)destination;
424 uint8_t *lutRGBA = Header->GetLUTRGBA();
429 // move Gray pixels to temp area
430 memmove(newDest, destination, ImageDataSizeRaw);
431 for (size_t i=0; i<ImageDataSizeRaw; ++i)
441 // now, it's an RGB image
442 // Lets's write it in the Header
444 // FIXME : Better use CreateOrReplaceIfExist ?
446 std::string spp = "3"; // Samples Per Pixel
447 Header->SetEntryByNumber(spp,0x0028,0x0002);
448 std::string rgb = "RGB "; // Photometric Interpretation
449 Header->SetEntryByNumber(rgb,0x0028,0x0004);
450 std::string planConfig = "0"; // Planar Configuration
451 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
454 else // GetLUTRGBA() failed
456 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
457 // that are *more* than 65535 long ?!?
458 // No idea how to manage such an image !
459 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
460 // It seems that *no Dicom Viewer* has any idea :-(
462 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
463 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
466 /// \todo Drop Palette Color out of the Header?
467 return ImageDataSize;
472 * \brief Allocates necessary memory,
473 * Transforms YBR pixels (if any) into RGB pixels
474 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
475 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
476 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
477 * @return Pointer to newly allocated pixel data.
478 * \ NULL if alloc fails
480 uint8_t* gdcmFile::GetImageDataRaw ()
483 if ( Header->HasLUT() )
484 /// \todo Let gdcmHeader user a chance to get the right value
485 imgDataSize = ImageDataSizeRaw;
487 imgDataSize = ImageDataSize;
490 // I need to deallocate Pixel_Data before doing any allocation:
493 if ( LastAllocatedPixelDataLength != imgDataSize )
496 Pixel_Data = new uint8_t[imgDataSize];
500 LastAllocatedPixelDataLength = imgDataSize;
502 // we load the pixels ( grey level or RGB, but NO transformation)
503 GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
505 // We say the value *is* loaded.
506 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
507 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
509 // will be 7fe0, 0010 in standard cases
510 GetHeader()->SetEntryBinAreaByNumber(Pixel_Data,
511 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
513 PixelRead = 1; // PixelRaw
520 * \brief Copies at most MaxSize bytes of pixel data to caller's
522 * \warning This function was designed to avoid people that want to build
523 * a volume from an image stack to need first to get the image pixels
524 * and then move them to the volume area.
525 * It's absolutely useless for any VTK user since vtk chooses
526 * to invert the lines of an image, that is the last line comes first
527 * (for some axis related reasons?). Hence he will have
528 * to load the image line by line, starting from the end.
529 * VTK users hace to call GetImageData
530 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
531 * into a single RGB Pixels Plane
532 * the (VTK) user will manage the palettes
534 * @param destination Address (in caller's memory space) at which the
535 * pixel data should be copied
536 * @param maxSize Maximum number of bytes to be copied. When MaxSize
537 * is not sufficient to hold the pixel data the copy is not
538 * executed (i.e. no partial copy).
539 * @return On success, the number of bytes actually copied. Zero on
540 * failure e.g. MaxSize is lower than necessary.
542 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t maxSize)
544 int nb, nbu, highBit, sign;
546 // we save the initial values of the following
547 // in order to be able to restore the header in a disk-consistent state
548 // (if user asks twice to get the pixels from disk)
550 if ( PixelRead != -1 ) // File was "read" before
552 RestoreInitialValues();
555 PixelRead = 1 ; // PixelRaw
557 if ( ImageDataSize > maxSize )
559 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
560 "than caller's expected MaxSize");
564 ReadPixelData( destination );
566 // Number of Bits Allocated for storing a Pixel
567 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
568 if ( str_nb == GDCM_UNFOUND )
574 nb = atoi( str_nb.c_str() );
576 // From reading SetPixelDataSizeFromHeader, it seems 12 should be treated
577 // separately, correct ?
580 // Number of Bits actually used
581 std::string str_nbu = Header->GetEntryByNumber(0x0028,0x0101);
582 if ( str_nbu == GDCM_UNFOUND )
588 nbu = atoi( str_nbu.c_str() );
592 std::string str_highBit = Header->GetEntryByNumber(0x0028,0x0102);
593 if ( str_highBit == GDCM_UNFOUND )
599 highBit = atoi( str_highBit.c_str() );
605 std::string str_sign = Header->GetEntryByNumber(0x0028,0x0103);
606 if ( str_sign == GDCM_UNFOUND )
608 sign = 0; // default is unsigned
612 sign = atoi( str_sign.c_str() );
615 // re arange bytes inside the integer (processor endianity)
618 SwapZone(destination, Header->GetSwapCode(), ImageDataSize, nb);
621 // to avoid pb with some xmedcon breakers images
622 if ( nb == 16 && nbu < nb && sign == 0)
624 int l = (int)(ImageDataSize / (nb/8));
625 uint16_t *deb = (uint16_t *)destination;
626 for(int i = 0; i<l; i++)
636 // re arange bits inside the bytes
639 int l = (int)(ImageDataSize / (nb/8));
642 uint16_t mask = 0xffff;
643 mask = mask >> (nb-nbu);
644 uint16_t *deb = (uint16_t *)destination;
645 for(int i = 0; i<l; i++)
647 *deb = (*deb >> (nbu - highBit - 1)) & mask;
653 uint32_t mask = 0xffffffff;
654 mask = mask >> (nb - nbu);
655 uint32_t *deb = (uint32_t *)destination;
656 for(int i = 0; i<l; i++)
658 *deb = (*deb >> (nbu - highBit - 1)) & mask;
664 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
668 // DO NOT remove this code commented out.
669 // Nobody knows what's expecting you ...
670 // Just to 'see' what was actually read on disk :-(
673 // f2 = fopen("SpuriousFile.RAW","wb");
674 // fwrite(destination,ImageDataSize,1,f2);
677 // Deal with the color
678 // -------------------
680 std::string str_PhotometricInterpretation =
681 Header->GetEntryByNumber(0x0028,0x0004);
683 if ( str_PhotometricInterpretation == "MONOCHROME1 "
684 || str_PhotometricInterpretation == "MONOCHROME2 " )
686 return ImageDataSize;
689 // Planar configuration = 0 : Pixels are already RGB
690 // Planar configuration = 1 : 3 planes : R, G, B
691 // Planar configuration = 2 : 1 gray Plane + 3 LUT
693 // Well ... supposed to be !
694 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
695 // PhotometricInterpretation=PALETTE COLOR
696 // and heuristic has to be found :-(
698 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
700 // Whatever Planar Configuration is,
701 // "PALETTE COLOR " implies that we deal with the palette.
702 if ( str_PhotometricInterpretation == "PALETTE COLOR ")
710 // Pixels are already RGB
713 if (str_PhotometricInterpretation == "YBR_FULL")
715 // Warning : YBR_FULL_422 acts as RGB
716 // : we need to make RGB Pixels from Planes Y,cB,cR
718 // to see the tricks about YBR_FULL, YBR_FULL_422,
719 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
720 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
721 // and be *very* affraid
723 int l = Header->GetXSize() * Header->GetYSize();
724 int nbFrames = Header->GetZSize();
726 uint8_t* newDest = new uint8_t[ImageDataSize];
727 uint8_t* x = newDest;
728 uint8_t* a = (uint8_t*)destination;
733 /// \todo : Replace by the 'well known' integer computation
735 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
736 /// for code optimisation
738 for (int i = 0; i < nbFrames; i++)
740 for (int j = 0; j < l; j++)
742 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
743 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
744 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
746 if (R < 0.0) R = 0.0;
747 if (G < 0.0) G = 0.0;
748 if (B < 0.0) B = 0.0;
749 if (R > 255.0) R = 255.0;
750 if (G > 255.0) G = 255.0;
751 if (B > 255.0) B = 255.0;
759 memmove(destination, newDest, ImageDataSize);
764 // need to make RGB Pixels from R,G,B Planes
765 // (all the Frames at a time)
767 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
769 uint8_t *newDest = new uint8_t[ImageDataSize];
770 uint8_t *x = newDest;
771 uint8_t *a = (uint8_t *)destination;
775 for (int j = 0; j < l; j++)
781 memmove(destination, newDest, ImageDataSize);
786 // Palettes were found
787 // Let the user deal with them !
788 return ImageDataSize;
790 // now, it's an RGB image
791 // Lets's write it in the Header
793 // Droping Palette Color out of the Header
794 // has been moved to the Write process.
796 // TODO : move 'values' modification to the write process
797 // : save also (in order to be able to restore)
798 // : 'high bit' -when not equal to 'bits stored' + 1
799 // : 'bits allocated', when it's equal to 12 ?!
801 std::string spp = "3"; // Samples Per Pixel
802 std::string photInt = "RGB "; // Photometric Interpretation
803 std::string planConfig = "0"; // Planar Configuration
805 Header->SetEntryByNumber(spp,0x0028,0x0002);
806 Header->SetEntryByNumber(photInt,0x0028,0x0004);
807 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
809 return ImageDataSize;
814 * \brief performs a shalow copy (not a deep copy) of the user given
816 * 'image' Pixels are presented as C-like 2D arrays : line per line.
817 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
818 * \warning user is kindly requested NOT TO 'free' the Pixel area
819 * @param inData user supplied pixel area
820 * @param expectedSize total image size, in Bytes
824 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
826 Header->SetImageDataSize( expectedSize );
827 // FIXME : if already allocated, memory leak !
829 ImageDataSize = ImageDataSizeRaw = expectedSize;
831 // FIXME : 7fe0, 0010 IS NOT set ...
837 * \brief Writes on disk A SINGLE Dicom file
838 * NO test is performed on processor "Endiannity".
839 * It's up to the user to call his Reader properly
840 * @param fileName name of the file to be created
841 * (any already existing file is over written)
842 * @return false if write fails
845 bool gdcmFile::WriteRawData(std::string const & fileName)
847 FILE *fp1 = fopen(fileName.c_str(), "wb");
850 printf("Fail to open (write) file [%s] \n", fileName.c_str());
853 fwrite (Pixel_Data, ImageDataSize, 1, fp1);
861 * \brief Writes on disk A SINGLE Dicom file,
862 * using the Implicit Value Representation convention
863 * NO test is performed on processor "Endiannity".
864 * @param fileName name of the file to be created
865 * (any already existing file is overwritten)
866 * @return false if write fails
869 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
871 return WriteBase(fileName, gdcmImplicitVR);
876 * \brief Writes on disk A SINGLE Dicom file,
877 * using the Explicit Value Representation convention
878 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
879 * (any already existing file is overwritten)
880 * @return false if write fails
883 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
885 return WriteBase(fileName, gdcmExplicitVR);
890 * \brief Writes on disk A SINGLE Dicom file,
891 * using the ACR-NEMA convention
892 * NO test is performed on processor "Endiannity".
893 * (a l'attention des logiciels cliniques
894 * qui ne prennent en entrée QUE des images ACR ...
895 * \warning if a DICOM_V3 header is supplied,
896 * groups < 0x0008 and shadow groups are ignored
897 * \warning NO TEST is performed on processor "Endiannity".
898 * @param fileName name of the file to be created
899 * (any already existing file is overwritten)
900 * @return false if write fails
903 bool gdcmFile::WriteAcr (std::string const & fileName)
905 return WriteBase(fileName, gdcmACR);
908 //-----------------------------------------------------------------------------
912 * \brief NOT a end user inteded function
913 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
914 * @param fileName name of the file to be created
915 * (any already existing file is overwritten)
916 * @param type file type (ExplicitVR, ImplicitVR, ...)
917 * @return false if write fails
919 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
921 if ( PixelRead == -1 && type != gdcmExplicitVR)
926 FILE *fp1 = fopen(fileName.c_str(), "wb");
929 printf("Failed to open (write) File [%s] \n", fileName.c_str());
933 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
935 // writing Dicom File Preamble
936 uint8_t* filePreamble = new uint8_t[128];
937 memset(filePreamble, 0, 128);
938 fwrite(filePreamble, 128, 1, fp1);
939 fwrite("DICM", 4, 1, fp1);
941 delete[] filePreamble;
944 // --------------------------------------------------------------
945 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
947 // if recognition code tells us we dealt with a LibIDO image
948 // we reproduce on disk the switch between lineNumber and columnNumber
949 // just before writting ...
951 /// \todo the best trick would be *change* the recognition code
952 /// but pb expected if user deals with, e.g. COMPLEX images
954 std::string rows, columns;
955 if ( Header->GetFileType() == gdcmACR_LIBIDO)
957 rows = Header->GetEntryByNumber(0x0028, 0x0010);
958 columns = Header->GetEntryByNumber(0x0028, 0x0011);
960 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
961 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
963 // ----------------- End of Special Patch ----------------
965 uint16_t grPixel = Header->GetGrPixel();
966 uint16_t numPixel = Header->GetNumPixel();;
968 gdcmDocEntry* PixelElement =
969 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
971 if ( PixelRead == 1 )
973 // we read pixel 'as is' (no tranformation LUT -> RGB)
974 PixelElement->SetLength( ImageDataSizeRaw );
976 else if ( PixelRead == 0 )
978 // we tranformed GrayLevel pixels + LUT into RGB Pixel
979 PixelElement->SetLength( ImageDataSize );
982 Header->Write(fp1, type);
984 // --------------------------------------------------------------
985 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
987 // ...and we restore the Header to be Dicom Compliant again
988 // just after writting
990 if ( Header->GetFileType() == gdcmACR_LIBIDO )
992 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
993 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
995 // ----------------- End of Special Patch ----------------
997 // fwrite(Pixel_Data, ImageDataSize, 1, fp1); // should be useless, now
1003 //-----------------------------------------------------------------------------
1007 * \brief Swap the bytes, according to swap code.
1008 * \warning not end user intended
1009 * @param im area to deal with
1010 * @param swap swap code
1011 * @param lgr Area Length
1012 * @param nb Pixels Bit number
1014 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb)
1020 uint16_t* im16 = (uint16_t*)im;
1031 for(i=0; i < lgr/2; i++)
1033 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
1037 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
1044 uint16_t fort, faible;
1045 uint32_t* im32 = (uint32_t*)im;
1052 for(i = 0; i < lgr/4; i++)
1054 faible = im32[i] & 0x0000ffff; // 4321
1055 fort = im32[i] >> 16;
1056 fort = ( fort >> 8 ) | ( fort << 8 );
1057 faible = ( faible >> 8 ) | ( faible << 8);
1059 im32[i] = ( s32 << 16 ) | fort;
1063 for(i = 0; i < lgr/4; i++)
1065 faible = im32[i] & 0x0000ffff; // 2143
1066 fort = im32[i] >> 16;
1067 fort = ( fort >> 8 ) | ( fort << 8 );
1068 faible = ( faible >> 8) | ( faible << 8);
1070 im32[i] = ( s32 << 16 ) | faible;
1074 for(i = 0; i < lgr/4; i++)
1076 faible = im32[i] & 0x0000ffff; // 3412
1077 fort = im32[i] >> 16;
1079 im32[i] = ( s32 << 16 ) | fort;
1083 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
1091 * \brief Read pixel data from disk (optionaly decompressing) into the
1092 * caller specified memory location.
1093 * @param destination where the pixel data should be stored.
1096 bool gdcmFile::ReadPixelData(void *destination)
1098 FILE *fp = Header->OpenFile();
1104 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1106 Header->CloseFile();
1110 // ---------------------- Compacted File (12 Bits Per Pixel)
1111 // unpack 12 Bits pixels into 16 Bits pixels
1112 // 2 pixels 12bit = [0xABCDEF]
1113 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1115 if ( Header->GetBitsAllocated() == 12 )
1117 int nbPixels = Header->GetXSize() * Header->GetYSize();
1120 uint16_t* pdestination = (uint16_t*)destination;
1121 for(int p = 0; p < nbPixels; p += 2 )
1127 //Two steps is necessary to please VC++
1128 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1130 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1133 // Troubles expected on Big-Endian processors ?
1136 Header->CloseFile();
1140 // ---------------------- Uncompressed File
1141 if ( !Header->IsDicomV3() ||
1142 Header->IsImplicitVRLittleEndianTransferSyntax() ||
1143 Header->IsExplicitVRLittleEndianTransferSyntax() ||
1144 Header->IsExplicitVRBigEndianTransferSyntax() ||
1145 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1147 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1148 Header->CloseFile();
1149 if ( ItemRead != 1 )
1159 // ---------------------- Run Length Encoding
1160 if ( Header->IsRLELossLessTransferSyntax() )
1162 bool res = gdcm_read_RLE_file (fp,destination);
1163 Header->CloseFile();
1167 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1169 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1170 if ( str_nb == GDCM_UNFOUND )
1176 nb = atoi( str_nb.c_str() );
1179 nb = 16; // ?? 12 should be ACR-NEMA only
1184 int taille = Header->GetXSize() * Header->GetYSize()
1185 * Header->GetSamplesPerPixel();
1186 long fragmentBegining; // for ftell, fseek
1188 bool jpg2000 = Header->IsJPEG2000();
1189 bool jpgLossless = Header->IsJPEGLossless();
1192 uint16_t ItemTagGr, ItemTagEl;
1195 // Position on begining of Jpeg Pixels
1197 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1198 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1199 if(Header->GetSwapCode())
1201 ItemTagGr = Header->SwapShort(ItemTagGr);
1202 ItemTagEl = Header->SwapShort(ItemTagEl);
1206 if( Header->GetSwapCode() )
1208 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1213 // What is it used for ?!?
1214 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1215 fread(BasicOffsetTableItemValue,ln,1,fp);
1216 //delete[] BasicOffsetTableItemValue;
1219 // first Fragment initialisation
1220 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1221 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1222 if( Header->GetSwapCode() )
1224 ItemTagGr = Header->SwapShort( ItemTagGr );
1225 ItemTagEl = Header->SwapShort( ItemTagEl );
1228 // parsing fragments until Sequence Delim. Tag found
1229 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1231 // --- for each Fragment
1233 if( Header->GetSwapCode() )
1235 ln = Header->SwapLong(ln); // Fragment Item length
1237 fragmentBegining = ftell( fp );
1241 // JPEG 2000 : call to ???
1242 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1243 // ------------------------------------- endif (JPEG2000)
1245 else if (jpgLossless)
1247 // JPEG LossLess : call to xmedcom Lossless JPEG
1248 // Reading Fragment pixels
1249 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1250 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1251 res = 1; // in order not to break the loop
1253 } // ------------------------------------- endif (JPEGLossless)
1256 // JPEG Lossy : call to IJG 6b
1257 if ( Header->GetBitsStored() == 8)
1259 // Reading Fragment pixels
1260 res = gdcm_read_JPEG_file (fp,destination);
1264 // Reading Fragment pixels
1265 res = gdcm_read_JPEG_file12 (fp,destination);
1267 // ------------------------------------- endif (JPEGLossy)
1275 // location in user's memory
1276 // for next fragment (if any)
1277 destination = (uint8_t*)destination + taille * nBytes;
1279 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1280 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1282 ItemTagGr = ItemTagEl = 0;
1283 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1284 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1285 if( Header->GetSwapCode() )
1287 ItemTagGr = Header->SwapShort( ItemTagGr );
1288 ItemTagEl = Header->SwapShort( ItemTagEl );
1291 // endWhile parsing fragments until Sequence Delim. Tag found
1293 Header->CloseFile();
1296 //-----------------------------------------------------------------------------