1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/09/29 17:33:17 $
7 Version: $Revision: 1.132 $
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 "jpeg/ljpg/jpegless.h"
23 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
25 //-------------------------------------------------------------------------
26 // Constructor / Destructor
28 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
29 * file (gdcmHeader only deals with the ... header)
30 * Opens (in read only and when possible) an existing file and checks
31 * for DICOM compliance. Returns NULL on failure.
32 * It will be up to the user to load the pixels into memory
33 * (see GetImageData, GetImageDataRaw)
34 * \note the in-memory representation of all available tags found in
35 * the DICOM header is post-poned to first header information access.
36 * This avoid a double parsing of public part of the header when
37 * user sets an a posteriori shadow dictionary (efficiency can be
38 * seen as a side effect).
39 * @param header already built gdcmHeader
41 gdcmFile::gdcmFile(gdcmHeader *header)
49 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
50 * file (gdcmHeader only deals with the ... header)
51 * Opens (in read only and when possible) an existing file and checks
52 * for DICOM compliance. Returns NULL on failure.
53 * It will be up to the user to load the pixels into memory
54 * (see GetImageData, GetImageDataRaw)
55 * \note the in-memory representation of all available tags found in
56 * the DICOM header is post-poned to first header information access.
57 * This avoid a double parsing of public part of the header when
58 * one sets an a posteriori shadow dictionary (efficiency can be
59 * seen as a side effect).
60 * @param filename file to be opened for parsing
62 gdcmFile::gdcmFile(std::string const & filename )
64 Header = new gdcmHeader( filename );
70 * \brief Factorization for various forms of constructors.
72 void gdcmFile::Initialise()
74 if ( Header->IsReadable() )
76 ImageDataSizeRaw = ComputeDecompressedPixelDataSizeFromHeader();
77 if ( Header->HasLUT() )
79 ImageDataSize = 3 * ImageDataSizeRaw;
83 ImageDataSize = ImageDataSizeRaw;
90 * \brief canonical destructor
91 * \note If the gdcmHeader was created by the gdcmFile constructor,
92 * it is destroyed by the gdcmFile
102 DeleteInitialValues();
106 * \brief Sets some initial values for the Constructor
107 * \warning not end user intended
109 void gdcmFile::SaveInitialValues()
112 PixelRead = -1; // no ImageData read yet.
113 LastAllocatedPixelDataLength = 0;
118 InitialPlanConfig = "";
119 InitialBitsAllocated = "";
122 InitialRedLUTDescr = 0;
123 InitialGreenLUTDescr = 0;
124 InitialBlueLUTDescr = 0;
125 InitialRedLUTData = 0;
126 InitialGreenLUTData = 0;
127 InitialBlueLUTData = 0;
129 if ( Header->IsReadable() )
131 // the following values *may* be modified
132 // by gdcmFile::GetImageDataIntoVectorRaw
133 // we save their initial value.
134 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
135 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
136 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
138 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
139 InitialHighBit = Header->GetEntryByNumber(0x0028,0x0102);
141 // the following entries *may* be removed from the H table
142 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
143 // we keep a pointer on them.
144 InitialRedLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1101);
145 InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
146 InitialBlueLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1103);
148 InitialRedLUTData = Header->GetDocEntryByNumber(0x0028,0x1201);
149 InitialGreenLUTData = Header->GetDocEntryByNumber(0x0028,0x1202);
150 InitialBlueLUTData = Header->GetDocEntryByNumber(0x0028,0x1203);
155 * \brief restores some initial values
156 * \warning not end user intended
158 void gdcmFile::RestoreInitialValues()
160 if ( Header->IsReadable() )
162 // the following values *may* have been modified
163 // by gdcmFile::GetImageDataIntoVectorRaw
164 // we restore their initial value.
165 if ( InitialSpp != "")
166 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
167 if ( InitialPhotInt != "")
168 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
169 if ( InitialPlanConfig != "")
171 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
172 if ( InitialBitsAllocated != "")
173 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
174 if ( InitialHighBit != "")
175 Header->SetEntryByNumber(InitialHighBit,0x0028,0x0102);
177 // the following entries *may* be have been removed from the H table
178 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
181 if (InitialRedLUTDescr)
182 Header->AddEntry(InitialRedLUTDescr);
183 if (InitialGreenLUTDescr)
184 Header->AddEntry(InitialGreenLUTDescr);
185 if (InitialBlueLUTDescr)
186 Header->AddEntry(InitialBlueLUTDescr);
188 if (InitialRedLUTData)
189 Header->AddEntry(InitialBlueLUTDescr);
190 if (InitialGreenLUTData)
191 Header->AddEntry(InitialGreenLUTData);
192 if (InitialBlueLUTData)
193 Header->AddEntry(InitialBlueLUTData);
198 * \brief delete initial values (il they were saved)
199 * of InitialLutDescriptors and InitialLutData
201 void gdcmFile::DeleteInitialValues()
204 // InitialLutDescriptors and InitialLutData
205 // will have to be deleted if the don't belong any longer
206 // to the Header H table when the header is deleted...
208 if ( InitialRedLUTDescr )
209 delete InitialRedLUTDescr;
211 if ( InitialGreenLUTDescr )
212 delete InitialGreenLUTDescr;
214 if ( InitialBlueLUTDescr )
215 delete InitialBlueLUTDescr;
217 if ( InitialRedLUTData )
218 delete InitialRedLUTData;
220 if ( InitialGreenLUTData != NULL)
221 delete InitialGreenLUTData;
223 if ( InitialBlueLUTData != NULL)
224 delete InitialBlueLUTData;
227 //-----------------------------------------------------------------------------
230 //-----------------------------------------------------------------------------
234 * \brief computes the length (in bytes) we must ALLOCATE to receive the
235 * image(s) pixels (multiframes taken into account)
236 * \warning : it is NOT the group 7FE0 length
237 * (no interest for compressed images).
239 int gdcmFile::ComputeDecompressedPixelDataSizeFromHeader()
241 // see PS 3.3-2003 : C.7.6.3.2.1
251 // YBR_FULL_422 (no LUT, no Palette)
257 // ex : gdcm-US-ALOKA-16.dcm
258 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
259 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
260 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
262 // ex : OT-PAL-8-face.dcm
263 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
264 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
265 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
267 // Number of "Bits Allocated"
268 int numberBitsAllocated = Header->GetBitsAllocated();
269 if ( ( numberBitsAllocated == 0 ) || ( numberBitsAllocated == 12 ) )
271 numberBitsAllocated = 16;
274 int DecompressedSize = Header->GetXSize()
277 * ( numberBitsAllocated / 8 )
278 * Header->GetSamplesPerPixel();
280 return DecompressedSize;
284 * \brief - Allocates necessary memory,
285 * - Reads the pixels from disk (uncompress if necessary),
286 * - Transforms YBR pixels, if any, into RGB pixels
287 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
288 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
289 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
290 * @return Pointer to newly allocated pixel data.
291 * NULL if alloc fails
293 uint8_t* gdcmFile::GetImageData()
296 // I need to deallocate Pixel_Data before doing any allocation:
299 if ( LastAllocatedPixelDataLength != ImageDataSize )
302 Pixel_Data = new uint8_t[ImageDataSize];
306 LastAllocatedPixelDataLength = ImageDataSize;
308 // we load the pixels (and transform grey level + LUT into RGB)
309 GetImageDataIntoVector(Pixel_Data, ImageDataSize);
311 // We say the value *is* loaded.
312 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
313 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
315 // Will be 7fe0, 0010 in standard case
316 GetHeader()->SetEntryBinAreaByNumber( Pixel_Data,
317 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
319 PixelRead = 0; // no PixelRaw
326 * Read the pixels from disk (uncompress if necessary),
327 * Transforms YBR pixels, if any, into RGB pixels
328 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
329 * Transforms single Grey plane + 3 Palettes into a RGB Plane
330 * Copies at most MaxSize bytes of pixel data to caller allocated
332 * \warning This function allows people that want to build a volume
333 * from an image stack *not to* have, first to get the image pixels,
334 * and then move them to the volume area.
335 * It's absolutely useless for any VTK user since vtk chooses
336 * to invert the lines of an image, that is the last line comes first
337 * (for some axis related reasons?). Hence he will have
338 * to load the image line by line, starting from the end.
339 * VTK users have to call GetImageData
341 * @param destination Address (in caller's memory space) at which the
342 * pixel data should be copied
343 * @param maxSize Maximum number of bytes to be copied. When MaxSize
344 * is not sufficient to hold the pixel data the copy is not
345 * executed (i.e. no partial copy).
346 * @return On success, the number of bytes actually copied. Zero on
347 * failure e.g. MaxSize is lower than necessary.
349 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
351 GetImageDataIntoVectorRaw (destination, maxSize);
352 PixelRead = 0 ; // =0 : no ImageDataRaw
353 if ( !Header->HasLUT() )
355 return ImageDataSize;
358 // from Lut R + Lut G + Lut B
359 uint8_t *newDest = new uint8_t[ImageDataSize];
360 uint8_t *a = (uint8_t *)destination;
361 uint8_t *lutRGBA = Header->GetLUTRGBA();
366 // move Gray pixels to temp area
367 memmove(newDest, destination, ImageDataSizeRaw);
368 for (size_t i=0; i<ImageDataSizeRaw; ++i)
378 // now, it's an RGB image
379 // Lets's write it in the Header
381 // FIXME : Better use CreateOrReplaceIfExist ?
383 std::string spp = "3"; // Samples Per Pixel
384 Header->SetEntryByNumber(spp,0x0028,0x0002);
385 std::string rgb = "RGB "; // Photometric Interpretation
386 Header->SetEntryByNumber(rgb,0x0028,0x0004);
387 std::string planConfig = "0"; // Planar Configuration
388 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
391 else // GetLUTRGBA() failed
393 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
394 // that are *more* than 65535 long ?!?
395 // No idea how to manage such an image !
396 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
397 // It seems that *no Dicom Viewer* has any idea :-(
399 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
400 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
403 /// \todo Drop Palette Color out of the Header?
404 return ImageDataSize;
408 * \brief Allocates necessary memory,
409 * Transforms YBR pixels (if any) into RGB pixels
410 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
411 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
412 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
413 * @return Pointer to newly allocated pixel data.
414 * \ NULL if alloc fails
416 uint8_t* gdcmFile::GetImageDataRaw ()
419 if ( Header->HasLUT() )
420 /// \todo Let gdcmHeader user a chance to get the right value
421 imgDataSize = ImageDataSizeRaw;
423 imgDataSize = ImageDataSize;
426 // I need to deallocate Pixel_Data before doing any allocation:
429 if ( LastAllocatedPixelDataLength != imgDataSize )
432 Pixel_Data = new uint8_t[imgDataSize];
436 LastAllocatedPixelDataLength = imgDataSize;
438 // we load the pixels ( grey level or RGB, but NO transformation)
439 GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
441 // We say the value *is* loaded.
442 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
443 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
445 // will be 7fe0, 0010 in standard cases
446 GetHeader()->SetEntryBinAreaByNumber(Pixel_Data,
447 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
449 PixelRead = 1; // PixelRaw
455 * \brief Copies at most MaxSize bytes of pixel data to caller's
457 * \warning This function was designed to avoid people that want to build
458 * a volume from an image stack to need first to get the image pixels
459 * and then move them to the volume area.
460 * It's absolutely useless for any VTK user since vtk chooses
461 * to invert the lines of an image, that is the last line comes first
462 * (for some axis related reasons?). Hence he will have
463 * to load the image line by line, starting from the end.
464 * VTK users hace to call GetImageData
465 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
466 * into a single RGB Pixels Plane
467 * the (VTK) user will manage the palettes
469 * @param destination Address (in caller's memory space) at which the
470 * pixel data should be copied
471 * @param maxSize Maximum number of bytes to be copied. When MaxSize
472 * is not sufficient to hold the pixel data the copy is not
473 * executed (i.e. no partial copy).
474 * @return On success, the number of bytes actually copied. Zero on
475 * failure e.g. MaxSize is lower than necessary.
477 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t maxSize)
479 // we save the initial values of the following
480 // in order to be able to restore the header in a disk-consistent state
481 // (if user asks twice to get the pixels from disk)
483 if ( PixelRead != -1 ) // File was "read" before
485 RestoreInitialValues();
488 PixelRead = 1 ; // PixelRaw
490 if ( ImageDataSize > maxSize )
492 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
493 "than caller's expected MaxSize");
497 ReadPixelData( destination );
499 // Number of Bits Allocated for storing a Pixel
500 int numberBitsAllocated = Header->GetBitsAllocated();
501 if ( numberBitsAllocated == 0 )
503 numberBitsAllocated = 16;
506 // Number of Bits actually used
507 int numberBitsStored = Header->GetBitsStored();
508 if ( numberBitsStored == 0 )
510 numberBitsStored = numberBitsAllocated;
514 int highBitPosition = Header->GetHighBitPosition();
515 if ( highBitPosition == 0 )
517 highBitPosition = numberBitsAllocated - 1;
520 bool signedPixel = Header->IsSignedPixelData();
523 ////////////////////////////////////////////////////////
524 // ENDIANITY SECTION: re-arange bytes inside the integer
525 if ( numberBitsAllocated != 8 )
527 SwapZone( destination, Header->GetSwapCode(), ImageDataSize,
528 numberBitsAllocated );
531 // to avoid pb with some xmedcon breakers images
532 if ( ( numberBitsAllocated == 16 )
533 && ( numberBitsStored < numberBitsAllocated )
534 && ( ! signedPixel ) )
536 int l = (int)(ImageDataSize / (numberBitsAllocated/8));
537 uint16_t *deb = (uint16_t *)destination;
538 for(int i = 0; i<l; i++)
549 //////////////////////////////////
550 // re arange bits inside the bytes
551 if ( numberBitsStored != numberBitsAllocated )
553 int l = (int)(ImageDataSize / (numberBitsAllocated/8));
554 if ( numberBitsAllocated == 16 )
556 uint16_t mask = 0xffff;
557 mask = mask >> ( numberBitsAllocated - numberBitsStored );
558 uint16_t *deb = (uint16_t *)destination;
559 for(int i = 0; i<l; i++)
561 *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
565 else if ( numberBitsAllocated == 32 )
567 uint32_t mask = 0xffffffff;
568 mask = mask >> ( numberBitsAllocated - numberBitsStored );
569 uint32_t *deb = (uint32_t *)destination;
570 for(int i = 0; i<l; i++)
572 *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
578 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
585 DebugFile = fopen( "SpuriousFile.RAW", "wb" );
586 fwrite( PixelConvertor.GetUncompressed(),
587 PixelConvertor.GetUncompressedsSize(),
593 //////////////////////////////////
594 // Deal with the color
596 // Monochrome pictures don't require color intervention
597 if ( Header->IsMonochrome() )
599 return ImageDataSize;
602 // Planar configuration = 0 : Pixels are already RGB
603 // Planar configuration = 1 : 3 planes : R, G, B
604 // Planar configuration = 2 : 1 gray Plane + 3 LUT
606 // Well ... supposed to be !
607 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
608 // PhotometricInterpretation=PALETTE COLOR
609 // and heuristic has to be found :-(
611 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
613 // Whatever Planar Configuration is,
614 // "PALETTE COLOR " implies that we deal with the palette.
615 if ( Header->IsPaletteColor() )
623 // Pixels are already RGB
626 if ( Header->IsYBRFull() )
628 // Warning : YBR_FULL_422 acts as RGB
629 // : we need to make RGB Pixels from Planes Y,cB,cR
631 // to see the tricks about YBR_FULL, YBR_FULL_422,
632 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
633 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
634 // and be *very* affraid
636 int l = Header->GetXSize() * Header->GetYSize();
637 int nbFrames = Header->GetZSize();
639 uint8_t* newDest = new uint8_t[ImageDataSize];
640 uint8_t* x = newDest;
641 uint8_t* a = (uint8_t*)destination;
646 /// \todo : Replace by the 'well known' integer computation
648 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
649 /// for code optimisation
651 for (int i = 0; i < nbFrames; i++)
653 for (int j = 0; j < l; j++)
655 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
656 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
657 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
659 if (R < 0.0) R = 0.0;
660 if (G < 0.0) G = 0.0;
661 if (B < 0.0) B = 0.0;
662 if (R > 255.0) R = 255.0;
663 if (G > 255.0) G = 255.0;
664 if (B > 255.0) B = 255.0;
672 memmove(destination, newDest, ImageDataSize);
677 // need to make RGB Pixels from R,G,B Planes
678 // (all the Frames at a time)
680 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
682 uint8_t *newDest = new uint8_t[ImageDataSize];
683 uint8_t *x = newDest;
684 uint8_t *a = (uint8_t *)destination;
688 for (int j = 0; j < l; j++)
694 memmove(destination, newDest, ImageDataSize);
699 // Palettes were found
700 // Let the user deal with them !
701 return ImageDataSize;
703 // now, it's an RGB image
704 // Lets's write it in the Header
706 // Droping Palette Color out of the Header
707 // has been moved to the Write process.
709 // TODO : move 'values' modification to the write process
710 // : save also (in order to be able to restore)
711 // : 'high bit' -when not equal to 'bits stored' + 1
712 // : 'bits allocated', when it's equal to 12 ?!
714 std::string spp = "3"; // Samples Per Pixel
715 std::string photInt = "RGB "; // Photometric Interpretation
716 std::string planConfig = "0"; // Planar Configuration
718 Header->SetEntryByNumber(spp,0x0028,0x0002);
719 Header->SetEntryByNumber(photInt,0x0028,0x0004);
720 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
722 return ImageDataSize;
726 * \brief Points the internal Pixel_Data pointer to the callers inData
727 * image representation, BUT WITHOUT COPYING THE DATA.
728 * 'image' Pixels are presented as C-like 2D arrays : line per line.
729 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
730 * \warning Since the pixels are not copied, it is the caller's responsability
731 * not to deallocate it's data before gdcm uses them (e.g. with
732 * the Write() method.
733 * @param inData user supplied pixel area
734 * @param expectedSize total image size, in Bytes
738 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
740 Header->SetImageDataSize( expectedSize );
741 // FIXME : if already allocated, memory leak !
743 ImageDataSize = ImageDataSizeRaw = expectedSize;
745 // FIXME : 7fe0, 0010 IS NOT set ...
750 * \brief Writes on disk A SINGLE Dicom file
751 * NO test is performed on processor "Endiannity".
752 * It's up to the user to call his Reader properly
753 * @param fileName name of the file to be created
754 * (any already existing file is over written)
755 * @return false if write fails
758 bool gdcmFile::WriteRawData(std::string const & fileName)
760 FILE* fp1 = fopen(fileName.c_str(), "wb");
763 printf("Fail to open (write) file [%s] \n", fileName.c_str());
766 fwrite (Pixel_Data, ImageDataSize, 1, fp1);
773 * \brief Writes on disk A SINGLE Dicom file,
774 * using the Implicit Value Representation convention
775 * NO test is performed on processor "Endiannity".
776 * @param fileName name of the file to be created
777 * (any already existing file is overwritten)
778 * @return false if write fails
781 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
783 return WriteBase(fileName, gdcmImplicitVR);
787 * \brief Writes on disk A SINGLE Dicom file,
788 * using the Explicit Value Representation convention
789 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
790 * (any already existing file is overwritten)
791 * @return false if write fails
794 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
796 return WriteBase(fileName, gdcmExplicitVR);
800 * \brief Writes on disk A SINGLE Dicom file,
801 * using the ACR-NEMA convention
802 * NO test is performed on processor "Endiannity".
803 * (a l'attention des logiciels cliniques
804 * qui ne prennent en entrée QUE des images ACR ...
805 * \warning if a DICOM_V3 header is supplied,
806 * groups < 0x0008 and shadow groups are ignored
807 * \warning NO TEST is performed on processor "Endiannity".
808 * @param fileName name of the file to be created
809 * (any already existing file is overwritten)
810 * @return false if write fails
813 bool gdcmFile::WriteAcr (std::string const & fileName)
815 return WriteBase(fileName, gdcmACR);
818 //-----------------------------------------------------------------------------
821 * \brief NOT a end user inteded function
822 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
823 * @param fileName name of the file to be created
824 * (any already existing file is overwritten)
825 * @param type file type (ExplicitVR, ImplicitVR, ...)
826 * @return false if write fails
828 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
830 if ( PixelRead == -1 && type != gdcmExplicitVR)
835 FILE* fp1 = fopen(fileName.c_str(), "wb");
838 printf("Failed to open (write) File [%s] \n", fileName.c_str());
842 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
844 // writing Dicom File Preamble
845 uint8_t* filePreamble = new uint8_t[128];
846 memset(filePreamble, 0, 128);
847 fwrite(filePreamble, 128, 1, fp1);
848 fwrite("DICM", 4, 1, fp1);
850 delete[] filePreamble;
853 // --------------------------------------------------------------
854 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
856 // if recognition code tells us we dealt with a LibIDO image
857 // we reproduce on disk the switch between lineNumber and columnNumber
858 // just before writting ...
860 /// \todo the best trick would be *change* the recognition code
861 /// but pb expected if user deals with, e.g. COMPLEX images
863 std::string rows, columns;
864 if ( Header->GetFileType() == gdcmACR_LIBIDO)
866 rows = Header->GetEntryByNumber(0x0028, 0x0010);
867 columns = Header->GetEntryByNumber(0x0028, 0x0011);
869 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
870 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
872 // ----------------- End of Special Patch ----------------
874 uint16_t grPixel = Header->GetGrPixel();
875 uint16_t numPixel = Header->GetNumPixel();;
877 gdcmDocEntry* PixelElement =
878 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
880 if ( PixelRead == 1 )
882 // we read pixel 'as is' (no tranformation LUT -> RGB)
883 PixelElement->SetLength( ImageDataSizeRaw );
885 else if ( PixelRead == 0 )
887 // we tranformed GrayLevel pixels + LUT into RGB Pixel
888 PixelElement->SetLength( ImageDataSize );
891 Header->Write(fp1, type);
893 // --------------------------------------------------------------
894 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
896 // ...and we restore the Header to be Dicom Compliant again
897 // just after writting
899 if ( Header->GetFileType() == gdcmACR_LIBIDO )
901 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
902 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
904 // ----------------- End of Special Patch ----------------
906 // fwrite(Pixel_Data, ImageDataSize, 1, fp1); // should be useless, now
912 //-----------------------------------------------------------------------------
915 * \brief Swap the bytes, according to swap code.
916 * \warning not end user intended
917 * @param im area to deal with
918 * @param swap swap code
919 * @param lgr Area Length
920 * @param nb Pixels Bit number
922 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb)
928 uint16_t* im16 = (uint16_t*)im;
939 for(i=0; i < lgr/2; i++)
941 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
945 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
952 uint16_t fort, faible;
953 uint32_t* im32 = (uint32_t*)im;
960 for(i = 0; i < lgr/4; i++)
962 faible = im32[i] & 0x0000ffff; // 4321
963 fort = im32[i] >> 16;
964 fort = ( fort >> 8 ) | ( fort << 8 );
965 faible = ( faible >> 8 ) | ( faible << 8);
967 im32[i] = ( s32 << 16 ) | fort;
971 for(i = 0; i < lgr/4; i++)
973 faible = im32[i] & 0x0000ffff; // 2143
974 fort = im32[i] >> 16;
975 fort = ( fort >> 8 ) | ( fort << 8 );
976 faible = ( faible >> 8) | ( faible << 8);
978 im32[i] = ( s32 << 16 ) | faible;
982 for(i = 0; i < lgr/4; i++)
984 faible = im32[i] & 0x0000ffff; // 3412
985 fort = im32[i] >> 16;
987 im32[i] = ( s32 << 16 ) | fort;
991 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
998 * \brief Read pixel data from disk (optionaly decompressing) into the
999 * caller specified memory location.
1000 * @param destination where the pixel data should be stored.
1003 bool gdcmFile::ReadPixelData(void* destination)
1005 FILE* fp = Header->OpenFile();
1011 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1013 Header->CloseFile();
1017 // ---------------------- Compacted File (12 Bits Per Pixel)
1018 // unpack 12 Bits pixels into 16 Bits pixels
1019 // 2 pixels 12bit = [0xABCDEF]
1020 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1022 if ( Header->GetBitsAllocated() == 12 )
1024 int nbPixels = Header->GetXSize() * Header->GetYSize();
1027 uint16_t* pdestination = (uint16_t*)destination;
1028 for(int p = 0; p < nbPixels; p += 2 )
1034 //Two steps is necessary to please VC++
1035 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1037 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1040 // Troubles expected on Big-Endian processors ?
1043 Header->CloseFile();
1047 // ---------------------- Uncompressed File
1048 if ( !Header->IsDicomV3() ||
1049 Header->IsImplicitVRLittleEndianTransferSyntax() ||
1050 Header->IsExplicitVRLittleEndianTransferSyntax() ||
1051 Header->IsExplicitVRBigEndianTransferSyntax() ||
1052 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1054 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1055 Header->CloseFile();
1056 if ( ItemRead != 1 )
1066 // ---------------------- Run Length Encoding
1067 if ( Header->IsRLELossLessTransferSyntax() )
1069 bool res = gdcm_read_RLE_file (fp,destination);
1070 Header->CloseFile();
1074 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1076 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1077 if ( str_nb == GDCM_UNFOUND )
1083 nb = atoi( str_nb.c_str() );
1086 nb = 16; // ?? 12 should be ACR-NEMA only
1091 int taille = Header->GetXSize() * Header->GetYSize()
1092 * Header->GetSamplesPerPixel();
1093 long fragmentBegining; // for ftell, fseek
1095 bool jpg2000 = Header->IsJPEG2000();
1096 bool jpgLossless = Header->IsJPEGLossless();
1099 uint16_t ItemTagGr, ItemTagEl;
1102 // Position on begining of Jpeg Pixels
1104 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1105 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1106 if(Header->GetSwapCode())
1108 ItemTagGr = Header->SwapShort(ItemTagGr);
1109 ItemTagEl = Header->SwapShort(ItemTagEl);
1113 if( Header->GetSwapCode() )
1115 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1120 // What is it used for ?!?
1121 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1122 fread(BasicOffsetTableItemValue,ln,1,fp);
1123 //delete[] BasicOffsetTableItemValue;
1126 // first Fragment initialisation
1127 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1128 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1129 if( Header->GetSwapCode() )
1131 ItemTagGr = Header->SwapShort( ItemTagGr );
1132 ItemTagEl = Header->SwapShort( ItemTagEl );
1135 // parsing fragments until Sequence Delim. Tag found
1136 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1138 // --- for each Fragment
1140 if( Header->GetSwapCode() )
1142 ln = Header->SwapLong(ln); // Fragment Item length
1144 fragmentBegining = ftell( fp );
1148 // JPEG 2000 : call to ???
1149 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1150 // ------------------------------------- endif (JPEG2000)
1152 else if (jpgLossless)
1154 // JPEG LossLess : call to xmedcom Lossless JPEG
1155 // Reading Fragment pixels
1156 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1157 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1158 res = 1; // in order not to break the loop
1160 } // ------------------------------------- endif (JPEGLossless)
1163 // JPEG Lossy : call to IJG 6b
1164 if ( Header->GetBitsStored() == 8)
1166 // Reading Fragment pixels
1167 res = gdcm_read_JPEG_file (fp,destination);
1171 // Reading Fragment pixels
1172 res = gdcm_read_JPEG_file12 (fp,destination);
1174 // ------------------------------------- endif (JPEGLossy)
1182 // location in user's memory
1183 // for next fragment (if any)
1184 destination = (uint8_t*)destination + taille * nBytes;
1186 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1187 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1189 ItemTagGr = ItemTagEl = 0;
1190 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1191 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1192 if( Header->GetSwapCode() )
1194 ItemTagGr = Header->SwapShort( ItemTagGr );
1195 ItemTagEl = Header->SwapShort( ItemTagEl );
1198 // endWhile parsing fragments until Sequence Delim. Tag found
1200 Header->CloseFile();
1203 //-----------------------------------------------------------------------------