1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/09/10 18:54:38 $
7 Version: $Revision: 1.124 $
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 Sets some initial for the Constructor
75 void gdcmFile::SetInitialValues()
77 PixelRead = -1; // no ImageData read yet.
78 LastAllocatedPixelDataLength = 0;
83 InitialPlanConfig = "";
84 InitialBitsAllocated = "";
86 InitialRedLUTDescr = 0;
87 InitialGreenLUTDescr = 0;
88 InitialBlueLUTDescr = 0;
89 InitialRedLUTData = 0;
90 InitialGreenLUTData = 0;
91 InitialBlueLUTData = 0;
93 if ( Header->IsReadable() )
95 SetPixelDataSizeFromHeader();
97 // the following values *may* be modified
98 // by gdcmFile::GetImageDataIntoVectorRaw
99 // we save their initial value.
100 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
101 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
102 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
103 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
105 // the following entries *may* be removed
106 // by gdcmFile::GetImageDataIntoVectorRaw
109 // we SHALL save them !
110 // (some troubles, now)
112 InitialRedLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1101);
113 InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
114 InitialBlueLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1103);
115 InitialRedLUTData = Header->GetDocEntryByNumber(0x0028,0x1201);
116 InitialGreenLUTData = Header->GetDocEntryByNumber(0x0028,0x1202);
117 InitialBlueLUTData = Header->GetDocEntryByNumber(0x0028,0x1203);
119 if (InitialRedLUTData == NULL)
120 std::cout << "echec InitialRedLUTData " << std::endl;
123 printf("%p\n",InitialRedLUTData);
124 InitialRedLUTData->Print(); std::cout <<std::endl;
132 * \brief canonical destructor
133 * \note If the gdcmHeader was created by the gdcmFile constructor,
134 * it is destroyed by the gdcmFile
136 gdcmFile::~gdcmFile()
144 if ( InitialRedLUTDescr )
145 delete InitialRedLUTDescr;
147 if ( InitialGreenLUTDescr )
148 delete InitialGreenLUTDescr;
150 if ( InitialBlueLUTDescr )
151 delete InitialBlueLUTDescr;
155 if ( InitialRedLUTData )
156 delete InitialRedLUTData;
158 if ( InitialGreenLUTData != NULL)
159 delete InitialGreenLUTData;
161 if ( InitialBlueLUTData != NULL)
162 delete InitialBlueLUTData;
166 //-----------------------------------------------------------------------------
169 //-----------------------------------------------------------------------------
174 * \brief computes the length (in bytes) we must ALLOCATE to receive the
175 * image(s) pixels (multiframes taken into account)
176 * \warning : it is NOT the group 7FE0 length
177 * (no interest for compressed images).
178 * \warning : not end user intended ?
180 void gdcmFile::SetPixelDataSizeFromHeader()
182 // see PS 3.3-2003 : C.7.6.3.2.1
192 // YBR_FULL_422 (no LUT, no Palette)
198 // ex : gdcm-US-ALOKA-16.dcm
199 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
200 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
201 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
203 // ex : OT-PAL-8-face.dcm
204 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
205 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
206 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
208 // Number of "Bits Allocated"
210 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
212 if ( str_nb == GDCM_UNFOUND )
218 nb = atoi( str_nb.c_str() );
225 ImageDataSizeRaw = Header->GetXSize() * Header->GetYSize()
226 * Header->GetZSize() * (nb/8) * Header->GetSamplesPerPixel();
227 std::string str_PhotometricInterpretation =
228 Header->GetEntryByNumber(0x0028,0x0004);
230 // if ( str_PhotometricInterpretation == "PALETTE COLOR " ),
231 // pb when undealt Segmented Palette Color
233 if ( Header->HasLUT() )
241 * \brief - Allocates necessary memory,
242 * - Reads the pixels from disk (uncompress if necessary),
243 * - Transforms YBR pixels, if any, into RGB pixels
244 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
245 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
246 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
247 * @return Pointer to newly allocated pixel data.
248 * NULL if alloc fails
250 void *gdcmFile::GetImageData()
253 // I need to deallocate Pixel_Data before doing any allocation:
256 if ( LastAllocatedPixelDataLength != ImageDataSize )
259 Pixel_Data = new uint8_t[ImageDataSize];
263 LastAllocatedPixelDataLength = ImageDataSize;
265 // we load the pixels (and transform grey level + LUT into RGB)
266 GetImageDataIntoVector(Pixel_Data, ImageDataSize);
268 // We say the value *is* loaded.
269 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
270 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
272 // Will be 7fe0, 0010 in standard case
273 GetHeader()->SetEntryVoidAreaByNumber( Pixel_Data,
274 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
276 PixelRead = 0; // no PixelRaw
284 * Read the pixels from disk (uncompress if necessary),
285 * Transforms YBR pixels, if any, into RGB pixels
286 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
287 * Transforms single Grey plane + 3 Palettes into a RGB Plane
288 * Copies at most MaxSize bytes of pixel data to caller allocated
290 * \warning This function allows people that want to build a volume
291 * from an image stack *not to* have, first to get the image pixels,
292 * and then move them to the volume area.
293 * It's absolutely useless for any VTK user since vtk chooses
294 * to invert the lines of an image, that is the last line comes first
295 * (for some axis related reasons?). Hence he will have
296 * to load the image line by line, starting from the end.
297 * VTK users have to call GetImageData
299 * @param destination Address (in caller's memory space) at which the
300 * pixel data should be copied
301 * @param maxSize Maximum number of bytes to be copied. When MaxSize
302 * is not sufficient to hold the pixel data the copy is not
303 * executed (i.e. no partial copy).
304 * @return On success, the number of bytes actually copied. Zero on
305 * failure e.g. MaxSize is lower than necessary.
307 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
309 GetImageDataIntoVectorRaw (destination, maxSize);
310 PixelRead = 0 ; // =0 : no ImageDataRaw
311 if ( !Header->HasLUT() )
313 return ImageDataSize;
316 // from Lut R + Lut G + Lut B
317 uint8_t *newDest = new uint8_t[ImageDataSize];
318 uint8_t *a = (uint8_t *)destination;
319 uint8_t *lutRGBA = Header->GetLUTRGBA();
324 // move Gray pixels to temp area
325 memmove(newDest, destination, ImageDataSizeRaw);
326 for (size_t i=0; i<ImageDataSizeRaw; ++i)
336 // now, it's an RGB image
337 // Lets's write it in the Header
339 // FIXME : Better use CreateOrReplaceIfExist ?
341 std::string spp = "3"; // Samples Per Pixel
342 Header->SetEntryByNumber(spp,0x0028,0x0002);
343 std::string rgb = "RGB "; // Photometric Interpretation
344 Header->SetEntryByNumber(rgb,0x0028,0x0004);
345 std::string planConfig = "0"; // Planar Configuration
346 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
349 else // GetLUTRGBA() failed
351 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
352 // that are *more* than 65535 long ?!?
353 // No idea how to manage such an image !
354 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
355 // It seems that *no Dicom Viewer* has any idea :-(
357 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
358 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
361 /// \todo Drop Palette Color out of the Header?
362 return ImageDataSize;
367 * \brief Allocates necessary memory,
368 * Transforms YBR pixels (if any) into RGB pixels
369 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
370 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
371 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
372 * @return Pointer to newly allocated pixel data.
373 * \ NULL if alloc fails
375 void * gdcmFile::GetImageDataRaw ()
378 if ( Header->HasLUT() )
379 /// \todo Let gdcmHeader user a chance to get the right value
380 imgDataSize = ImageDataSizeRaw;
382 imgDataSize = ImageDataSize;
385 // I need to deallocate Pixel_Data before doing any allocation:
388 if ( LastAllocatedPixelDataLength != imgDataSize )
391 Pixel_Data = new uint8_t[imgDataSize];
395 LastAllocatedPixelDataLength = imgDataSize;
397 // we load the pixels ( grey level or RGB, but NO transformation)
398 GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
400 // We say the value *is* loaded.
401 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
402 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
404 // will be 7fe0, 0010 in standard cases
405 GetHeader()->SetEntryVoidAreaByNumber(Pixel_Data,
406 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
408 PixelRead = 1; // PixelRaw
415 * \brief Copies at most MaxSize bytes of pixel data to caller's
417 * \warning This function was designed to avoid people that want to build
418 * a volume from an image stack to need first to get the image pixels
419 * and then move them to the volume area.
420 * It's absolutely useless for any VTK user since vtk chooses
421 * to invert the lines of an image, that is the last line comes first
422 * (for some axis related reasons?). Hence he will have
423 * to load the image line by line, starting from the end.
424 * VTK users hace to call GetImageData
425 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
426 * into a single RGB Pixels Plane
427 * the (VTK) user will manage the palettes
429 * @param destination Address (in caller's memory space) at which the
430 * pixel data should be copied
431 * @param maxSize Maximum number of bytes to be copied. When MaxSize
432 * is not sufficient to hold the pixel data the copy is not
433 * executed (i.e. no partial copy).
434 * @return On success, the number of bytes actually copied. Zero on
435 * failure e.g. MaxSize is lower than necessary.
437 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t maxSize)
439 int nb, nbu, highBit, sign;
441 // we save the initial values of the following
442 // in order to be able to restore the header in a disk-consistent state
443 // (if user asks twice to get the pixels from disk)
445 if ( PixelRead == -1 ) // File was never "read" before
447 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
448 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
449 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
450 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
452 else // File was already "read", the following *may* have been modified
453 // we restore them to be in a disk-consistent state
455 // FIXME : What happened with the LUTs ?
456 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
457 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
458 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
459 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
462 PixelRead = 1 ; // PixelRaw
464 if ( ImageDataSize > maxSize )
466 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
467 "than caller's expected MaxSize");
471 ReadPixelData( destination );
473 // Number of Bits Allocated for storing a Pixel
474 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
475 if ( str_nb == GDCM_UNFOUND )
481 nb = atoi( str_nb.c_str() );
483 // From reading SetPixelDataSizeFromHeader, it seems 12 should be treated
484 // separately, correct ?
487 // Number of Bits actually used
488 std::string str_nbu = Header->GetEntryByNumber(0x0028,0x0101);
489 if ( str_nbu == GDCM_UNFOUND )
495 nbu = atoi( str_nbu.c_str() );
499 std::string str_highBit = Header->GetEntryByNumber(0x0028,0x0102);
500 if ( str_highBit == GDCM_UNFOUND )
506 highBit = atoi( str_highBit.c_str() );
512 std::string str_sign = Header->GetEntryByNumber(0x0028,0x0103);
513 if ( str_sign == GDCM_UNFOUND )
515 sign = 0; // default is unsigned
519 sign = atoi( str_sign.c_str() );
522 // re arange bytes inside the integer (processor endianity)
525 SwapZone(destination, Header->GetSwapCode(), ImageDataSize, nb);
528 // to avoid pb with some xmedcon breakers images
529 if ( nb == 16 && nbu < nb && sign == 0)
531 int l = (int)(ImageDataSize / (nb/8));
532 uint16_t *deb = (uint16_t *)destination;
533 for(int i = 0; i<l; i++)
543 // re arange bits inside the bytes
546 int l = (int)(ImageDataSize / (nb/8));
549 uint16_t mask = 0xffff;
550 mask = mask >> (nb-nbu);
551 uint16_t *deb = (uint16_t *)destination;
552 for(int i = 0; i<l; i++)
554 *deb = (*deb >> (nbu - highBit - 1)) & mask;
560 uint32_t mask = 0xffffffff;
561 mask = mask >> (nb - nbu);
562 uint32_t *deb = (uint32_t *)destination;
563 for(int i = 0; i<l; i++)
565 *deb = (*deb >> (nbu - highBit - 1)) & mask;
571 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
575 // DO NOT remove this code commented out.
576 // Nobody knows what's expecting you ...
577 // Just to 'see' what was actually read on disk :-(
580 // f2 = fopen("SpuriousFile.RAW","wb");
581 // fwrite(destination,ImageDataSize,1,f2);
584 // Deal with the color
585 // -------------------
587 std::string str_PhotometricInterpretation =
588 Header->GetEntryByNumber(0x0028,0x0004);
590 if ( str_PhotometricInterpretation == "MONOCHROME1 "
591 || str_PhotometricInterpretation == "MONOCHROME2 " )
593 return ImageDataSize;
596 // Planar configuration = 0 : Pixels are already RGB
597 // Planar configuration = 1 : 3 planes : R, G, B
598 // Planar configuration = 2 : 1 gray Plane + 3 LUT
600 // Well ... supposed to be !
601 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
602 // PhotometricInterpretation=PALETTE COLOR
603 // and heuristic has to be found :-(
605 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
607 // Whatever Planar Configuration is,
608 // "PALETTE COLOR " implies that we deal with the palette.
609 if ( str_PhotometricInterpretation == "PALETTE COLOR ")
617 // Pixels are already RGB
620 if (str_PhotometricInterpretation == "YBR_FULL")
622 // Warning : YBR_FULL_422 acts as RGB
623 // : we need to make RGB Pixels from Planes Y,cB,cR
625 // to see the tricks about YBR_FULL, YBR_FULL_422,
626 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
627 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
628 // and be *very* affraid
630 int l = Header->GetXSize() * Header->GetYSize();
631 int nbFrames = Header->GetZSize();
633 uint8_t* newDest = new uint8_t[ImageDataSize];
634 uint8_t* x = newDest;
635 uint8_t* a = (uint8_t*)destination;
640 /// \todo : Replace by the 'well known' integer computation
642 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
643 /// for code optimisation
645 for (int i = 0; i < nbFrames; i++)
647 for (int j = 0; j < l; j++)
649 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
650 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
651 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
653 if (R < 0.0) R = 0.0;
654 if (G < 0.0) G = 0.0;
655 if (B < 0.0) B = 0.0;
656 if (R > 255.0) R = 255.0;
657 if (G > 255.0) G = 255.0;
658 if (B > 255.0) B = 255.0;
666 memmove(destination, newDest, ImageDataSize);
671 // need to make RGB Pixels from R,G,B Planes
672 // (all the Frames at a time)
674 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
676 uint8_t *newDest = new uint8_t[ImageDataSize];
677 uint8_t *x = newDest;
678 uint8_t *a = (uint8_t *)destination;
682 for (int j = 0; j < l; j++)
688 memmove(destination, newDest, ImageDataSize);
693 // Palettes were found
694 // Let the user deal with them !
695 return ImageDataSize;
697 // now, it's an RGB image
698 // Lets's write it in the Header
700 // CreateOrReplaceIfExist ?
702 std::string spp = "3"; // Samples Per Pixel
703 std::string photInt = "RGB "; // Photometric Interpretation
704 std::string planConfig = "0"; // Planar Configuration
708 Header->SetEntryByNumber(spp,0x0028,0x0002);
709 Header->SetEntryByNumber(photInt,0x0028,0x0004);
710 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
712 /// \todo Drop Palette Color out of the Header?
713 return ImageDataSize;
718 * \brief performs a shalow copy (not a deep copy) of the user given
720 * 'image' Pixels are presented as C-like 2D arrays : line per line.
721 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
722 * \warning user is kindly requested NOT TO 'free' the Pixel area
723 * @param inData user supplied pixel area
724 * @param expectedSize total image size, in Bytes
728 bool gdcmFile::SetImageData(void *inData, size_t expectedSize)
730 Header->SetImageDataSize( expectedSize );
731 // FIXME : if already allocated, memory leak !
733 ImageDataSize = ImageDataSizeRaw = expectedSize;
735 // FIXME : 7fe0, 0010 IS NOT set ...
741 * \brief Writes on disk A SINGLE Dicom file
742 * NO test is performed on processor "Endiannity".
743 * It's up to the user to call his Reader properly
744 * @param fileName name of the file to be created
745 * (any already existing file is over written)
746 * @return false if write fails
749 bool gdcmFile::WriteRawData(std::string const & fileName)
751 FILE *fp1 = fopen(fileName.c_str(), "wb");
754 printf("Fail to open (write) file [%s] \n", fileName.c_str());
757 fwrite (Pixel_Data, ImageDataSize, 1, fp1);
765 * \brief Writes on disk A SINGLE Dicom file,
766 * using the Implicit Value Representation convention
767 * NO test is performed on processor "Endiannity".
768 * @param fileName name of the file to be created
769 * (any already existing file is overwritten)
770 * @return false if write fails
773 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
775 return WriteBase(fileName, gdcmImplicitVR);
780 * \brief Writes on disk A SINGLE Dicom file,
781 * using the Explicit Value Representation convention
782 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
783 * (any already existing file is overwritten)
784 * @return false if write fails
787 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
789 return WriteBase(fileName, gdcmExplicitVR);
794 * \brief Writes on disk A SINGLE Dicom file,
795 * using the ACR-NEMA convention
796 * NO test is performed on processor "Endiannity".
797 * (a l'attention des logiciels cliniques
798 * qui ne prennent en entrée QUE des images ACR ...
799 * \warning if a DICOM_V3 header is supplied,
800 * groups < 0x0008 and shadow groups are ignored
801 * \warning NO TEST is performed on processor "Endiannity".
802 * @param fileName name of the file to be created
803 * (any already existing file is overwritten)
804 * @return false if write fails
807 bool gdcmFile::WriteAcr (std::string const & fileName)
809 return WriteBase(fileName, gdcmACR);
812 //-----------------------------------------------------------------------------
816 * \brief NOT a end user inteded function
817 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
818 * @param fileName name of the file to be created
819 * (any already existing file is overwritten)
820 * @param type file type (ExplicitVR, ImplicitVR, ...)
821 * @return false if write fails
823 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
825 if ( PixelRead == -1 && type != gdcmExplicitVR)
830 FILE *fp1 = fopen(fileName.c_str(), "wb");
833 printf("Failed to open (write) File [%s] \n", fileName.c_str());
837 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
839 // writing Dicom File Preamble
840 uint8_t* filePreamble = new uint8_t[128];
841 memset(filePreamble, 0, 128);
842 fwrite(filePreamble, 128, 1, fp1);
843 fwrite("DICM", 4, 1, fp1);
845 delete[] filePreamble;
848 // --------------------------------------------------------------
849 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
851 // if recognition code tells us we dealt with a LibIDO image
852 // we reproduce on disk the switch between lineNumber and columnNumber
853 // just before writting ...
855 /// \todo the best trick would be *change* the recognition code
856 /// but pb expected if user deals with, e.g. COMPLEX images
858 std::string rows, columns;
859 if ( Header->GetFileType() == gdcmACR_LIBIDO)
861 rows = Header->GetEntryByNumber(0x0028, 0x0010);
862 columns = Header->GetEntryByNumber(0x0028, 0x0011);
864 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
865 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
867 // ----------------- End of Special Patch ----------------
869 uint16_t grPixel = Header->GetGrPixel();
870 uint16_t numPixel = Header->GetNumPixel();;
872 gdcmDocEntry* PixelElement =
873 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
875 if ( PixelRead == 1 )
877 // we read pixel 'as is' (no tranformation LUT -> RGB)
878 PixelElement->SetLength( ImageDataSizeRaw );
880 else if ( PixelRead == 0 )
882 // we tranformed GrayLevel pixels + LUT into RGB Pixel
883 PixelElement->SetLength( ImageDataSize );
886 Header->Write(fp1, type);
888 // --------------------------------------------------------------
889 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
891 // ...and we restore the Header to be Dicom Compliant again
892 // just after writting
894 if ( Header->GetFileType() == gdcmACR_LIBIDO )
896 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
897 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
899 // ----------------- End of Special Patch ----------------
901 // fwrite(Pixel_Data, ImageDataSize, 1, fp1); // should be useless, now
907 //-----------------------------------------------------------------------------
911 * \brief Swap the bytes, according to swap code.
912 * \warning not end user intended
913 * @param im area to deal with
914 * @param swap swap code
915 * @param lgr Area Length
916 * @param nb Pixels Bit number
918 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb)
924 uint16_t* im16 = (uint16_t*)im;
935 for(i=0; i < lgr/2; i++)
937 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
941 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
948 uint16_t fort, faible;
949 uint32_t* im32 = (uint32_t*)im;
956 for(i = 0; i < lgr/4; i++)
958 faible = im32[i] & 0x0000ffff; // 4321
959 fort = im32[i] >> 16;
960 fort = ( fort >> 8 ) | ( fort << 8 );
961 faible = ( faible >> 8 ) | ( faible << 8);
963 im32[i] = ( s32 << 16 ) | fort;
967 for(i = 0; i < lgr/4; i++)
969 faible = im32[i] & 0x0000ffff; // 2143
970 fort = im32[i] >> 16;
971 fort = ( fort >> 8 ) | ( fort << 8 );
972 faible = ( faible >> 8) | ( faible << 8);
974 im32[i] = ( s32 << 16 ) | faible;
978 for(i = 0; i < lgr/4; i++)
980 faible = im32[i] & 0x0000ffff; // 3412
981 fort = im32[i] >> 16;
983 im32[i] = ( s32 << 16 ) | fort;
987 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
995 * \brief Read pixel data from disk (optionaly decompressing) into the
996 * caller specified memory location.
997 * @param destination where the pixel data should be stored.
1000 bool gdcmFile::ReadPixelData(void *destination)
1002 FILE *fp = Header->OpenFile();
1008 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1010 Header->CloseFile();
1014 // ---------------------- Compacted File (12 Bits Per Pixel)
1015 // unpack 12 Bits pixels into 16 Bits pixels
1016 // 2 pixels 12bit = [0xABCDEF]
1017 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1019 if ( Header->GetBitsAllocated() == 12 )
1021 int nbPixels = Header->GetXSize() * Header->GetYSize();
1024 uint16_t* pdestination = (uint16_t*)destination;
1025 for(int p = 0; p < nbPixels; p += 2 )
1031 //Two steps is necessary to please VC++
1032 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1034 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1037 // Troubles expected on Big-Endian processors ?
1040 Header->CloseFile();
1044 // ---------------------- Uncompressed File
1045 if ( !Header->IsDicomV3() ||
1046 Header->IsImplicitVRLittleEndianTransferSyntax() ||
1047 Header->IsExplicitVRLittleEndianTransferSyntax() ||
1048 Header->IsExplicitVRBigEndianTransferSyntax() ||
1049 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1051 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1052 Header->CloseFile();
1053 if ( ItemRead != 1 )
1063 // ---------------------- Run Length Encoding
1064 if ( Header->IsRLELossLessTransferSyntax() )
1066 bool res = gdcm_read_RLE_file (fp,destination);
1067 Header->CloseFile();
1071 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1073 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1074 if ( str_nb == GDCM_UNFOUND )
1080 nb = atoi( str_nb.c_str() );
1083 nb = 16; // ?? 12 should be ACR-NEMA only
1088 int taille = Header->GetXSize() * Header->GetYSize()
1089 * Header->GetSamplesPerPixel();
1090 long fragmentBegining; // for ftell, fseek
1092 bool jpg2000 = Header->IsJPEG2000();
1093 bool jpgLossless = Header->IsJPEGLossless();
1096 uint16_t ItemTagGr, ItemTagEl;
1099 // Position on begining of Jpeg Pixels
1101 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1102 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1103 if(Header->GetSwapCode())
1105 ItemTagGr = Header->SwapShort(ItemTagGr);
1106 ItemTagEl = Header->SwapShort(ItemTagEl);
1110 if( Header->GetSwapCode() )
1112 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1117 // What is it used for ?!?
1118 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1119 fread(BasicOffsetTableItemValue,ln,1,fp);
1120 //delete[] BasicOffsetTableItemValue;
1123 // first Fragment initialisation
1124 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1125 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1126 if( Header->GetSwapCode() )
1128 ItemTagGr = Header->SwapShort( ItemTagGr );
1129 ItemTagEl = Header->SwapShort( ItemTagEl );
1132 // parsing fragments until Sequence Delim. Tag found
1133 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1135 // --- for each Fragment
1137 if( Header->GetSwapCode() )
1139 ln = Header->SwapLong(ln); // Fragment Item length
1141 fragmentBegining = ftell( fp );
1145 // JPEG 2000 : call to ???
1146 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1147 // ------------------------------------- endif (JPEG2000)
1149 else if (jpgLossless)
1151 // JPEG LossLess : call to xmedcom Lossless JPEG
1152 // Reading Fragment pixels
1153 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1154 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1155 res = 1; // in order not to break the loop
1157 } // ------------------------------------- endif (JPEGLossless)
1160 // JPEG Lossy : call to IJG 6b
1161 if ( Header->GetBitsStored() == 8)
1163 // Reading Fragment pixels
1164 res = gdcm_read_JPEG_file (fp,destination);
1168 // Reading Fragment pixels
1169 res = gdcm_read_JPEG_file12 (fp,destination);
1171 // ------------------------------------- endif (JPEGLossy)
1179 // location in user's memory
1180 // for next fragment (if any)
1181 destination = (uint8_t*)destination + taille * nBytes;
1183 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1184 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1186 ItemTagGr = ItemTagEl = 0;
1187 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1188 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1189 if( Header->GetSwapCode() )
1191 ItemTagGr = Header->SwapShort( ItemTagGr );
1192 ItemTagEl = Header->SwapShort( ItemTagEl );
1195 // endWhile parsing fragments until Sequence Delim. Tag found
1197 Header->CloseFile();
1200 //-----------------------------------------------------------------------------