1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/07/16 15:18:05 $
7 Version: $Revision: 1.116 $
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 writing a new DICOMV3 part10 compliant
30 * file (see SetFileName, SetDcmTag and Write)
31 * Opens (in read only and when possible) an existing file and checks
32 * for DICOM compliance. Returns NULL on failure.
33 * \note the in-memory representation of all available tags found in
34 * the DICOM header is post-poned to first header information access.
35 * This avoid a double parsing of public part of the header when
36 * one sets an a posteriori shadow dictionary (efficiency can be
37 * seen as a side effect).
38 * @param header file to be opened for reading datas
41 gdcmFile::gdcmFile(gdcmHeader *header)
45 PixelRead = -1; // no ImageData read yet.
47 if (Header->IsReadable())
49 SetPixelDataSizeFromHeader();
55 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
56 * file (see SetFileName, SetDcmTag and Write)
57 * Opens (in read only and when possible) an existing file and checks
58 * for DICOM compliance. Returns NULL on failure.
59 * \note the in-memory representation of all available tags found in
60 * the DICOM header is post-poned to first header information access.
61 * This avoid a double parsing of public part of the header when
62 * one sets an a posteriori shadow dictionary (efficiency can be
63 * seen as a side effect).
64 * @param filename file to be opened for parsing
65 * @param exception_on_error whether we throw an exception or not
66 * @param enable_sequences = true to allow the header
67 * to be parsed *inside* the SeQuences,
68 * when they have an actual length
69 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
70 * @param ignore_shadow to allow skipping the shadow elements,
71 * to save memory space.
72 * \warning The TRUE value for this param has to be used
73 * with a FALSE value for the 'enable_sequence' param.
74 * ('public elements' may be embedded in 'shadow Sequences')
76 gdcmFile::gdcmFile(std::string const & filename,
77 bool exception_on_error,
78 bool enable_sequences,
81 Header = new gdcmHeader( filename,
86 PixelRead = -1; // no ImageData read yet.
88 if ( Header->IsReadable() )
90 SetPixelDataSizeFromHeader();
96 * \brief canonical destructor
97 * \note If the gdcmHeader is created by the gdcmFile, it is destroyed
100 gdcmFile::~gdcmFile()
109 //-----------------------------------------------------------------------------
112 //-----------------------------------------------------------------------------
117 * \brief computes the length (in bytes) to ALLOCATE to receive the
118 * image(s) pixels (multiframes taken into account)
119 * \warning : it is NOT the group 7FE0 length
120 * (no interest for compressed images).
121 * @return length to allocate
123 void gdcmFile::SetPixelDataSizeFromHeader()
125 // see PS 3.3-2003 : C.7.6.3.2.1
135 // YBR_FULL_422 (no LUT, no Palette)
141 // ex : gdcm-US-ALOKA-16.dcm
142 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
143 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
144 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
146 // ex : OT-PAL-8-face.dcm
147 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
148 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
149 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
151 // Number of "Bits Allocated"
153 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
155 if ( str_nb == GDCM_UNFOUND )
161 nb = atoi( str_nb.c_str() );
167 ImageDataSize = ImageDataSizeRaw = Header->GetXSize() * Header->GetYSize()
168 * Header->GetZSize() * (nb/8) * Header->GetSamplesPerPixel();
169 std::string str_PhotometricInterpretation =
170 Header->GetEntryByNumber(0x0028,0x0004);
172 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
173 // pb when undealt Segmented Palette Color
175 if ( Header->HasLUT() )
183 * \brief Returns the size (in bytes) of required memory to hold
184 * the pixel data represented in this file.
185 * @return The size of pixel data in bytes.
187 size_t gdcmFile::GetImageDataSize()
189 return ImageDataSize;
194 * \brief Returns the size (in bytes) of required memory to hold
195 * the pixel data represented in this file, when user DOESN'T want
196 * to get RGB pixels image when it's stored as a PALETTE COLOR image
197 * -the (vtk) user is supposed to know how deal with LUTs-
198 * \warning to be used with GetImagePixelsRaw()
199 * @return The size of pixel data in bytes.
201 size_t gdcmFile::GetImageDataSizeRaw()
203 return ImageDataSizeRaw;
208 * \brief Allocates necessary memory, copies the pixel data
209 * (image[s]/volume[s]) to newly allocated zone.
210 * Transforms YBR pixels into RGB pixels if any
211 * Transforms 3 planes R, G, B into a single RGB Plane
212 * Transforms single Grey plane + 3 Palettes into a RGB Plane
213 * @return Pointer to newly allocated pixel data.
214 * NULL if alloc fails
216 void *gdcmFile::GetImageData()
219 // I need to deallocate PixelData before doing any allocation:
220 PixelData = new uint8_t[ImageDataSize];
223 GetImageDataIntoVector(PixelData, ImageDataSize);
224 GetHeader()->SetEntryVoidAreaByNumber( PixelData,
225 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
227 PixelRead = 0; // no PixelRaw
234 * \brief Copies at most MaxSize bytes of pixel data to caller's
236 * \warning This function was designed to avoid people that want to build
237 * a volume from an image stack to need first to get the image pixels
238 * and then move them to the volume area.
239 * It's absolutely useless for any VTK user since vtk chooses
240 * to invert the lines of an image, that is the last line comes first
241 * (for some axis related reasons?). Hence he will have
242 * to load the image line by line, starting from the end.
243 * VTK users have to call GetImageData
245 * @param destination Address (in caller's memory space) at which the
246 * pixel data should be copied
247 * @param maxSize Maximum number of bytes to be copied. When MaxSize
248 * is not sufficient to hold the pixel data the copy is not
249 * executed (i.e. no partial copy).
250 * @return On success, the number of bytes actually copied. Zero on
251 * failure e.g. MaxSize is lower than necessary.
253 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
255 //size_t l = GetImageDataIntoVectorRaw (destination, maxSize);
256 GetImageDataIntoVectorRaw (destination, maxSize);
257 PixelRead = 0 ; // no PixelRaw
258 if ( !Header->HasLUT() )
260 return ImageDataSize;
263 // from Lut R + Lut G + Lut B
264 uint8_t *newDest = new uint8_t[ImageDataSize];
265 uint8_t *a = (uint8_t *)destination;
266 uint8_t *lutRGBA = Header->GetLUTRGBA();
271 //int l = ImageDataSizeRaw; //loss of precision
272 // move Gray pixels to temp area
273 memmove(newDest, destination, ImageDataSizeRaw);
274 for (size_t i=0; i<ImageDataSizeRaw; ++i)
284 // now, it's an RGB image
285 // Lets's write it in the Header
287 // CreateOrReplaceIfExist ?
289 std::string spp = "3"; // Samples Per Pixel
290 Header->SetEntryByNumber(spp,0x0028,0x0002);
291 std::string rgb = "RGB "; // Photometric Interpretation
292 Header->SetEntryByNumber(rgb,0x0028,0x0004);
293 std::string planConfig = "0"; // Planar Configuration
294 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
297 else //why is there a 'else' when an allocation failed ?
299 // need to make RGB Pixels (?)
300 // from grey Pixels (?!)
301 // and Gray Lut (!?!)
302 // or Segmented xxx Palette Color Lookup Table Data and so on
304 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
305 // No idea how to manage such an image
306 // It seems that *no Dicom Viewer* has any idea :-(
307 // Segmented xxx Palette Color are *more* than 65535 long ?!?
309 std::string rgb = "MONOCHROME1 "; // Photometric Interpretation
310 Header->SetEntryByNumber(rgb,0x0028,0x0004);
313 /// \todo Drop Palette Color out of the Header?
314 return ImageDataSize;
319 * \brief Allocates necessary memory, copies the pixel data
320 * (image[s]/volume[s]) to newly allocated zone.
321 * Transforms YBR pixels into RGB pixels if any
322 * Transforms 3 planes R, G, B into a single RGB Plane
323 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
324 * @return Pointer to newly allocated pixel data.
325 * \ NULL if alloc fails
327 void * gdcmFile::GetImageDataRaw ()
329 size_t imgDataSize = ImageDataSize;
330 if ( Header->HasLUT() )
332 /// \todo Let gdcmHeader user a chance to get the right value
333 imgDataSize = ImageDataSizeRaw;
337 // I need to deallocate PixelData before doing any allocation:
338 PixelData = new uint8_t[imgDataSize];
341 GetImageDataIntoVectorRaw(PixelData, ImageDataSize);
342 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
343 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
345 PixelRead = 1; // PixelRaw
352 * \brief Copies at most MaxSize bytes of pixel data to caller's
354 * \warning This function was designed to avoid people that want to build
355 * a volume from an image stack to need first to get the image pixels
356 * and then move them to the volume area.
357 * It's absolutely useless for any VTK user since vtk chooses
358 * to invert the lines of an image, that is the last line comes first
359 * (for some axis related reasons?). Hence he will have
360 * to load the image line by line, starting from the end.
361 * VTK users hace to call GetImageData
362 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
363 * into a single RGB Pixels Plane
364 * the (VTK) user will manage the palettes
366 * @param destination Address (in caller's memory space) at which the
367 * pixel data should be copied
368 * @param maxSize Maximum number of bytes to be copied. When MaxSize
369 * is not sufficient to hold the pixel data the copy is not
370 * executed (i.e. no partial copy).
371 * @return On success, the number of bytes actually copied. Zero on
372 * failure e.g. MaxSize is lower than necessary.
374 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t maxSize)
376 int nb, nbu, highBit, sign;
377 PixelRead = 1 ; // PixelRaw
379 if ( ImageDataSize > maxSize )
381 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
382 "than caller's expected MaxSize");
386 ReadPixelData( destination );
388 // Number of Bits Allocated for storing a Pixel
389 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
390 if ( str_nb == GDCM_UNFOUND )
396 nb = atoi( str_nb.c_str() );
398 // From reading SetPixelDataSizeFromHeader, it seems 12 should be treated
399 // separately, correct ?
402 // Number of Bits actually used
403 std::string str_nbu = Header->GetEntryByNumber(0x0028,0x0101);
404 if ( str_nbu == GDCM_UNFOUND )
410 nbu = atoi( str_nbu.c_str() );
414 std::string str_highBit = Header->GetEntryByNumber(0x0028,0x0102);
415 if ( str_highBit == GDCM_UNFOUND )
421 highBit = atoi( str_highBit.c_str() );
427 std::string str_sign = Header->GetEntryByNumber(0x0028,0x0103);
428 if ( str_sign == GDCM_UNFOUND )
430 sign = 0; // default is unsigned
434 sign = atoi( str_sign.c_str() );
437 // re arange bytes inside the integer (processor endianity)
440 SwapZone(destination, Header->GetSwapCode(), ImageDataSize, nb);
443 // to avoid pb with some xmedcon breakers images
444 if ( nb == 16 && nbu < nb && sign == 0)
446 int l = (int)(ImageDataSize / (nb/8));
447 uint16_t *deb = (uint16_t *)destination;
448 for(int i = 0; i<l; i++)
458 // re arange bits inside the bytes
461 int l = (int)(ImageDataSize / (nb/8));
464 uint16_t mask = 0xffff;
465 mask = mask >> (nb-nbu);
466 uint16_t *deb = (uint16_t *)destination;
467 for(int i = 0; i<l; i++)
469 *deb = (*deb >> (nbu - highBit - 1)) & mask;
475 uint32_t mask = 0xffffffff;
476 mask = mask >> (nb - nbu);
477 uint32_t *deb = (uint32_t *)destination;
478 for(int i = 0; i<l; i++)
480 *deb = (*deb >> (nbu - highBit - 1)) & mask;
486 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
490 // DO NOT remove this code commented out.
491 // Nobody knows what's expecting you ...
492 // Just to 'see' what was actually read on disk :-(
495 // f2 = fopen("SpuriousFile.RAW","wb");
496 // fwrite(destination,ImageDataSize,1,f2);
499 // Deal with the color
500 // -------------------
502 std::string str_PhotometricInterpretation =
503 Header->GetEntryByNumber(0x0028,0x0004);
505 if ( str_PhotometricInterpretation == "MONOCHROME1 "
506 || str_PhotometricInterpretation == "MONOCHROME2 " )
508 return ImageDataSize;
511 // Planar configuration = 0 : Pixels are already RGB
512 // Planar configuration = 1 : 3 planes : R, G, B
513 // Planar configuration = 2 : 1 gray Plane + 3 LUT
515 // Well ... supposed to be !
516 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
517 // PhotometricInterpretation=PALETTE COLOR
518 // and heuristic has to be found :-(
520 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
522 // Whatever Planar Configuration is,
523 // "PALETTE COLOR " implies that we deal with the palette.
524 if ( str_PhotometricInterpretation == "PALETTE COLOR ")
532 // Pixels are already RGB
535 if (str_PhotometricInterpretation == "YBR_FULL")
537 // Warning : YBR_FULL_422 acts as RGB
538 // : we need to make RGB Pixels from Planes Y,cB,cR
540 // to see the tricks about YBR_FULL, YBR_FULL_422,
541 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
542 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
543 // and be *very* affraid
545 int l = Header->GetXSize() * Header->GetYSize();
546 int nbFrames = Header->GetZSize();
548 uint8_t* newDest = new uint8_t[ImageDataSize];
549 uint8_t* x = newDest;
550 uint8_t* a = (uint8_t*)destination;
555 /// \todo : Replace by the 'well known' integer computation
557 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
558 /// for code optimisation
560 for (int i = 0; i < nbFrames; i++)
562 for (int j = 0; j < l; j++)
564 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
565 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
566 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
568 if (R < 0.0) R = 0.0;
569 if (G < 0.0) G = 0.0;
570 if (B < 0.0) B = 0.0;
571 if (R > 255.0) R = 255.0;
572 if (G > 255.0) G = 255.0;
573 if (B > 255.0) B = 255.0;
581 memmove(destination, newDest, ImageDataSize);
586 // need to make RGB Pixels from R,G,B Planes
587 // (all the Frames at a time)
589 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
591 uint8_t *newDest = new uint8_t[ImageDataSize];
592 uint8_t *x = newDest;
593 uint8_t *a = (uint8_t *)destination;
597 for (int j = 0; j < l; j++)
603 memmove(destination, newDest, ImageDataSize);
608 // Palettes were found
609 // Let the user deal with them !
610 return ImageDataSize;
612 // now, it's an RGB image
613 // Lets's write it in the Header
615 // CreateOrReplaceIfExist ?
617 std::string spp = "3"; // Samples Per Pixel
618 std::string rgb = "RGB "; // Photometric Interpretation
619 std::string planConfig = "0"; // Planar Configuration
621 Header->SetEntryByNumber(spp,0x0028,0x0002);
622 Header->SetEntryByNumber(rgb,0x0028,0x0004);
623 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
625 /// \todo Drop Palette Color out of the Header?
626 return ImageDataSize;
631 * \brief performs a shalow copy (not a deep copy) of the user given
633 * 'image' Pixels are presented as C-like 2D arrays : line per line.
634 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
635 * \warning user is kindly requested NOT TO 'free' the Pixel area
636 * @param inData user supplied pixel area
637 * @param expectedSize total image size, in Bytes
641 bool gdcmFile::SetImageData(void *inData, size_t expectedSize)
643 Header->SetImageDataSize( expectedSize );
645 ImageDataSize = expectedSize;
653 * \brief Writes on disk A SINGLE Dicom file
654 * NO test is performed on processor "Endiannity".
655 * It's up to the user to call his Reader properly
656 * @param fileName name of the file to be created
657 * (any already existing file is over written)
658 * @return false if write fails
661 bool gdcmFile::WriteRawData(std::string const & fileName)
663 FILE *fp1 = fopen(fileName.c_str(), "wb");
666 printf("Fail to open (write) file [%s] \n", fileName.c_str());
669 fwrite (PixelData, ImageDataSize, 1, fp1);
677 * \brief Writes on disk A SINGLE Dicom file,
678 * using the Implicit Value Representation convention
679 * NO test is performed on processor "Endiannity".
680 * @param fileName name of the file to be created
681 * (any already existing file is overwritten)
682 * @return false if write fails
685 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
687 return WriteBase(fileName, gdcmImplicitVR);
692 * \brief Writes on disk A SINGLE Dicom file,
693 * using the Explicit Value Representation convention
694 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
695 * (any already existing file is overwritten)
696 * @return false if write fails
699 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
701 return WriteBase(fileName, gdcmExplicitVR);
706 * \brief Writes on disk A SINGLE Dicom file,
707 * using the ACR-NEMA convention
708 * NO test is performed on processor "Endiannity".
709 * (a l'attention des logiciels cliniques
710 * qui ne prennent en entrée QUE des images ACR ...
711 * \warning if a DICOM_V3 header is supplied,
712 * groups < 0x0008 and shadow groups are ignored
713 * \warning NO TEST is performed on processor "Endiannity".
714 * @param fileName name of the file to be created
715 * (any already existing file is overwritten)
716 * @return false if write fails
719 bool gdcmFile::WriteAcr (std::string const & fileName)
721 return WriteBase(fileName, gdcmACR);
724 //-----------------------------------------------------------------------------
728 * \brief NOT a end user inteded function
729 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
730 * @param fileName name of the file to be created
731 * (any already existing file is overwritten)
732 * @param type file type (ExplicitVR, ImplicitVR, ...)
733 * @return false if write fails
735 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
737 if ( PixelRead == -1 && type != gdcmExplicitVR)
742 FILE *fp1 = fopen(fileName.c_str(), "wb");
745 printf("Failed to open (write) File [%s] \n", fileName.c_str());
749 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
751 // writing Dicom File Preamble
752 uint8_t* filePreamble = new uint8_t[128];
753 memset(filePreamble, 0, 128);
754 fwrite(filePreamble, 128, 1, fp1);
755 fwrite("DICM", 4, 1, fp1);
757 delete[] filePreamble;
760 // --------------------------------------------------------------
761 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
763 // if recognition code tells us we dealt with a LibIDO image
764 // we reproduce on disk the switch between lineNumber and columnNumber
765 // just before writting ...
767 /// \todo the best trick would be *change* the recognition code
768 /// but pb expected if user deals with, e.g. COMPLEX images
770 std::string rows, columns;
771 if ( Header->GetFileType() == gdcmACR_LIBIDO)
773 rows = Header->GetEntryByNumber(0x0028, 0x0010);
774 columns = Header->GetEntryByNumber(0x0028, 0x0011);
776 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
777 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
779 // ----------------- End of Special Patch ----------------
781 uint16_t grPixel = Header->GetGrPixel();
782 uint16_t numPixel = Header->GetNumPixel();;
784 gdcmDocEntry* PixelElement =
785 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
787 if ( PixelRead == 1 )
789 // we read pixel 'as is' (no tranformation LUT -> RGB)
790 PixelElement->SetLength( ImageDataSizeRaw );
792 else if ( PixelRead == 0 )
794 // we tranformed GrayLevel pixels + LUT into RGB Pixel
795 PixelElement->SetLength( ImageDataSize );
798 Header->Write(fp1, type);
800 // --------------------------------------------------------------
801 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
803 // ...and we restore the Header to be Dicom Compliant again
804 // just after writting
806 if ( Header->GetFileType() == gdcmACR_LIBIDO )
808 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
809 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
811 // ----------------- End of Special Patch ----------------
813 // fwrite(PixelData, ImageDataSize, 1, fp1); // should be useless, now
819 //-----------------------------------------------------------------------------
823 * \brief Swap the bytes, according to swap code.
824 * \warning not end user intended
825 * @param im area to deal with
826 * @param swap swap code
827 * @param lgr Area Length
828 * @param nb Pixels Bit number
830 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb)
836 uint16_t* im16 = (uint16_t*)im;
847 for(i=0; i < lgr/2; i++)
849 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
853 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
860 uint16_t fort, faible;
861 uint32_t* im32 = (uint32_t*)im;
868 for(i = 0; i < lgr/4; i++)
870 faible = im32[i] & 0x0000ffff; // 4321
871 fort = im32[i] >> 16;
872 fort = ( fort >> 8 ) | ( fort << 8 );
873 faible = ( faible >> 8 ) | ( faible << 8);
875 im32[i] = ( s32 << 16 ) | fort;
879 for(i = 0; i < lgr/4; i++)
881 faible = im32[i] & 0x0000ffff; // 2143
882 fort = im32[i] >> 16;
883 fort = ( fort >> 8 ) | ( fort << 8 );
884 faible = ( faible >> 8) | ( faible << 8);
886 im32[i] = ( s32 << 16 ) | faible;
890 for(i = 0; i < lgr/4; i++)
892 faible = im32[i] & 0x0000ffff; // 3412
893 fort = im32[i] >> 16;
895 im32[i] = ( s32 << 16 ) | fort;
899 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
907 * \brief Read pixel data from disk (optionaly decompressing) into the
908 * caller specified memory location.
909 * @param destination where the pixel data should be stored.
912 bool gdcmFile::ReadPixelData(void *destination)
914 FILE *fp = Header->OpenFile();
920 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
926 // ---------------------- Compacted File (12 Bits Per Pixel)
927 // unpack 12 Bits pixels into 16 Bits pixels
928 // 2 pixels 12bit = [0xABCDEF]
929 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
931 if ( Header->GetBitsAllocated() == 12 )
933 int nbPixels = Header->GetXSize() * Header->GetYSize();
936 uint16_t* pdestination = (uint16_t*)destination;
937 for(int p = 0; p < nbPixels; p += 2 )
943 //Two steps is necessary to please VC++
944 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
946 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
949 // Troubles expected on Big-Endian processors ?
956 // ---------------------- Uncompressed File
957 if ( !Header->IsDicomV3() ||
958 Header->IsImplicitVRLittleEndianTransferSyntax() ||
959 Header->IsExplicitVRLittleEndianTransferSyntax() ||
960 Header->IsExplicitVRBigEndianTransferSyntax() ||
961 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
963 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
975 // ---------------------- Run Length Encoding
976 if ( Header->IsRLELossLessTransferSyntax() )
978 bool res = gdcm_read_RLE_file (fp,destination);
983 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
985 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
986 if ( str_nb == GDCM_UNFOUND )
992 nb = atoi( str_nb.c_str() );
995 nb = 16; // ?? 12 should be ACR-NEMA only
1000 int taille = Header->GetXSize() * Header->GetYSize()
1001 * Header->GetSamplesPerPixel();
1002 long fragmentBegining; // for ftell, fseek
1004 bool jpg2000 = Header->IsJPEG2000();
1005 bool jpgLossless = Header->IsJPEGLossless();
1008 uint16_t ItemTagGr, ItemTagEl;
1011 // Position on begining of Jpeg Pixels
1013 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1014 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1015 if(Header->GetSwapCode())
1017 ItemTagGr = Header->SwapShort(ItemTagGr);
1018 ItemTagEl = Header->SwapShort(ItemTagEl);
1022 if( Header->GetSwapCode() )
1024 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1029 // What is it used for ?!?
1030 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1031 fread(BasicOffsetTableItemValue,ln,1,fp);
1032 //delete[] BasicOffsetTableItemValue;
1035 // first Fragment initialisation
1036 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1037 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1038 if( Header->GetSwapCode() )
1040 ItemTagGr = Header->SwapShort( ItemTagGr );
1041 ItemTagEl = Header->SwapShort( ItemTagEl );
1044 // parsing fragments until Sequence Delim. Tag found
1045 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1047 // --- for each Fragment
1049 if( Header->GetSwapCode() )
1051 ln = Header->SwapLong(ln); // Fragment Item length
1053 fragmentBegining = ftell( fp );
1057 // JPEG 2000 : call to ???
1058 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1059 // ------------------------------------- endif (JPEG2000)
1061 else if (jpgLossless)
1063 // JPEG LossLess : call to xmedcom Lossless JPEG
1064 // Reading Fragment pixels
1065 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1066 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1067 res = 1; // in order not to break the loop
1069 } // ------------------------------------- endif (JPEGLossless)
1072 // JPEG Lossy : call to IJG 6b
1073 if ( Header->GetBitsStored() == 8)
1075 // Reading Fragment pixels
1076 res = (bool)gdcm_read_JPEG_file (fp,destination);
1080 // Reading Fragment pixels
1081 res = (bool)gdcm_read_JPEG_file12 (fp,destination);
1083 // ------------------------------------- endif (JPEGLossy)
1091 // location in user's memory
1092 // for next fragment (if any)
1093 destination = (uint8_t*)destination + taille * nBytes;
1095 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1096 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1098 ItemTagGr = ItemTagEl = 0;
1099 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1100 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1101 if( Header->GetSwapCode() )
1103 ItemTagGr = Header->SwapShort( ItemTagGr );
1104 ItemTagEl = Header->SwapShort( ItemTagEl );
1107 // endWhile parsing fragments until Sequence Delim. Tag found
1109 Header->CloseFile();
1112 //-----------------------------------------------------------------------------