1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/09/24 12:28:40 $
7 Version: $Revision: 1.130 $
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 canonical destructor
74 * \note If the gdcmHeader was created by the gdcmFile constructor,
75 * it is destroyed by the gdcmFile
85 DeleteInitialValues();
90 * \brief Sets some initial values for the Constructor
91 * \warning not end user intended
93 void gdcmFile::SaveInitialValues()
96 PixelRead = -1; // no ImageData read yet.
97 LastAllocatedPixelDataLength = 0;
102 InitialPlanConfig = "";
103 InitialBitsAllocated = "";
106 InitialRedLUTDescr = 0;
107 InitialGreenLUTDescr = 0;
108 InitialBlueLUTDescr = 0;
109 InitialRedLUTData = 0;
110 InitialGreenLUTData = 0;
111 InitialBlueLUTData = 0;
113 if ( Header->IsReadable() )
115 SetPixelDataSizeFromHeader();
117 // the following values *may* be modified
118 // by gdcmFile::GetImageDataIntoVectorRaw
119 // we save their initial value.
120 InitialSpp = Header->GetEntryByNumber(0x0028,0x0002);
121 InitialPhotInt = Header->GetEntryByNumber(0x0028,0x0004);
122 InitialPlanConfig = Header->GetEntryByNumber(0x0028,0x0006);
124 InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
125 InitialHighBit = Header->GetEntryByNumber(0x0028,0x0102);
127 // the following entries *may* be removed from the H table
128 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
129 // we keep a pointer on them.
130 InitialRedLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1101);
131 InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
132 InitialBlueLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1103);
134 InitialRedLUTData = Header->GetDocEntryByNumber(0x0028,0x1201);
135 InitialGreenLUTData = Header->GetDocEntryByNumber(0x0028,0x1202);
136 InitialBlueLUTData = Header->GetDocEntryByNumber(0x0028,0x1203);
142 * \brief restores some initial values
143 * \warning not end user intended
145 void gdcmFile::RestoreInitialValues()
147 if ( Header->IsReadable() )
149 // the following values *may* have been modified
150 // by gdcmFile::GetImageDataIntoVectorRaw
151 // we restore their initial value.
152 if ( InitialSpp != "")
153 Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
154 if ( InitialPhotInt != "")
155 Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
156 if ( InitialPlanConfig != "")
158 Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
159 if ( InitialBitsAllocated != "")
160 Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
161 if ( InitialHighBit != "")
162 Header->SetEntryByNumber(InitialHighBit,0x0028,0x0102);
164 // the following entries *may* be have been removed from the H table
165 // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw
168 if (InitialRedLUTDescr)
169 Header->AddEntry(InitialRedLUTDescr);
170 if (InitialGreenLUTDescr)
171 Header->AddEntry(InitialGreenLUTDescr);
172 if (InitialBlueLUTDescr)
173 Header->AddEntry(InitialBlueLUTDescr);
175 if (InitialRedLUTData)
176 Header->AddEntry(InitialBlueLUTDescr);
177 if (InitialGreenLUTData)
178 Header->AddEntry(InitialGreenLUTData);
179 if (InitialBlueLUTData)
180 Header->AddEntry(InitialBlueLUTData);
186 * \brief delete initial values (il they were saved)
187 * of InitialLutDescriptors and InitialLutData
189 void gdcmFile::DeleteInitialValues()
192 // InitialLutDescriptors and InitialLutData
193 // will have to be deleted if the don't belong any longer
194 // to the Header H table when the header is deleted...
196 if ( InitialRedLUTDescr )
197 delete InitialRedLUTDescr;
199 if ( InitialGreenLUTDescr )
200 delete InitialGreenLUTDescr;
202 if ( InitialBlueLUTDescr )
203 delete InitialBlueLUTDescr;
205 if ( InitialRedLUTData )
206 delete InitialRedLUTData;
208 if ( InitialGreenLUTData != NULL)
209 delete InitialGreenLUTData;
211 if ( InitialBlueLUTData != NULL)
212 delete InitialBlueLUTData;
217 * \brief drop palette related initial values -if any-
218 * (InitialLutDescriptors and InitialLutData)
219 * out of header, to make it consistent with the Pixel_Data
220 * as it's loaded in memory
223 //FIXME : Should be nice, if we could let it here.
224 // will be moved to PixelData class
225 // Now, the job is done in gdcmHeader.cxx
228 void gdcmFile::DropInitialValues()
230 gdcmHeader* h=GetHeader();
231 if ( GetEntryByNumber(0x0028,0x0002).c_str()[0] == '3' )
233 // if SamplesPerPixel = 3, sure we don't need any LUT !
234 // Drop 0028|1101, 0028|1102, 0028|1103
235 // Drop 0028|1201, 0028|1202, 0028|1203
237 gdcmDocEntry* e = h->GetDocEntryByNumber(0x0028,0x01101);
240 h->RemoveEntryNoDestroy(e);
242 e = h->GetDocEntryByNumber(0x0028,0x1102);
245 h->RemoveEntryNoDestroy(e);
247 e = h->GetDocEntryByNumber(0x0028,0x1103);
250 h->RemoveEntryNoDestroy(e);
252 e = h->GetDocEntryByNumber(0x0028,0x01201);
255 h->RemoveEntryNoDestroy(e);
257 e = h->GetDocEntryByNumber(0x0028,0x1202);
260 h->RemoveEntryNoDestroy(e);
262 e = h->GetDocEntryByNumber(0x0028,0x1203);
265 h->RemoveEntryNoDestroy(e);
271 //-----------------------------------------------------------------------------
274 //-----------------------------------------------------------------------------
279 * \brief computes the length (in bytes) we must ALLOCATE to receive the
280 * image(s) pixels (multiframes taken into account)
281 * \warning : it is NOT the group 7FE0 length
282 * (no interest for compressed images).
283 * \warning : not end user intended ?
285 void gdcmFile::SetPixelDataSizeFromHeader()
287 // see PS 3.3-2003 : C.7.6.3.2.1
297 // YBR_FULL_422 (no LUT, no Palette)
303 // ex : gdcm-US-ALOKA-16.dcm
304 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
305 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
306 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
308 // ex : OT-PAL-8-face.dcm
309 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
310 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
311 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
313 // Number of "Bits Allocated"
315 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
317 if ( str_nb == GDCM_UNFOUND )
323 nb = atoi( str_nb.c_str() );
330 ImageDataSizeRaw = Header->GetXSize() * Header->GetYSize()
331 * Header->GetZSize() * (nb/8) * Header->GetSamplesPerPixel();
332 std::string str_PhotometricInterpretation =
333 Header->GetEntryByNumber(0x0028,0x0004);
335 // if ( str_PhotometricInterpretation == "PALETTE COLOR " ),
336 // pb when undealt Segmented Palette Color
338 if ( Header->HasLUT() )
346 * \brief - Allocates necessary memory,
347 * - Reads the pixels from disk (uncompress if necessary),
348 * - Transforms YBR pixels, if any, into RGB pixels
349 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
350 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
351 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
352 * @return Pointer to newly allocated pixel data.
353 * NULL if alloc fails
355 uint8_t* gdcmFile::GetImageData()
358 // I need to deallocate Pixel_Data before doing any allocation:
361 if ( LastAllocatedPixelDataLength != ImageDataSize )
364 Pixel_Data = new uint8_t[ImageDataSize];
368 LastAllocatedPixelDataLength = ImageDataSize;
370 // we load the pixels (and transform grey level + LUT into RGB)
371 GetImageDataIntoVector(Pixel_Data, ImageDataSize);
373 // We say the value *is* loaded.
374 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
375 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
377 // Will be 7fe0, 0010 in standard case
378 GetHeader()->SetEntryBinAreaByNumber( Pixel_Data,
379 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
381 PixelRead = 0; // no PixelRaw
389 * Read the pixels from disk (uncompress if necessary),
390 * Transforms YBR pixels, if any, into RGB pixels
391 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
392 * Transforms single Grey plane + 3 Palettes into a RGB Plane
393 * Copies at most MaxSize bytes of pixel data to caller allocated
395 * \warning This function allows people that want to build a volume
396 * from an image stack *not to* have, first to get the image pixels,
397 * and then move them to the volume area.
398 * It's absolutely useless for any VTK user since vtk chooses
399 * to invert the lines of an image, that is the last line comes first
400 * (for some axis related reasons?). Hence he will have
401 * to load the image line by line, starting from the end.
402 * VTK users have to call GetImageData
404 * @param destination Address (in caller's memory space) at which the
405 * pixel data should be copied
406 * @param maxSize Maximum number of bytes to be copied. When MaxSize
407 * is not sufficient to hold the pixel data the copy is not
408 * executed (i.e. no partial copy).
409 * @return On success, the number of bytes actually copied. Zero on
410 * failure e.g. MaxSize is lower than necessary.
412 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
414 GetImageDataIntoVectorRaw (destination, maxSize);
415 PixelRead = 0 ; // =0 : no ImageDataRaw
416 if ( !Header->HasLUT() )
418 return ImageDataSize;
421 // from Lut R + Lut G + Lut B
422 uint8_t *newDest = new uint8_t[ImageDataSize];
423 uint8_t *a = (uint8_t *)destination;
424 uint8_t *lutRGBA = Header->GetLUTRGBA();
429 // move Gray pixels to temp area
430 memmove(newDest, destination, ImageDataSizeRaw);
431 for (size_t i=0; i<ImageDataSizeRaw; ++i)
441 // now, it's an RGB image
442 // Lets's write it in the Header
444 // FIXME : Better use CreateOrReplaceIfExist ?
446 std::string spp = "3"; // Samples Per Pixel
447 Header->SetEntryByNumber(spp,0x0028,0x0002);
448 std::string rgb = "RGB "; // Photometric Interpretation
449 Header->SetEntryByNumber(rgb,0x0028,0x0004);
450 std::string planConfig = "0"; // Planar Configuration
451 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
454 else // GetLUTRGBA() failed
456 // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color
457 // that are *more* than 65535 long ?!?
458 // No idea how to manage such an image !
459 // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut (!?!)
460 // It seems that *no Dicom Viewer* has any idea :-(
462 std::string photomInterp = "MONOCHROME1 "; // Photometric Interpretation
463 Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
466 /// \todo Drop Palette Color out of the Header?
467 return ImageDataSize;
472 * \brief Allocates necessary memory,
473 * Transforms YBR pixels (if any) into RGB pixels
474 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
475 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
476 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
477 * @return Pointer to newly allocated pixel data.
478 * \ NULL if alloc fails
480 uint8_t* gdcmFile::GetImageDataRaw ()
483 if ( Header->HasLUT() )
484 /// \todo Let gdcmHeader user a chance to get the right value
485 imgDataSize = ImageDataSizeRaw;
487 imgDataSize = ImageDataSize;
490 // I need to deallocate Pixel_Data before doing any allocation:
493 if ( LastAllocatedPixelDataLength != imgDataSize )
496 Pixel_Data = new uint8_t[imgDataSize];
500 LastAllocatedPixelDataLength = imgDataSize;
502 // we load the pixels ( grey level or RGB, but NO transformation)
503 GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
505 // We say the value *is* loaded.
506 GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
507 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
509 // will be 7fe0, 0010 in standard cases
510 GetHeader()->SetEntryBinAreaByNumber(Pixel_Data,
511 GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
513 PixelRead = 1; // PixelRaw
520 * \brief Copies at most MaxSize bytes of pixel data to caller's
522 * \warning This function was designed to avoid people that want to build
523 * a volume from an image stack to need first to get the image pixels
524 * and then move them to the volume area.
525 * It's absolutely useless for any VTK user since vtk chooses
526 * to invert the lines of an image, that is the last line comes first
527 * (for some axis related reasons?). Hence he will have
528 * to load the image line by line, starting from the end.
529 * VTK users hace to call GetImageData
530 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
531 * into a single RGB Pixels Plane
532 * the (VTK) user will manage the palettes
534 * @param destination Address (in caller's memory space) at which the
535 * pixel data should be copied
536 * @param maxSize Maximum number of bytes to be copied. When MaxSize
537 * is not sufficient to hold the pixel data the copy is not
538 * executed (i.e. no partial copy).
539 * @return On success, the number of bytes actually copied. Zero on
540 * failure e.g. MaxSize is lower than necessary.
542 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t maxSize)
544 int nb, nbu, highBit, sign;
546 // we save the initial values of the following
547 // in order to be able to restore the header in a disk-consistent state
548 // (if user asks twice to get the pixels from disk)
550 if ( PixelRead != -1 ) // File was "read" before
552 RestoreInitialValues();
555 PixelRead = 1 ; // PixelRaw
557 if ( ImageDataSize > maxSize )
559 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
560 "than caller's expected MaxSize");
564 ReadPixelData( destination );
566 // Number of Bits Allocated for storing a Pixel
567 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
568 if ( str_nb == GDCM_UNFOUND )
574 nb = atoi( str_nb.c_str() );
576 // From reading SetPixelDataSizeFromHeader, it seems 12 should be treated
577 // separately, correct ?
580 // Number of Bits actually used
581 std::string str_nbu = Header->GetEntryByNumber(0x0028,0x0101);
582 if ( str_nbu == GDCM_UNFOUND )
588 nbu = atoi( str_nbu.c_str() );
592 std::string str_highBit = Header->GetEntryByNumber(0x0028,0x0102);
593 if ( str_highBit == GDCM_UNFOUND )
599 highBit = atoi( str_highBit.c_str() );
605 std::string str_sign = Header->GetEntryByNumber(0x0028,0x0103);
606 if ( str_sign == GDCM_UNFOUND )
608 sign = 0; // default is unsigned
612 sign = atoi( str_sign.c_str() );
615 // re arange bytes inside the integer (processor endianity)
618 SwapZone(destination, Header->GetSwapCode(), ImageDataSize, nb);
621 // to avoid pb with some xmedcon breakers images
622 if ( nb == 16 && nbu < nb && sign == 0)
624 int l = (int)(ImageDataSize / (nb/8));
625 uint16_t *deb = (uint16_t *)destination;
626 for(int i = 0; i<l; i++)
636 // re arange bits inside the bytes
639 int l = (int)(ImageDataSize / (nb/8));
642 uint16_t mask = 0xffff;
643 mask = mask >> (nb-nbu);
644 uint16_t *deb = (uint16_t *)destination;
645 for(int i = 0; i<l; i++)
647 *deb = (*deb >> (nbu - highBit - 1)) & mask;
653 uint32_t mask = 0xffffffff;
654 mask = mask >> (nb - nbu);
655 uint32_t *deb = (uint32_t *)destination;
656 for(int i = 0; i<l; i++)
658 *deb = (*deb >> (nbu - highBit - 1)) & mask;
664 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
669 /// DO NOT remove this code commented out.
670 /// Nobody knows what's expecting you ...
671 /// Just to 'see' what was actually read on disk :-(
674 /// f2 = fopen("SpuriousFile.RAW","wb");
675 /// fwrite(destination,ImageDataSize,1,f2);
678 // Deal with the color
679 // -------------------
681 std::string str_PhotometricInterpretation =
682 Header->GetEntryByNumber(0x0028,0x0004);
684 if ( str_PhotometricInterpretation == "MONOCHROME1 "
685 || str_PhotometricInterpretation == "MONOCHROME2 " )
687 return ImageDataSize;
690 // Planar configuration = 0 : Pixels are already RGB
691 // Planar configuration = 1 : 3 planes : R, G, B
692 // Planar configuration = 2 : 1 gray Plane + 3 LUT
694 // Well ... supposed to be !
695 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
696 // PhotometricInterpretation=PALETTE COLOR
697 // and heuristic has to be found :-(
699 int planConf = Header->GetPlanarConfiguration(); // 0028,0006
701 // Whatever Planar Configuration is,
702 // "PALETTE COLOR " implies that we deal with the palette.
703 if ( str_PhotometricInterpretation == "PALETTE COLOR ")
711 // Pixels are already RGB
714 if (str_PhotometricInterpretation == "YBR_FULL")
716 // Warning : YBR_FULL_422 acts as RGB
717 // : we need to make RGB Pixels from Planes Y,cB,cR
719 // to see the tricks about YBR_FULL, YBR_FULL_422,
720 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
721 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
722 // and be *very* affraid
724 int l = Header->GetXSize() * Header->GetYSize();
725 int nbFrames = Header->GetZSize();
727 uint8_t* newDest = new uint8_t[ImageDataSize];
728 uint8_t* x = newDest;
729 uint8_t* a = (uint8_t*)destination;
734 /// \todo : Replace by the 'well known' integer computation
736 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
737 /// for code optimisation
739 for (int i = 0; i < nbFrames; i++)
741 for (int j = 0; j < l; j++)
743 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
744 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
745 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
747 if (R < 0.0) R = 0.0;
748 if (G < 0.0) G = 0.0;
749 if (B < 0.0) B = 0.0;
750 if (R > 255.0) R = 255.0;
751 if (G > 255.0) G = 255.0;
752 if (B > 255.0) B = 255.0;
760 memmove(destination, newDest, ImageDataSize);
765 // need to make RGB Pixels from R,G,B Planes
766 // (all the Frames at a time)
768 int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
770 uint8_t *newDest = new uint8_t[ImageDataSize];
771 uint8_t *x = newDest;
772 uint8_t *a = (uint8_t *)destination;
776 for (int j = 0; j < l; j++)
782 memmove(destination, newDest, ImageDataSize);
787 // Palettes were found
788 // Let the user deal with them !
789 return ImageDataSize;
791 // now, it's an RGB image
792 // Lets's write it in the Header
794 // Droping Palette Color out of the Header
795 // has been moved to the Write process.
797 // TODO : move 'values' modification to the write process
798 // : save also (in order to be able to restore)
799 // : 'high bit' -when not equal to 'bits stored' + 1
800 // : 'bits allocated', when it's equal to 12 ?!
802 std::string spp = "3"; // Samples Per Pixel
803 std::string photInt = "RGB "; // Photometric Interpretation
804 std::string planConfig = "0"; // Planar Configuration
806 Header->SetEntryByNumber(spp,0x0028,0x0002);
807 Header->SetEntryByNumber(photInt,0x0028,0x0004);
808 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
810 return ImageDataSize;
815 * \brief performs a shalow copy (not a deep copy) of the user given
817 * 'image' Pixels are presented as C-like 2D arrays : line per line.
818 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
819 * \warning user is kindly requested NOT TO 'free' the Pixel area
820 * @param inData user supplied pixel area
821 * @param expectedSize total image size, in Bytes
825 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
827 Header->SetImageDataSize( expectedSize );
828 // FIXME : if already allocated, memory leak !
830 ImageDataSize = ImageDataSizeRaw = expectedSize;
832 // FIXME : 7fe0, 0010 IS NOT set ...
838 * \brief Writes on disk A SINGLE Dicom file
839 * NO test is performed on processor "Endiannity".
840 * It's up to the user to call his Reader properly
841 * @param fileName name of the file to be created
842 * (any already existing file is over written)
843 * @return false if write fails
846 bool gdcmFile::WriteRawData(std::string const & fileName)
848 FILE* fp1 = fopen(fileName.c_str(), "wb");
851 printf("Fail to open (write) file [%s] \n", fileName.c_str());
854 fwrite (Pixel_Data, ImageDataSize, 1, fp1);
862 * \brief Writes on disk A SINGLE Dicom file,
863 * using the Implicit Value Representation convention
864 * NO test is performed on processor "Endiannity".
865 * @param fileName name of the file to be created
866 * (any already existing file is overwritten)
867 * @return false if write fails
870 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
872 return WriteBase(fileName, gdcmImplicitVR);
877 * \brief Writes on disk A SINGLE Dicom file,
878 * using the Explicit Value Representation convention
879 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
880 * (any already existing file is overwritten)
881 * @return false if write fails
884 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
886 return WriteBase(fileName, gdcmExplicitVR);
891 * \brief Writes on disk A SINGLE Dicom file,
892 * using the ACR-NEMA convention
893 * NO test is performed on processor "Endiannity".
894 * (a l'attention des logiciels cliniques
895 * qui ne prennent en entrée QUE des images ACR ...
896 * \warning if a DICOM_V3 header is supplied,
897 * groups < 0x0008 and shadow groups are ignored
898 * \warning NO TEST is performed on processor "Endiannity".
899 * @param fileName name of the file to be created
900 * (any already existing file is overwritten)
901 * @return false if write fails
904 bool gdcmFile::WriteAcr (std::string const & fileName)
906 return WriteBase(fileName, gdcmACR);
909 //-----------------------------------------------------------------------------
913 * \brief NOT a end user inteded function
914 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
915 * @param fileName name of the file to be created
916 * (any already existing file is overwritten)
917 * @param type file type (ExplicitVR, ImplicitVR, ...)
918 * @return false if write fails
920 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
922 if ( PixelRead == -1 && type != gdcmExplicitVR)
927 FILE* fp1 = fopen(fileName.c_str(), "wb");
930 printf("Failed to open (write) File [%s] \n", fileName.c_str());
934 if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
936 // writing Dicom File Preamble
937 uint8_t* filePreamble = new uint8_t[128];
938 memset(filePreamble, 0, 128);
939 fwrite(filePreamble, 128, 1, fp1);
940 fwrite("DICM", 4, 1, fp1);
942 delete[] filePreamble;
945 // --------------------------------------------------------------
946 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
948 // if recognition code tells us we dealt with a LibIDO image
949 // we reproduce on disk the switch between lineNumber and columnNumber
950 // just before writting ...
952 /// \todo the best trick would be *change* the recognition code
953 /// but pb expected if user deals with, e.g. COMPLEX images
955 std::string rows, columns;
956 if ( Header->GetFileType() == gdcmACR_LIBIDO)
958 rows = Header->GetEntryByNumber(0x0028, 0x0010);
959 columns = Header->GetEntryByNumber(0x0028, 0x0011);
961 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
962 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
964 // ----------------- End of Special Patch ----------------
966 uint16_t grPixel = Header->GetGrPixel();
967 uint16_t numPixel = Header->GetNumPixel();;
969 gdcmDocEntry* PixelElement =
970 GetHeader()->GetDocEntryByNumber(grPixel, numPixel);
972 if ( PixelRead == 1 )
974 // we read pixel 'as is' (no tranformation LUT -> RGB)
975 PixelElement->SetLength( ImageDataSizeRaw );
977 else if ( PixelRead == 0 )
979 // we tranformed GrayLevel pixels + LUT into RGB Pixel
980 PixelElement->SetLength( ImageDataSize );
983 Header->Write(fp1, type);
985 // --------------------------------------------------------------
986 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
988 // ...and we restore the Header to be Dicom Compliant again
989 // just after writting
991 if ( Header->GetFileType() == gdcmACR_LIBIDO )
993 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
994 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
996 // ----------------- End of Special Patch ----------------
998 // fwrite(Pixel_Data, ImageDataSize, 1, fp1); // should be useless, now
1004 //-----------------------------------------------------------------------------
1008 * \brief Swap the bytes, according to swap code.
1009 * \warning not end user intended
1010 * @param im area to deal with
1011 * @param swap swap code
1012 * @param lgr Area Length
1013 * @param nb Pixels Bit number
1015 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb)
1021 uint16_t* im16 = (uint16_t*)im;
1032 for(i=0; i < lgr/2; i++)
1034 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
1038 std::cout << "SWAP value (16 bits) not allowed :i" << swap <<
1045 uint16_t fort, faible;
1046 uint32_t* im32 = (uint32_t*)im;
1053 for(i = 0; i < lgr/4; i++)
1055 faible = im32[i] & 0x0000ffff; // 4321
1056 fort = im32[i] >> 16;
1057 fort = ( fort >> 8 ) | ( fort << 8 );
1058 faible = ( faible >> 8 ) | ( faible << 8);
1060 im32[i] = ( s32 << 16 ) | fort;
1064 for(i = 0; i < lgr/4; i++)
1066 faible = im32[i] & 0x0000ffff; // 2143
1067 fort = im32[i] >> 16;
1068 fort = ( fort >> 8 ) | ( fort << 8 );
1069 faible = ( faible >> 8) | ( faible << 8);
1071 im32[i] = ( s32 << 16 ) | faible;
1075 for(i = 0; i < lgr/4; i++)
1077 faible = im32[i] & 0x0000ffff; // 3412
1078 fort = im32[i] >> 16;
1080 im32[i] = ( s32 << 16 ) | fort;
1084 std::cout << "SWAP value (32 bits) not allowed : " << swap <<
1092 * \brief Read pixel data from disk (optionaly decompressing) into the
1093 * caller specified memory location.
1094 * @param destination where the pixel data should be stored.
1097 bool gdcmFile::ReadPixelData(void* destination)
1099 FILE* fp = Header->OpenFile();
1105 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1107 Header->CloseFile();
1111 // ---------------------- Compacted File (12 Bits Per Pixel)
1112 // unpack 12 Bits pixels into 16 Bits pixels
1113 // 2 pixels 12bit = [0xABCDEF]
1114 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1116 if ( Header->GetBitsAllocated() == 12 )
1118 int nbPixels = Header->GetXSize() * Header->GetYSize();
1121 uint16_t* pdestination = (uint16_t*)destination;
1122 for(int p = 0; p < nbPixels; p += 2 )
1128 //Two steps is necessary to please VC++
1129 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1131 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1134 // Troubles expected on Big-Endian processors ?
1137 Header->CloseFile();
1141 // ---------------------- Uncompressed File
1142 if ( !Header->IsDicomV3() ||
1143 Header->IsImplicitVRLittleEndianTransferSyntax() ||
1144 Header->IsExplicitVRLittleEndianTransferSyntax() ||
1145 Header->IsExplicitVRBigEndianTransferSyntax() ||
1146 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1148 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1149 Header->CloseFile();
1150 if ( ItemRead != 1 )
1160 // ---------------------- Run Length Encoding
1161 if ( Header->IsRLELossLessTransferSyntax() )
1163 bool res = gdcm_read_RLE_file (fp,destination);
1164 Header->CloseFile();
1168 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
1170 std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1171 if ( str_nb == GDCM_UNFOUND )
1177 nb = atoi( str_nb.c_str() );
1180 nb = 16; // ?? 12 should be ACR-NEMA only
1185 int taille = Header->GetXSize() * Header->GetYSize()
1186 * Header->GetSamplesPerPixel();
1187 long fragmentBegining; // for ftell, fseek
1189 bool jpg2000 = Header->IsJPEG2000();
1190 bool jpgLossless = Header->IsJPEGLossless();
1193 uint16_t ItemTagGr, ItemTagEl;
1196 // Position on begining of Jpeg Pixels
1198 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1199 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1200 if(Header->GetSwapCode())
1202 ItemTagGr = Header->SwapShort(ItemTagGr);
1203 ItemTagEl = Header->SwapShort(ItemTagEl);
1207 if( Header->GetSwapCode() )
1209 ln = Header->SwapLong( ln ); // Basic Offset Table Item length
1214 // What is it used for ?!?
1215 uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1216 fread(BasicOffsetTableItemValue,ln,1,fp);
1217 //delete[] BasicOffsetTableItemValue;
1220 // first Fragment initialisation
1221 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1222 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1223 if( Header->GetSwapCode() )
1225 ItemTagGr = Header->SwapShort( ItemTagGr );
1226 ItemTagEl = Header->SwapShort( ItemTagEl );
1229 // parsing fragments until Sequence Delim. Tag found
1230 while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1232 // --- for each Fragment
1234 if( Header->GetSwapCode() )
1236 ln = Header->SwapLong(ln); // Fragment Item length
1238 fragmentBegining = ftell( fp );
1242 // JPEG 2000 : call to ???
1243 res = gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
1244 // ------------------------------------- endif (JPEG2000)
1246 else if (jpgLossless)
1248 // JPEG LossLess : call to xmedcom Lossless JPEG
1249 // Reading Fragment pixels
1250 JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1251 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1252 res = 1; // in order not to break the loop
1254 } // ------------------------------------- endif (JPEGLossless)
1257 // JPEG Lossy : call to IJG 6b
1258 if ( Header->GetBitsStored() == 8)
1260 // Reading Fragment pixels
1261 res = gdcm_read_JPEG_file (fp,destination);
1265 // Reading Fragment pixels
1266 res = gdcm_read_JPEG_file12 (fp,destination);
1268 // ------------------------------------- endif (JPEGLossy)
1276 // location in user's memory
1277 // for next fragment (if any)
1278 destination = (uint8_t*)destination + taille * nBytes;
1280 fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start
1281 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1283 ItemTagGr = ItemTagEl = 0;
1284 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1285 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1286 if( Header->GetSwapCode() )
1288 ItemTagGr = Header->SwapShort( ItemTagGr );
1289 ItemTagEl = Header->SwapShort( ItemTagEl );
1292 // endWhile parsing fragments until Sequence Delim. Tag found
1294 Header->CloseFile();
1297 //-----------------------------------------------------------------------------