1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/10/08 16:27:20 $
7 Version: $Revision: 1.135 $
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.html 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 "gdcmPixelConvert.h"
22 #include "jpeg/ljpg/jpegless.h"
24 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
26 //-------------------------------------------------------------------------
27 // 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)
50 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
51 * file (gdcmHeader only deals with the ... header)
52 * Opens (in read only and when possible) an existing file and checks
53 * for DICOM compliance. Returns NULL on failure.
54 * It will be up to the user to load the pixels into memory
55 * (see GetImageData, GetImageDataRaw)
56 * \note the in-memory representation of all available tags found in
57 * the DICOM header is post-poned to first header information access.
58 * This avoid a double parsing of public part of the header when
59 * one sets an a posteriori shadow dictionary (efficiency can be
60 * seen as a side effect).
61 * @param filename file to be opened for parsing
63 gdcmFile::gdcmFile(std::string const & filename )
65 Header = new gdcmHeader( filename );
71 * \brief Factorization for various forms of constructors.
73 void gdcmFile::Initialise()
75 if ( Header->IsReadable() )
77 ImageDataSizeRaw = ComputeDecompressedPixelDataSizeFromHeader();
78 if ( Header->HasLUT() )
80 ImageDataSize = 3 * ImageDataSizeRaw;
84 ImageDataSize = ImageDataSizeRaw;
91 * \brief canonical destructor
92 * \note If the gdcmHeader was created by the gdcmFile constructor,
93 * it is destroyed by the gdcmFile
103 DeleteInitialValues();
107 * \brief Sets some initial values for the Constructor
108 * \warning not end user intended
110 void gdcmFile::SaveInitialValues()
113 PixelRead = -1; // no ImageData read yet.
114 LastAllocatedPixelDataLength = 0;
119 InitialPlanConfig = "";
120 InitialBitsAllocated = "";
123 InitialRedLUTDescr = 0;
124 InitialGreenLUTDescr = 0;
125 InitialBlueLUTDescr = 0;
126 InitialRedLUTData = 0;
127 InitialGreenLUTData = 0;
128 InitialBlueLUTData = 0;
130 if ( Header->IsReadable() )
132 // the following values *may* be modified
133 // by gdcmFile::GetImageDataIntoVectorRaw
134 // we save their initial value.
135 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
136 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
137 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
139 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
140 InitialHighBit = Header->GetEntryByNumber(0x0028,0x0102);
142 // the following entries *may* be removed from the H table
143 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
144 // we keep a pointer on them.
145 InitialRedLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1101);
146 InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
147 InitialBlueLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1103);
149 InitialRedLUTData = Header->GetDocEntryByNumber(0x0028,0x1201);
150 InitialGreenLUTData = Header->GetDocEntryByNumber(0x0028,0x1202);
151 InitialBlueLUTData = Header->GetDocEntryByNumber(0x0028,0x1203);
156 * \brief restores some initial values
157 * \warning not end user intended
159 void gdcmFile::RestoreInitialValues()
161 if ( Header->IsReadable() )
163 // the following values *may* have been modified
164 // by gdcmFile::GetImageDataIntoVectorRaw
165 // we restore their initial value.
166 if ( InitialSpp != "")
167 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
168 if ( InitialPhotInt != "")
169 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
170 if ( InitialPlanConfig != "")
172 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
173 if ( InitialBitsAllocated != "")
174 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
175 if ( InitialHighBit != "")
176 Header->SetEntryByNumber(InitialHighBit,0x0028,0x0102);
178 // the following entries *may* be have been removed from the H table
179 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
182 if (InitialRedLUTDescr)
183 Header->AddEntry(InitialRedLUTDescr);
184 if (InitialGreenLUTDescr)
185 Header->AddEntry(InitialGreenLUTDescr);
186 if (InitialBlueLUTDescr)
187 Header->AddEntry(InitialBlueLUTDescr);
189 if (InitialRedLUTData)
190 Header->AddEntry(InitialBlueLUTDescr);
191 if (InitialGreenLUTData)
192 Header->AddEntry(InitialGreenLUTData);
193 if (InitialBlueLUTData)
194 Header->AddEntry(InitialBlueLUTData);
199 * \brief delete initial values (il they were saved)
200 * of InitialLutDescriptors and InitialLutData
202 void gdcmFile::DeleteInitialValues()
205 // InitialLutDescriptors and InitialLutData
206 // will have to be deleted if the don't belong any longer
207 // to the Header H table when the header is deleted...
209 if ( InitialRedLUTDescr )
210 delete InitialRedLUTDescr;
212 if ( InitialGreenLUTDescr )
213 delete InitialGreenLUTDescr;
215 if ( InitialBlueLUTDescr )
216 delete InitialBlueLUTDescr;
218 if ( InitialRedLUTData )
219 delete InitialRedLUTData;
221 if ( InitialGreenLUTData != NULL)
222 delete InitialGreenLUTData;
224 if ( InitialBlueLUTData != NULL)
225 delete InitialBlueLUTData;
228 //-----------------------------------------------------------------------------
231 //-----------------------------------------------------------------------------
235 * \brief computes the length (in bytes) we must ALLOCATE to receive the
236 * image(s) pixels (multiframes taken into account)
237 * \warning : it is NOT the group 7FE0 length
238 * (no interest for compressed images).
240 int gdcmFile::ComputeDecompressedPixelDataSizeFromHeader()
242 // see PS 3.3-2003 : C.7.6.3.2.1
252 // YBR_FULL_422 (no LUT, no Palette)
258 // ex : gdcm-US-ALOKA-16.dcm
259 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
260 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
261 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
263 // ex : OT-PAL-8-face.dcm
264 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
265 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
266 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
268 // Number of "Bits Allocated"
269 int numberBitsAllocated = Header->GetBitsAllocated();
270 if ( ( numberBitsAllocated == 0 ) || ( numberBitsAllocated == 12 ) )
272 numberBitsAllocated = 16;
275 int DecompressedSize = Header->GetXSize()
278 * ( numberBitsAllocated / 8 )
279 * Header->GetSamplesPerPixel();
281 return DecompressedSize;
285 * \brief - Allocates necessary memory,
286 * - Reads the pixels from disk (uncompress if necessary),
287 * - Transforms YBR pixels, if any, into RGB pixels
288 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
289 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
290 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
291 * @return Pointer to newly allocated pixel data.
292 * NULL if alloc fails
294 uint8_t* gdcmFile::GetImageData()
297 // I need to deallocate Pixel_Data before doing any allocation:
300 if ( LastAllocatedPixelDataLength != ImageDataSize )
303 Pixel_Data = new uint8_t[ImageDataSize];
307 LastAllocatedPixelDataLength = ImageDataSize;
309 // we load the pixels (and transform grey level + LUT into RGB)
310 GetImageDataIntoVector(Pixel_Data, ImageDataSize);
312 // We say the value *is* loaded.
313 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
314 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
316 // Will be 7fe0, 0010 in standard case
317 GetHeader()->SetEntryBinAreaByNumber( Pixel_Data,
318 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
320 PixelRead = 0; // no PixelRaw
327 * Read the pixels from disk (uncompress if necessary),
328 * Transforms YBR pixels, if any, into RGB pixels
329 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
330 * Transforms single Grey plane + 3 Palettes into a RGB Plane
331 * Copies at most MaxSize bytes of pixel data to caller allocated
333 * \warning This function allows people that want to build a volume
334 * from an image stack *not to* have, first to get the image pixels,
335 * and then move them to the volume area.
336 * It's absolutely useless for any VTK user since vtk chooses
337 * to invert the lines of an image, that is the last line comes first
338 * (for some axis related reasons?). Hence he will have
339 * to load the image line by line, starting from the end.
340 * VTK users have to call GetImageData
342 * @param destination Address (in caller's memory space) at which the
343 * pixel data should be copied
344 * @param maxSize Maximum number of bytes to be copied. When MaxSize
345 * is not sufficient to hold the pixel data the copy is not
346 * executed (i.e. no partial copy).
347 * @return On success, the number of bytes actually copied. Zero on
348 * failure e.g. MaxSize is lower than necessary.
350 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
352 GetImageDataIntoVectorRaw (destination, maxSize);
353 PixelRead = 0 ; // =0 : no ImageDataRaw
354 if ( !Header->HasLUT() )
356 return ImageDataSize;
359 // from Lut R + Lut G + Lut B
360 uint8_t *newDest = new uint8_t[ImageDataSize];
361 uint8_t *a = (uint8_t *)destination;
362 uint8_t *lutRGBA = Header->GetLUTRGBA();
367 // move Gray pixels to temp area
368 memmove(newDest, destination, ImageDataSizeRaw);
369 for (size_t i=0; i<ImageDataSizeRaw; ++i)
379 // now, it's an RGB image
380 // Lets's write it in the Header
382 // FIXME : Better use CreateOrReplaceIfExist ?
384 std::string spp = "3"; // Samples Per Pixel
385 Header->SetEntryByNumber(spp,0x0028,0x0002);
386 std::string rgb = "RGB "; // Photometric Interpretation
387 Header->SetEntryByNumber(rgb,0x0028,0x0004);
388 std::string planConfig = "0"; // Planar Configuration
389 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
392 else // GetLUTRGBA() failed
394 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
395 // that are *more* than 65535 long ?!?
396 // No idea how to manage such an image !
397 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
398 // It seems that *no Dicom Viewer* has any idea :-(
400 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
401 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
404 /// \todo Drop Palette Color out of the Header?
405 return ImageDataSize;
409 * \brief Allocates necessary memory,
410 * Transforms YBR pixels (if any) into RGB pixels
411 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
412 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
413 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
414 * @return Pointer to newly allocated pixel data.
415 * \ NULL if alloc fails
417 uint8_t* gdcmFile::GetImageDataRaw ()
420 if ( Header->HasLUT() )
421 /// \todo Let gdcmHeader user a chance to get the right value
422 imgDataSize = ImageDataSizeRaw;
424 imgDataSize = ImageDataSize;
427 // I need to deallocate Pixel_Data before doing any allocation:
430 if ( LastAllocatedPixelDataLength != imgDataSize )
433 Pixel_Data = new uint8_t[imgDataSize];
437 LastAllocatedPixelDataLength = imgDataSize;
439 // we load the pixels ( grey level or RGB, but NO transformation)
440 GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
442 // We say the value *is* loaded.
443 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
444 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
446 // will be 7fe0, 0010 in standard cases
447 GetHeader()->SetEntryBinAreaByNumber(Pixel_Data,
448 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
450 PixelRead = 1; // PixelRaw
456 * \brief Copies at most MaxSize bytes of pixel data to caller's
458 * \warning This function was designed to avoid people that want to build
459 * a volume from an image stack to need first to get the image pixels
460 * and then move them to the volume area.
461 * It's absolutely useless for any VTK user since vtk chooses
462 * to invert the lines of an image, that is the last line comes first
463 * (for some axis related reasons?). Hence he will have
464 * to load the image line by line, starting from the end.
465 * VTK users hace to call GetImageData
466 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
467 * into a single RGB Pixels Plane
468 * the (VTK) user will manage the palettes
470 * @param destination Address (in caller's memory space) at which the
471 * pixel data should be copied
472 * @param maxSize Maximum number of bytes to be copied. When MaxSize
473 * is not sufficient to hold the pixel data the copy is not
474 * executed (i.e. no partial copy).
475 * @return On success, the number of bytes actually copied. Zero on
476 * failure e.g. MaxSize is lower than necessary.
478 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t maxSize)
480 // we save the initial values of the following
481 // in order to be able to restore the header in a disk-consistent state
482 // (if user asks twice to get the pixels from disk)
484 if ( PixelRead != -1 ) // File was "read" before
486 RestoreInitialValues();
489 PixelRead = 1 ; // PixelRaw
491 if ( ImageDataSize > maxSize )
493 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
494 "than caller's expected MaxSize");
498 ReadPixelData( destination );
500 // Number of Bits Allocated for storing a Pixel
501 int numberBitsAllocated = Header->GetBitsAllocated();
502 if ( numberBitsAllocated == 0 )
504 numberBitsAllocated = 16;
507 // Number of Bits actually used
508 int numberBitsStored = Header->GetBitsStored();
509 if ( numberBitsStored == 0 )
511 numberBitsStored = numberBitsAllocated;
515 int highBitPosition = Header->GetHighBitPosition();
516 if ( highBitPosition == 0 )
518 highBitPosition = numberBitsAllocated - 1;
521 bool signedPixel = Header->IsSignedPixelData();
523 ConvertReorderEndianity( (uint8_t*) destination,
529 ConvertReArrangeBits( (uint8_t*) destination,
537 DebugFile = fopen( "SpuriousFile.RAW", "wb" );
538 fwrite( PixelConvertor.GetUncompressed(),
539 PixelConvertor.GetUncompressedsSize(),
545 //////////////////////////////////
546 // Deal with the color
548 // Monochrome pictures don't require color intervention
549 if ( Header->IsMonochrome() )
551 return ImageDataSize;
554 // Planar configuration = 0 : Pixels are already RGB
555 // Planar configuration = 1 : 3 planes : R, G, B
556 // Planar configuration = 2 : 1 gray Plane + 3 LUT
558 // Well ... supposed to be !
559 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
560 // PhotometricInterpretation=PALETTE COLOR
561 // and heuristic has to be found :-(
563 int planConf = Header->GetPlanarConfiguration();
565 // Planar configuration = 2 ==> 1 gray Plane + 3 LUT
567 // whatever the Planar Configuration might be, "PALETTE COLOR "
568 // implies that we deal with the palette.
569 if ( ( planConf == 2 ) || Header->IsPaletteColor() )
571 return ImageDataSize;
574 // When planConf is 0, pixels are allready in RGB
578 uint8_t* newDest = new uint8_t[ImageDataSize];
579 // Warning : YBR_FULL_422 acts as RGB
580 if ( Header->IsYBRFull() )
582 ConvertYcBcRPlanesToRGBPixels((uint8_t*)destination, newDest);
586 ConvertRGBPlanesToRGBPixels((uint8_t*)destination, newDest);
588 memmove(destination, newDest, ImageDataSize);
592 ///////////////////////////////////////////////////
593 // now, it's an RGB image
594 // Lets's write it in the Header
596 // Droping Palette Color out of the Header
597 // has been moved to the Write process.
599 // TODO : move 'values' modification to the write process
600 // : save also (in order to be able to restore)
601 // : 'high bit' -when not equal to 'bits stored' + 1
602 // : 'bits allocated', when it's equal to 12 ?!
604 std::string spp = "3"; // Samples Per Pixel
605 std::string photInt = "RGB "; // Photometric Interpretation
606 std::string planConfig = "0"; // Planar Configuration
608 Header->SetEntryByNumber(spp,0x0028,0x0002);
609 Header->SetEntryByNumber(photInt,0x0028,0x0004);
610 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
612 return ImageDataSize;
616 * \brief Re-arrange the bits within the bytes.
618 void gdcmFile::ConvertReArrangeBits( uint8_t* pixelZone,
619 size_t imageDataSize,
620 int numberBitsStored,
621 int numberBitsAllocated,
623 throw ( gdcmFormatError )
625 if ( numberBitsStored != numberBitsAllocated )
627 int l = (int)(imageDataSize / (numberBitsAllocated/8));
628 if ( numberBitsAllocated == 16 )
630 uint16_t mask = 0xffff;
631 mask = mask >> ( numberBitsAllocated - numberBitsStored );
632 uint16_t* deb = (uint16_t*)pixelZone;
633 for(int i = 0; i<l; i++)
635 *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
639 else if ( numberBitsAllocated == 32 )
641 uint32_t mask = 0xffffffff;
642 mask = mask >> ( numberBitsAllocated - numberBitsStored );
643 uint32_t* deb = (uint32_t*)pixelZone;
644 for(int i = 0; i<l; i++)
646 *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
652 dbg.Verbose(0, "gdcmFile::ConvertReArrangeBits: weird image");
653 throw gdcmFormatError( "gdcmFile::ConvertReArrangeBits()",
660 * \brief Deal with endianity i.e. re-arange bytes inside the integer
662 void gdcmFile::ConvertReorderEndianity( uint8_t* pixelZone,
663 size_t imageDataSize,
664 int numberBitsStored,
665 int numberBitsAllocated,
668 if ( numberBitsAllocated != 8 )
670 SwapZone( pixelZone, Header->GetSwapCode(), ImageDataSize,
671 numberBitsAllocated );
674 // Special kludge in order to deal with xmedcon broken images:
675 if ( ( numberBitsAllocated == 16 )
676 && ( numberBitsStored < numberBitsAllocated )
677 && ( ! signedPixel ) )
679 int l = (int)(ImageDataSize / (numberBitsAllocated/8));
680 uint16_t *deb = (uint16_t *)pixelZone;
681 for(int i = 0; i<l; i++)
693 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
694 * \warning Works on all the frames at a time
696 void gdcmFile::ConvertYcBcRPlanesToRGBPixels(uint8_t* source,
697 uint8_t* destination)
699 // to see the tricks about YBR_FULL, YBR_FULL_422,
700 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
701 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
702 // and be *very* affraid
704 int l = Header->GetXSize() * Header->GetYSize();
705 int nbFrames = Header->GetZSize();
708 uint8_t* b = source + l;
709 uint8_t* c = source + l + l;
712 /// \todo : Replace by the 'well known' integer computation
713 /// counterpart. Refer to
714 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
715 /// for code optimisation.
717 for (int i = 0; i < nbFrames; i++)
719 for (int j = 0; j < l; j++)
721 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
722 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
723 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
725 if (R < 0.0) R = 0.0;
726 if (G < 0.0) G = 0.0;
727 if (B < 0.0) B = 0.0;
728 if (R > 255.0) R = 255.0;
729 if (G > 255.0) G = 255.0;
730 if (B > 255.0) B = 255.0;
732 *(destination++) = (uint8_t)R;
733 *(destination++) = (uint8_t)G;
734 *(destination++) = (uint8_t)B;
743 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
744 * \warning Works on all the frames at a time
746 void gdcmFile::ConvertRGBPlanesToRGBPixels(uint8_t* source,
747 uint8_t* destination)
749 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
752 uint8_t* b = source + l;
753 uint8_t* c = source + l + l;
755 for (int j = 0; j < l; j++)
757 *(destination++) = *(a++);
758 *(destination++) = *(b++);
759 *(destination++) = *(c++);
764 * \brief Points the internal Pixel_Data pointer to the callers inData
765 * image representation, BUT WITHOUT COPYING THE DATA.
766 * 'image' Pixels are presented as C-like 2D arrays : line per line.
767 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
768 * \warning Since the pixels are not copied, it is the caller's responsability
769 * not to deallocate it's data before gdcm uses them (e.g. with
770 * the Write() method.
771 * @param inData user supplied pixel area
772 * @param expectedSize total image size, in Bytes
776 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
778 Header->SetImageDataSize( expectedSize );
779 // FIXME : if already allocated, memory leak !
781 ImageDataSize = ImageDataSizeRaw = expectedSize;
783 // FIXME : 7fe0, 0010 IS NOT set ...
788 * \brief Writes on disk A SINGLE Dicom file
789 * NO test is performed on processor "Endiannity".
790 * It's up to the user to call his Reader properly
791 * @param fileName name of the file to be created
792 * (any already existing file is over written)
793 * @return false if write fails
796 bool gdcmFile::WriteRawData(std::string const & fileName)
798 FILE* fp1 = fopen(fileName.c_str(), "wb");
801 printf("Fail to open (write) file [%s] \n", fileName.c_str());
804 fwrite (Pixel_Data, ImageDataSize, 1, fp1);
811 * \brief Writes on disk A SINGLE Dicom file,
812 * using the Implicit Value Representation convention
813 * NO test is performed on processor "Endiannity".
814 * @param fileName name of the file to be created
815 * (any already existing file is overwritten)
816 * @return false if write fails
819 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
821 return WriteBase(fileName, gdcmImplicitVR);
825 * \brief Writes on disk A SINGLE Dicom file,
826 * using the Explicit Value Representation convention
827 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
828 * (any already existing file is overwritten)
829 * @return false if write fails
832 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
834 return WriteBase(fileName, gdcmExplicitVR);
838 * \brief Writes on disk A SINGLE Dicom file,
839 * using the ACR-NEMA convention
840 * NO test is performed on processor "Endiannity".
841 * (a l'attention des logiciels cliniques
842 * qui ne prennent en entrée QUE des images ACR ...
843 * \warning if a DICOM_V3 header is supplied,
844 * groups < 0x0008 and shadow groups are ignored
845 * \warning NO TEST is performed on processor "Endiannity".
846 * @param fileName name of the file to be created
847 * (any already existing file is overwritten)
848 * @return false if write fails
851 bool gdcmFile::WriteAcr (std::string const & fileName)
853 return WriteBase(fileName, gdcmACR);
856 //-----------------------------------------------------------------------------
859 * \brief NOT a end user inteded function
860 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
861 * @param fileName name of the file to be created
862 * (any already existing file is overwritten)
863 * @param type file type (ExplicitVR, ImplicitVR, ...)
864 * @return false if write fails
866 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
868 if ( PixelRead == -1 && type != gdcmExplicitVR)
873 FILE* fp1 = fopen(fileName.c_str(), "wb");
876 printf("Failed to open (write) File [%s] \n", fileName.c_str());
880 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
882 // writing Dicom File Preamble
883 uint8_t* filePreamble = new uint8_t[128];
884 memset(filePreamble, 0, 128);
885 fwrite(filePreamble, 128, 1, fp1);
886 fwrite("DICM", 4, 1, fp1);
888 delete[] filePreamble;
891 // --------------------------------------------------------------
892 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
894 // if recognition code tells us we dealt with a LibIDO image
895 // we reproduce on disk the switch between lineNumber and columnNumber
896 // just before writting ...
898 /// \todo the best trick would be *change* the recognition code
899 /// but pb expected if user deals with, e.g. COMPLEX images
901 std::string rows, columns;
902 if ( Header->GetFileType() == gdcmACR_LIBIDO)
904 rows = Header->GetEntryByNumber(0x0028, 0x0010);
905 columns = Header->GetEntryByNumber(0x0028, 0x0011);
907 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
908 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
910 // ----------------- End of Special Patch ----------------
912 uint16_t grPixel = Header->GetGrPixel();
913 uint16_t numPixel = Header->GetNumPixel();;
915 gdcmDocEntry* PixelElement =
916 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
918 if ( PixelRead == 1 )
920 // we read pixel 'as is' (no tranformation LUT -> RGB)
921 PixelElement->SetLength( ImageDataSizeRaw );
923 else if ( PixelRead == 0 )
925 // we tranformed GrayLevel pixels + LUT into RGB Pixel
926 PixelElement->SetLength( ImageDataSize );
929 Header->Write(fp1, type);
931 // --------------------------------------------------------------
932 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
934 // ...and we restore the Header to be Dicom Compliant again
935 // just after writting
937 if ( Header->GetFileType() == gdcmACR_LIBIDO )
939 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
940 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
942 // ----------------- End of Special Patch ----------------
944 // fwrite(Pixel_Data, ImageDataSize, 1, fp1); // should be useless, now
950 //-----------------------------------------------------------------------------
953 * \brief Swap the bytes, according to swap code.
954 * \warning not end user intended
955 * @param im area to deal with
956 * @param swap swap code
957 * @param lgr Area Length
958 * @param nb Pixels Bit number
960 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb)
966 uint16_t* im16 = (uint16_t*)im;
977 for(i=0; i < lgr/2; i++)
979 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
983 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
990 uint16_t fort, faible;
991 uint32_t* im32 = (uint32_t*)im;
998 for(i = 0; i < lgr/4; i++)
1000 faible = im32[i] & 0x0000ffff; // 4321
1001 fort = im32[i] >> 16;
1002 fort = ( fort >> 8 ) | ( fort << 8 );
1003 faible = ( faible >> 8 ) | ( faible << 8);
1005 im32[i] = ( s32 << 16 ) | fort;
1009 for(i = 0; i < lgr/4; i++)
1011 faible = im32[i] & 0x0000ffff; // 2143
1012 fort = im32[i] >> 16;
1013 fort = ( fort >> 8 ) | ( fort << 8 );
1014 faible = ( faible >> 8) | ( faible << 8);
1016 im32[i] = ( s32 << 16 ) | faible;
1020 for(i = 0; i < lgr/4; i++)
1022 faible = im32[i] & 0x0000ffff; // 3412
1023 fort = im32[i] >> 16;
1025 im32[i] = ( s32 << 16 ) | fort;
1029 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
1036 * \brief Read pixel data from disk (optionaly decompressing) into the
1037 * caller specified memory location.
1038 * @param destination where the pixel data should be stored.
1041 bool gdcmFile::ReadPixelData(void* destination)
1043 FILE* fp = Header->OpenFile();
1049 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1051 Header->CloseFile();
1055 if ( Header->GetBitsAllocated() == 12 )
1057 ConvertDecompress12BitsTo16Bits( (uint8_t*)destination,
1061 Header->CloseFile();
1065 // ---------------------- Uncompressed File
1066 if ( !Header->IsDicomV3() ||
1067 Header->IsImplicitVRLittleEndianTransferSyntax() ||
1068 Header->IsExplicitVRLittleEndianTransferSyntax() ||
1069 Header->IsExplicitVRBigEndianTransferSyntax() ||
1070 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1072 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1073 Header->CloseFile();
1074 if ( ItemRead != 1 )
1084 // ---------------------- Run Length Encoding
1085 if ( Header->IsRLELossLessTransferSyntax() )
1087 bool res = gdcmPixelConvert::gdcm_read_RLE_file ( destination,
1091 Header->GetBitsAllocated(),
1094 Header->CloseFile();
1098 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1099 int numberBitsAllocated = Header->GetBitsAllocated();
1100 if ( ( numberBitsAllocated == 0 ) || ( numberBitsAllocated == 12 ) )
1102 numberBitsAllocated = 16;
1105 int nBytes= numberBitsAllocated/8;
1106 int taille = Header->GetXSize() * Header->GetYSize()
1107 * Header->GetSamplesPerPixel();
1108 long fragmentBegining; // for ftell, fseek
1110 bool jpg2000 = Header->IsJPEG2000();
1111 bool jpgLossless = Header->IsJPEGLossless();
1114 uint16_t ItemTagGr, ItemTagEl;
1117 // Position on begining of Jpeg Pixels
1119 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1120 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1121 if(Header->GetSwapCode())
1123 ItemTagGr = Header->SwapShort(ItemTagGr);
1124 ItemTagEl = Header->SwapShort(ItemTagEl);
1128 if( Header->GetSwapCode() )
1130 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1135 // What is it used for ?!?
1136 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1137 fread(BasicOffsetTableItemValue,ln,1,fp);
1138 //delete[] BasicOffsetTableItemValue;
1141 // first Fragment initialisation
1142 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1143 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1144 if( Header->GetSwapCode() )
1146 ItemTagGr = Header->SwapShort( ItemTagGr );
1147 ItemTagEl = Header->SwapShort( ItemTagEl );
1150 // parsing fragments until Sequence Delim. Tag found
1151 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1153 // --- for each Fragment
1155 if( Header->GetSwapCode() )
1157 ln = Header->SwapLong(ln); // Fragment Item length
1159 fragmentBegining = ftell( fp );
1163 // JPEG 2000 : call to ???
1164 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1165 // ------------------------------------- endif (JPEG2000)
1167 else if (jpgLossless)
1169 // JPEG LossLess : call to xmedcom Lossless JPEG
1170 // Reading Fragment pixels
1171 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1172 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1173 res = 1; // in order not to break the loop
1175 } // ------------------------------------- endif (JPEGLossless)
1178 // JPEG Lossy : call to IJG 6b
1179 if ( Header->GetBitsStored() == 8)
1181 // Reading Fragment pixels
1182 res = gdcm_read_JPEG_file (fp,destination);
1186 // Reading Fragment pixels
1187 res = gdcm_read_JPEG_file12 (fp,destination);
1189 // ------------------------------------- endif (JPEGLossy)
1197 // location in user's memory
1198 // for next fragment (if any)
1199 destination = (uint8_t*)destination + taille * nBytes;
1201 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1202 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1204 ItemTagGr = ItemTagEl = 0;
1205 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1206 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1207 if( Header->GetSwapCode() )
1209 ItemTagGr = Header->SwapShort( ItemTagGr );
1210 ItemTagEl = Header->SwapShort( ItemTagEl );
1213 // endWhile parsing fragments until Sequence Delim. Tag found
1215 Header->CloseFile();
1220 * \brief Read from file a 12 bits per pixel image and uncompress it
1221 * into a 16 bits per pixel image.
1223 void gdcmFile::ConvertDecompress12BitsTo16Bits(
1228 throw ( gdcmFormatError )
1230 int nbPixels = sizeX * sizeY;
1231 uint16_t* destination = (uint16_t*)pixelZone;
1233 for( int p = 0; p < nbPixels; p += 2 )
1238 ItemRead = fread( &b0, 1, 1, filePtr);
1239 if ( ItemRead != 1 )
1241 throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1242 "Unfound first block" );
1245 ItemRead = fread( &b1, 1, 1, filePtr);
1246 if ( ItemRead != 1 )
1248 throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1249 "Unfound second block" );
1252 ItemRead = fread( &b2, 1, 1, filePtr);
1253 if ( ItemRead != 1 )
1255 throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1256 "Unfound second block" );
1259 // Two steps are necessary to please VC++
1261 // 2 pixels 12bit = [0xABCDEF]
1262 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1264 *destination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1266 *destination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1268 /// \todo JPR Troubles expected on Big-Endian processors ?
1271 //-----------------------------------------------------------------------------