1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/09/09 17:49:25 $
7 Version: $Revision: 1.123 $
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
43 gdcmFile::gdcmFile(gdcmHeader *header)
48 PixelRead = -1; // no ImageData read yet.
49 LastAllocatedPixelDataLength = 0;
54 InitialPlanConfig = "";
55 InitialBitsAllocated = "";
57 if (Header->IsReadable())
59 SetPixelDataSizeFromHeader();
65 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
66 * file (gdcmHeader only deals with the ... header)
67 * Opens (in read only and when possible) an existing file and checks
68 * for DICOM compliance. Returns NULL on failure.
69 * It will be up to the user to load the pixels into memory
70 * (see GetImageData, GetImageDataRaw)
71 * \note the in-memory representation of all available tags found in
72 * the DICOM header is post-poned to first header information access.
73 * This avoid a double parsing of public part of the header when
74 * one sets an a posteriori shadow dictionary (efficiency can be
75 * seen as a side effect).
76 * @param filename file to be opened for parsing
78 gdcmFile::gdcmFile(std::string const & filename )
80 Header = new gdcmHeader( filename );
83 PixelRead = -1; // no ImageData read yet.
84 LastAllocatedPixelDataLength = 0;
89 InitialPlanConfig = "";
90 InitialBitsAllocated = "";
92 if ( Header->IsReadable() )
94 SetPixelDataSizeFromHeader();
100 * \brief canonical destructor
101 * \note If the gdcmHeader was created by the gdcmFile constructor,
102 * it is destroyed by the gdcmFile
104 gdcmFile::~gdcmFile()
113 //-----------------------------------------------------------------------------
116 //-----------------------------------------------------------------------------
121 * \brief computes the length (in bytes) we must ALLOCATE to receive the
122 * image(s) pixels (multiframes taken into account)
123 * \warning : it is NOT the group 7FE0 length
124 * (no interest for compressed images).
126 void gdcmFile::SetPixelDataSizeFromHeader()
128 // see PS 3.3-2003 : C.7.6.3.2.1
138 // YBR_FULL_422 (no LUT, no Palette)
144 // ex : gdcm-US-ALOKA-16.dcm
145 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
146 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
147 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
149 // ex : OT-PAL-8-face.dcm
150 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
151 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
152 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
154 // Number of "Bits Allocated"
156 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
158 if ( str_nb == GDCM_UNFOUND )
164 nb = atoi( str_nb.c_str() );
170 ImageDataSize = ImageDataSizeRaw = Header->GetXSize() * Header->GetYSize()
171 * Header->GetZSize() * (nb/8) * Header->GetSamplesPerPixel();
172 std::string str_PhotometricInterpretation =
173 Header->GetEntryByNumber(0x0028,0x0004);
175 // if ( str_PhotometricInterpretation == "PALETTE COLOR " ),
176 // pb when undealt Segmented Palette Color
178 if ( Header->HasLUT() )
187 * \brief Returns the size (in bytes) of required memory to hold
188 * the pixel data represented in this file, if user DOESN'T want
189 * to get RGB pixels image when it's stored as a PALETTE COLOR image
190 * -the (vtk) user is supposed to know how to deal with LUTs-
191 * \warning to be used with GetImagePixelsRaw()
192 * @return The size of pixel data in bytes.
194 size_t gdcmFile::GetImageDataSizeRaw()
196 return ImageDataSizeRaw;
201 * \brief - Allocates necessary memory,
202 * - Reads the pixels from disk (uncompress if necessary),
203 * - Transforms YBR pixels, if any, into RGB pixels
204 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
205 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
206 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
207 * @return Pointer to newly allocated pixel data.
208 * NULL if alloc fails
210 void *gdcmFile::GetImageData()
213 // I need to deallocate PixelData before doing any allocation:
216 if ( LastAllocatedPixelDataLength != ImageDataSize)
218 PixelData = new uint8_t[ImageDataSize];
221 LastAllocatedPixelDataLength = ImageDataSize;
223 GetImageDataIntoVector(PixelData, ImageDataSize);
224 // Will be 7fe0, 0010 in standard case
225 GetHeader()->SetEntryVoidAreaByNumber( PixelData,
226 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
227 // Now, the value is loaded.
228 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
229 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
231 PixelRead = 0; // no PixelRaw
239 * Read the pixels from disk (uncompress if necessary),
240 * Transforms YBR pixels, if any, into RGB pixels
241 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
242 * Transforms single Grey plane + 3 Palettes into a RGB Plane
243 * Copies at most MaxSize bytes of pixel data to caller allocated
245 * \warning This function allows people that want to build a volume
246 * from an image stack *not to* have, first to get the image pixels,
247 * and then move them to the volume area.
248 * It's absolutely useless for any VTK user since vtk chooses
249 * to invert the lines of an image, that is the last line comes first
250 * (for some axis related reasons?). Hence he will have
251 * to load the image line by line, starting from the end.
252 * VTK users have to call GetImageData
254 * @param destination Address (in caller's memory space) at which the
255 * pixel data should be copied
256 * @param maxSize Maximum number of bytes to be copied. When MaxSize
257 * is not sufficient to hold the pixel data the copy is not
258 * executed (i.e. no partial copy).
259 * @return On success, the number of bytes actually copied. Zero on
260 * failure e.g. MaxSize is lower than necessary.
262 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
264 GetImageDataIntoVectorRaw (destination, maxSize);
265 PixelRead = 0 ; // =0 : no ImageDataRaw
266 if ( !Header->HasLUT() )
268 return ImageDataSize;
271 // from Lut R + Lut G + Lut B
272 uint8_t *newDest = new uint8_t[ImageDataSize];
273 uint8_t *a = (uint8_t *)destination;
274 uint8_t *lutRGBA = Header->GetLUTRGBA();
279 // move Gray pixels to temp area
280 memmove(newDest, destination, ImageDataSizeRaw);
281 for (size_t i=0; i<ImageDataSizeRaw; ++i)
291 // now, it's an RGB image
292 // Lets's write it in the Header
294 // FIXME : Better use CreateOrReplaceIfExist ?
296 std::string spp = "3"; // Samples Per Pixel
297 Header->SetEntryByNumber(spp,0x0028,0x0002);
298 std::string rgb = "RGB "; // Photometric Interpretation
299 Header->SetEntryByNumber(rgb,0x0028,0x0004);
300 std::string planConfig = "0"; // Planar Configuration
301 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
304 else // GetLUTRGBA() failed
306 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
307 // that are *more* than 65535 long ?!?
308 // No idea how to manage such an image !
309 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
310 // It seems that *no Dicom Viewer* has any idea :-(
312 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
313 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
316 /// \todo Drop Palette Color out of the Header?
317 return ImageDataSize;
322 * \brief Allocates necessary memory,
323 * Transforms YBR pixels (if any) into RGB pixels
324 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
325 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
326 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
327 * @return Pointer to newly allocated pixel data.
328 * \ NULL if alloc fails
330 void * gdcmFile::GetImageDataRaw ()
333 if ( Header->HasLUT() )
334 /// \todo Let gdcmHeader user a chance to get the right value
335 imgDataSize = ImageDataSizeRaw;
337 imgDataSize = ImageDataSize;
340 // I need to deallocate PixelData before doing any allocation:
343 if ( LastAllocatedPixelDataLength != imgDataSize)
345 PixelData = new uint8_t[imgDataSize];
348 LastAllocatedPixelDataLength = imgDataSize;
350 GetImageDataIntoVectorRaw(PixelData, imgDataSize);
351 // will be 7fe0, 0010 in standard cases
352 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
353 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
354 // Now, the value is loaded.
355 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
356 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
358 PixelRead = 1; // PixelRaw
365 * \brief Copies at most MaxSize bytes of pixel data to caller's
367 * \warning This function was designed to avoid people that want to build
368 * a volume from an image stack to need first to get the image pixels
369 * and then move them to the volume area.
370 * It's absolutely useless for any VTK user since vtk chooses
371 * to invert the lines of an image, that is the last line comes first
372 * (for some axis related reasons?). Hence he will have
373 * to load the image line by line, starting from the end.
374 * VTK users hace to call GetImageData
375 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
376 * into a single RGB Pixels Plane
377 * the (VTK) user will manage the palettes
379 * @param destination Address (in caller's memory space) at which the
380 * pixel data should be copied
381 * @param maxSize Maximum number of bytes to be copied. When MaxSize
382 * is not sufficient to hold the pixel data the copy is not
383 * executed (i.e. no partial copy).
384 * @return On success, the number of bytes actually copied. Zero on
385 * failure e.g. MaxSize is lower than necessary.
387 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t maxSize)
389 int nb, nbu, highBit, sign;
391 // we save the initial values of the following
392 // in order to be able to restore the header in a disk-consistent state
393 // (if user asks twice to get the pixels from disk)
395 if ( PixelRead == -1 ) // File was never "read" before
397 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
398 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
399 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
400 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
402 else // File was already "read", the following *may* have been modified
403 // we restore them to be in a disk-consistent state
405 // FIXME : What happened with the LUTs ?
406 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
407 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
408 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
409 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
412 PixelRead = 1 ; // PixelRaw
414 if ( ImageDataSize > maxSize )
416 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
417 "than caller's expected MaxSize");
421 ReadPixelData( destination );
423 // Number of Bits Allocated for storing a Pixel
424 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
425 if ( str_nb == GDCM_UNFOUND )
431 nb = atoi( str_nb.c_str() );
433 // From reading SetPixelDataSizeFromHeader, it seems 12 should be treated
434 // separately, correct ?
437 // Number of Bits actually used
438 std::string str_nbu = Header->GetEntryByNumber(0x0028,0x0101);
439 if ( str_nbu == GDCM_UNFOUND )
445 nbu = atoi( str_nbu.c_str() );
449 std::string str_highBit = Header->GetEntryByNumber(0x0028,0x0102);
450 if ( str_highBit == GDCM_UNFOUND )
456 highBit = atoi( str_highBit.c_str() );
462 std::string str_sign = Header->GetEntryByNumber(0x0028,0x0103);
463 if ( str_sign == GDCM_UNFOUND )
465 sign = 0; // default is unsigned
469 sign = atoi( str_sign.c_str() );
472 // re arange bytes inside the integer (processor endianity)
475 SwapZone(destination, Header->GetSwapCode(), ImageDataSize, nb);
478 // to avoid pb with some xmedcon breakers images
479 if ( nb == 16 && nbu < nb && sign == 0)
481 int l = (int)(ImageDataSize / (nb/8));
482 uint16_t *deb = (uint16_t *)destination;
483 for(int i = 0; i<l; i++)
493 // re arange bits inside the bytes
496 int l = (int)(ImageDataSize / (nb/8));
499 uint16_t mask = 0xffff;
500 mask = mask >> (nb-nbu);
501 uint16_t *deb = (uint16_t *)destination;
502 for(int i = 0; i<l; i++)
504 *deb = (*deb >> (nbu - highBit - 1)) & mask;
510 uint32_t mask = 0xffffffff;
511 mask = mask >> (nb - nbu);
512 uint32_t *deb = (uint32_t *)destination;
513 for(int i = 0; i<l; i++)
515 *deb = (*deb >> (nbu - highBit - 1)) & mask;
521 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
525 // DO NOT remove this code commented out.
526 // Nobody knows what's expecting you ...
527 // Just to 'see' what was actually read on disk :-(
530 // f2 = fopen("SpuriousFile.RAW","wb");
531 // fwrite(destination,ImageDataSize,1,f2);
534 // Deal with the color
535 // -------------------
537 std::string str_PhotometricInterpretation =
538 Header->GetEntryByNumber(0x0028,0x0004);
540 if ( str_PhotometricInterpretation == "MONOCHROME1 "
541 || str_PhotometricInterpretation == "MONOCHROME2 " )
543 return ImageDataSize;
546 // Planar configuration = 0 : Pixels are already RGB
547 // Planar configuration = 1 : 3 planes : R, G, B
548 // Planar configuration = 2 : 1 gray Plane + 3 LUT
550 // Well ... supposed to be !
551 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
552 // PhotometricInterpretation=PALETTE COLOR
553 // and heuristic has to be found :-(
555 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
557 // Whatever Planar Configuration is,
558 // "PALETTE COLOR " implies that we deal with the palette.
559 if ( str_PhotometricInterpretation == "PALETTE COLOR ")
567 // Pixels are already RGB
570 if (str_PhotometricInterpretation == "YBR_FULL")
572 // Warning : YBR_FULL_422 acts as RGB
573 // : we need to make RGB Pixels from Planes Y,cB,cR
575 // to see the tricks about YBR_FULL, YBR_FULL_422,
576 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
577 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
578 // and be *very* affraid
580 int l = Header->GetXSize() * Header->GetYSize();
581 int nbFrames = Header->GetZSize();
583 uint8_t* newDest = new uint8_t[ImageDataSize];
584 uint8_t* x = newDest;
585 uint8_t* a = (uint8_t*)destination;
590 /// \todo : Replace by the 'well known' integer computation
592 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
593 /// for code optimisation
595 for (int i = 0; i < nbFrames; i++)
597 for (int j = 0; j < l; j++)
599 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
600 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
601 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
603 if (R < 0.0) R = 0.0;
604 if (G < 0.0) G = 0.0;
605 if (B < 0.0) B = 0.0;
606 if (R > 255.0) R = 255.0;
607 if (G > 255.0) G = 255.0;
608 if (B > 255.0) B = 255.0;
616 memmove(destination, newDest, ImageDataSize);
621 // need to make RGB Pixels from R,G,B Planes
622 // (all the Frames at a time)
624 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
626 uint8_t *newDest = new uint8_t[ImageDataSize];
627 uint8_t *x = newDest;
628 uint8_t *a = (uint8_t *)destination;
632 for (int j = 0; j < l; j++)
638 memmove(destination, newDest, ImageDataSize);
643 // Palettes were found
644 // Let the user deal with them !
645 return ImageDataSize;
647 // now, it's an RGB image
648 // Lets's write it in the Header
650 // CreateOrReplaceIfExist ?
652 std::string spp = "3"; // Samples Per Pixel
653 std::string photInt = "RGB "; // Photometric Interpretation
654 std::string planConfig = "0"; // Planar Configuration
658 Header->SetEntryByNumber(spp,0x0028,0x0002);
659 Header->SetEntryByNumber(photInt,0x0028,0x0004);
660 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
662 /// \todo Drop Palette Color out of the Header?
663 return ImageDataSize;
668 * \brief performs a shalow copy (not a deep copy) of the user given
670 * 'image' Pixels are presented as C-like 2D arrays : line per line.
671 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
672 * \warning user is kindly requested NOT TO 'free' the Pixel area
673 * @param inData user supplied pixel area
674 * @param expectedSize total image size, in Bytes
678 bool gdcmFile::SetImageData(void *inData, size_t expectedSize)
680 Header->SetImageDataSize( expectedSize );
681 // FIXME : if already allocated, memory leak !
683 ImageDataSize = ImageDataSizeRaw = expectedSize;
685 // FIXME : 7fe0, 0010 IS NOT set ...
691 * \brief Writes on disk A SINGLE Dicom file
692 * NO test is performed on processor "Endiannity".
693 * It's up to the user to call his Reader properly
694 * @param fileName name of the file to be created
695 * (any already existing file is over written)
696 * @return false if write fails
699 bool gdcmFile::WriteRawData(std::string const & fileName)
701 FILE *fp1 = fopen(fileName.c_str(), "wb");
704 printf("Fail to open (write) file [%s] \n", fileName.c_str());
707 fwrite (PixelData, ImageDataSize, 1, fp1);
715 * \brief Writes on disk A SINGLE Dicom file,
716 * using the Implicit Value Representation convention
717 * NO test is performed on processor "Endiannity".
718 * @param fileName name of the file to be created
719 * (any already existing file is overwritten)
720 * @return false if write fails
723 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
725 return WriteBase(fileName, gdcmImplicitVR);
730 * \brief Writes on disk A SINGLE Dicom file,
731 * using the Explicit Value Representation convention
732 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
733 * (any already existing file is overwritten)
734 * @return false if write fails
737 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
739 return WriteBase(fileName, gdcmExplicitVR);
744 * \brief Writes on disk A SINGLE Dicom file,
745 * using the ACR-NEMA convention
746 * NO test is performed on processor "Endiannity".
747 * (a l'attention des logiciels cliniques
748 * qui ne prennent en entrée QUE des images ACR ...
749 * \warning if a DICOM_V3 header is supplied,
750 * groups < 0x0008 and shadow groups are ignored
751 * \warning NO TEST is performed on processor "Endiannity".
752 * @param fileName name of the file to be created
753 * (any already existing file is overwritten)
754 * @return false if write fails
757 bool gdcmFile::WriteAcr (std::string const & fileName)
759 return WriteBase(fileName, gdcmACR);
762 //-----------------------------------------------------------------------------
766 * \brief NOT a end user inteded function
767 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
768 * @param fileName name of the file to be created
769 * (any already existing file is overwritten)
770 * @param type file type (ExplicitVR, ImplicitVR, ...)
771 * @return false if write fails
773 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
775 if ( PixelRead == -1 && type != gdcmExplicitVR)
780 FILE *fp1 = fopen(fileName.c_str(), "wb");
783 printf("Failed to open (write) File [%s] \n", fileName.c_str());
787 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
789 // writing Dicom File Preamble
790 uint8_t* filePreamble = new uint8_t[128];
791 memset(filePreamble, 0, 128);
792 fwrite(filePreamble, 128, 1, fp1);
793 fwrite("DICM", 4, 1, fp1);
795 delete[] filePreamble;
798 // --------------------------------------------------------------
799 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
801 // if recognition code tells us we dealt with a LibIDO image
802 // we reproduce on disk the switch between lineNumber and columnNumber
803 // just before writting ...
805 /// \todo the best trick would be *change* the recognition code
806 /// but pb expected if user deals with, e.g. COMPLEX images
808 std::string rows, columns;
809 if ( Header->GetFileType() == gdcmACR_LIBIDO)
811 rows = Header->GetEntryByNumber(0x0028, 0x0010);
812 columns = Header->GetEntryByNumber(0x0028, 0x0011);
814 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
815 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
817 // ----------------- End of Special Patch ----------------
819 uint16_t grPixel = Header->GetGrPixel();
820 uint16_t numPixel = Header->GetNumPixel();;
822 gdcmDocEntry* PixelElement =
823 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
825 if ( PixelRead == 1 )
827 // we read pixel 'as is' (no tranformation LUT -> RGB)
828 PixelElement->SetLength( ImageDataSizeRaw );
830 else if ( PixelRead == 0 )
832 // we tranformed GrayLevel pixels + LUT into RGB Pixel
833 PixelElement->SetLength( ImageDataSize );
836 Header->Write(fp1, type);
838 // --------------------------------------------------------------
839 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
841 // ...and we restore the Header to be Dicom Compliant again
842 // just after writting
844 if ( Header->GetFileType() == gdcmACR_LIBIDO )
846 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
847 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
849 // ----------------- End of Special Patch ----------------
851 // fwrite(PixelData, ImageDataSize, 1, fp1); // should be useless, now
857 //-----------------------------------------------------------------------------
861 * \brief Swap the bytes, according to swap code.
862 * \warning not end user intended
863 * @param im area to deal with
864 * @param swap swap code
865 * @param lgr Area Length
866 * @param nb Pixels Bit number
868 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb)
874 uint16_t* im16 = (uint16_t*)im;
885 for(i=0; i < lgr/2; i++)
887 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
891 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
898 uint16_t fort, faible;
899 uint32_t* im32 = (uint32_t*)im;
906 for(i = 0; i < lgr/4; i++)
908 faible = im32[i] & 0x0000ffff; // 4321
909 fort = im32[i] >> 16;
910 fort = ( fort >> 8 ) | ( fort << 8 );
911 faible = ( faible >> 8 ) | ( faible << 8);
913 im32[i] = ( s32 << 16 ) | fort;
917 for(i = 0; i < lgr/4; i++)
919 faible = im32[i] & 0x0000ffff; // 2143
920 fort = im32[i] >> 16;
921 fort = ( fort >> 8 ) | ( fort << 8 );
922 faible = ( faible >> 8) | ( faible << 8);
924 im32[i] = ( s32 << 16 ) | faible;
928 for(i = 0; i < lgr/4; i++)
930 faible = im32[i] & 0x0000ffff; // 3412
931 fort = im32[i] >> 16;
933 im32[i] = ( s32 << 16 ) | fort;
937 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
945 * \brief Read pixel data from disk (optionaly decompressing) into the
946 * caller specified memory location.
947 * @param destination where the pixel data should be stored.
950 bool gdcmFile::ReadPixelData(void *destination)
952 FILE *fp = Header->OpenFile();
958 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
964 // ---------------------- Compacted File (12 Bits Per Pixel)
965 // unpack 12 Bits pixels into 16 Bits pixels
966 // 2 pixels 12bit = [0xABCDEF]
967 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
969 if ( Header->GetBitsAllocated() == 12 )
971 int nbPixels = Header->GetXSize() * Header->GetYSize();
974 uint16_t* pdestination = (uint16_t*)destination;
975 for(int p = 0; p < nbPixels; p += 2 )
981 //Two steps is necessary to please VC++
982 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
984 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
987 // Troubles expected on Big-Endian processors ?
994 // ---------------------- Uncompressed File
995 if ( !Header->IsDicomV3() ||
996 Header->IsImplicitVRLittleEndianTransferSyntax() ||
997 Header->IsExplicitVRLittleEndianTransferSyntax() ||
998 Header->IsExplicitVRBigEndianTransferSyntax() ||
999 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1001 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1002 Header->CloseFile();
1003 if ( ItemRead != 1 )
1013 // ---------------------- Run Length Encoding
1014 if ( Header->IsRLELossLessTransferSyntax() )
1016 bool res = gdcm_read_RLE_file (fp,destination);
1017 Header->CloseFile();
1021 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1023 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1024 if ( str_nb == GDCM_UNFOUND )
1030 nb = atoi( str_nb.c_str() );
1033 nb = 16; // ?? 12 should be ACR-NEMA only
1038 int taille = Header->GetXSize() * Header->GetYSize()
1039 * Header->GetSamplesPerPixel();
1040 long fragmentBegining; // for ftell, fseek
1042 bool jpg2000 = Header->IsJPEG2000();
1043 bool jpgLossless = Header->IsJPEGLossless();
1046 uint16_t ItemTagGr, ItemTagEl;
1049 // Position on begining of Jpeg Pixels
1051 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1052 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1053 if(Header->GetSwapCode())
1055 ItemTagGr = Header->SwapShort(ItemTagGr);
1056 ItemTagEl = Header->SwapShort(ItemTagEl);
1060 if( Header->GetSwapCode() )
1062 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1067 // What is it used for ?!?
1068 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1069 fread(BasicOffsetTableItemValue,ln,1,fp);
1070 //delete[] BasicOffsetTableItemValue;
1073 // first Fragment initialisation
1074 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1075 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1076 if( Header->GetSwapCode() )
1078 ItemTagGr = Header->SwapShort( ItemTagGr );
1079 ItemTagEl = Header->SwapShort( ItemTagEl );
1082 // parsing fragments until Sequence Delim. Tag found
1083 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1085 // --- for each Fragment
1087 if( Header->GetSwapCode() )
1089 ln = Header->SwapLong(ln); // Fragment Item length
1091 fragmentBegining = ftell( fp );
1095 // JPEG 2000 : call to ???
1096 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1097 // ------------------------------------- endif (JPEG2000)
1099 else if (jpgLossless)
1101 // JPEG LossLess : call to xmedcom Lossless JPEG
1102 // Reading Fragment pixels
1103 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1104 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1105 res = 1; // in order not to break the loop
1107 } // ------------------------------------- endif (JPEGLossless)
1110 // JPEG Lossy : call to IJG 6b
1111 if ( Header->GetBitsStored() == 8)
1113 // Reading Fragment pixels
1114 res = gdcm_read_JPEG_file (fp,destination);
1118 // Reading Fragment pixels
1119 res = gdcm_read_JPEG_file12 (fp,destination);
1121 // ------------------------------------- endif (JPEGLossy)
1129 // location in user's memory
1130 // for next fragment (if any)
1131 destination = (uint8_t*)destination + taille * nBytes;
1133 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1134 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1136 ItemTagGr = ItemTagEl = 0;
1137 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1138 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1139 if( Header->GetSwapCode() )
1141 ItemTagGr = Header->SwapShort( ItemTagGr );
1142 ItemTagEl = Header->SwapShort( ItemTagEl );
1145 // endWhile parsing fragments until Sequence Delim. Tag found
1147 Header->CloseFile();
1150 //-----------------------------------------------------------------------------