1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/06/22 14:14:01 $
7 Version: $Revision: 1.106 $
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) {
44 PixelRead=-1; // no ImageData read yet.
46 if (Header->IsReadable())
47 SetPixelDataSizeFromHeader();
52 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
53 * file (see SetFileName, SetDcmTag and Write)
54 * Opens (in read only and when possible) an existing file and checks
55 * for DICOM compliance. Returns NULL on failure.
56 * \note the in-memory representation of all available tags found in
57 * the DICOM header is post-poned to first header information access.
58 * This avoid a double parsing of public part of the header when
59 * one sets an a posteriori shadow dictionary (efficiency can be
60 * seen as a side effect).
61 * @param filename file to be opened for parsing
62 * @param exception_on_error whether we throw an exception or not
63 * @param enable_sequences = true to allow the header
64 * to be parsed *inside* the SeQuences,
65 * when they have an actual length
66 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
67 * @param ignore_shadow to allow skipping the shadow elements,
68 * to save memory space.
69 * \warning The TRUE value for this param has to be used
70 * with a FALSE value for the 'enable_sequence' param.
71 * ('public elements' may be embedded in 'shadow Sequences')
73 gdcmFile::gdcmFile(std::string const & filename,
74 bool exception_on_error,
75 bool enable_sequences,
77 Header=new gdcmHeader(filename.c_str(),
82 PixelRead=-1; // no ImageData read yet.
84 if (Header->IsReadable())
85 SetPixelDataSizeFromHeader();
90 * \brief canonical destructor
91 * \note If the gdcmHeader is created by the gdcmFile, it is destroyed
94 gdcmFile::~gdcmFile(void) {
100 //-----------------------------------------------------------------------------
103 //-----------------------------------------------------------------------------
108 * \brief computes the length (in bytes) to ALLOCATE to receive the
109 * image(s) pixels (multiframes taken into account)
110 * \warning : it is NOT the group 7FE0 length
111 * (no interest for compressed images).
112 * @return length to allocate
114 void gdcmFile::SetPixelDataSizeFromHeader(void) {
115 // see PS 3.3-2003 : C.7.6.3.2.1
125 // YBR_FULL_422 (no LUT, no Palette)
131 // ex : gdcm-US-ALOKA-16.dcm
132 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
133 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
134 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
136 // ex : OT-PAL-8-face.dcm
137 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
138 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
139 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
143 str_nb=Header->GetEntryByNumber(0x0028,0x0100);
144 if (str_nb == GDCM_UNFOUND ) {
147 nb = atoi(str_nb.c_str() );
148 if (nb == 12) nb =16;
150 lgrTotale = lgrTotaleRaw = Header->GetXSize() * Header->GetYSize()
151 * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
152 std::string str_PhotometricInterpretation =
153 Header->GetEntryByNumber(0x0028,0x0004);
155 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
156 // pb when undealt Segmented Palette Color
158 if (Header->HasLUT()) {
165 * \brief Returns the size (in bytes) of required memory to hold
166 * the pixel data represented in this file.
167 * @return The size of pixel data in bytes.
169 size_t gdcmFile::GetImageDataSize(void) {
175 * \brief Returns the size (in bytes) of required memory to hold
176 * the pixel data represented in this file, when user DOESN'T want
177 * to get RGB pixels image when it's stored as a PALETTE COLOR image
178 * -the (vtk) user is supposed to know how deal with LUTs-
179 * \warning to be used with GetImagePixelsRaw()
180 * @return The size of pixel data in bytes.
182 size_t gdcmFile::GetImageDataSizeRaw(void) {
183 return (lgrTotaleRaw);
188 * \brief Allocates necessary memory, copies the pixel data
189 * (image[s]/volume[s]) to newly allocated zone.
190 * Transforms YBR pixels into RGB pixels if any
191 * Transforms 3 planes R, G, B into a single RGB Plane
192 * Transforms single Grey plane + 3 Palettes into a RGB Plane
193 * @return Pointer to newly allocated pixel data.
194 * NULL if alloc fails
196 void * gdcmFile::GetImageData (void) {
197 PixelData = new char[lgrTotale];
199 GetImageDataIntoVector(PixelData, lgrTotale);
200 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
201 GetHeader()->GetGrPixel(),
202 GetHeader()->GetNumPixel());
204 PixelRead=0; // no PixelRaw
211 * \brief Copies at most MaxSize bytes of pixel data to caller's
213 * \warning This function was designed to avoid people that want to build
214 * a volume from an image stack to need first to get the image pixels
215 * and then move them to the volume area.
216 * It's absolutely useless for any VTK user since vtk chooses
217 * to invert the lines of an image, that is the last line comes first
218 * (for some axis related reasons?). Hence he will have
219 * to load the image line by line, starting from the end.
220 * VTK users have to call GetImageData
222 * @param destination Address (in caller's memory space) at which the
223 * pixel data should be copied
224 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
225 * is not sufficient to hold the pixel data the copy is not
226 * executed (i.e. no partial copy).
227 * @return On success, the number of bytes actually copied. Zero on
228 * failure e.g. MaxSize is lower than necessary.
230 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
231 //size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
232 GetImageDataIntoVectorRaw (destination, MaxSize);
233 PixelRead=0 ; // no PixelRaw
234 if (!Header->HasLUT())
237 // from Lut R + Lut G + Lut B
238 unsigned char *newDest = new unsigned char[lgrTotale];
239 unsigned char *a = (unsigned char *)destination;
240 unsigned char *lutRGBA = Header->GetLUTRGBA();
242 int l = lgrTotaleRaw;
243 memmove(newDest, destination, l);// move Gray pixels to temp area
245 for (int i=0;i<l; i++) { // Build RGB Pixels
253 // now, it's an RGB image
254 // Lets's write it in the Header
256 // CreateOrReplaceIfExist ?
258 std::string spp = "3"; // Samples Per Pixel
259 Header->SetEntryByNumber(spp,0x0028,0x0002);
260 std::string rgb= "RGB "; // Photometric Interpretation
261 Header->SetEntryByNumber(rgb,0x0028,0x0004);
262 std::string planConfig = "0"; // Planar Configuration
263 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
266 // need to make RGB Pixels (?)
267 // from grey Pixels (?!)
268 // and Gray Lut (!?!)
269 // or Segmented xxx Palette Color Lookup Table Data and so on
271 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
272 // No idea how to manage such an image
273 // It seems that *no Dicom Viewer* has any idea :-(
274 // Segmented xxx Palette Color are *more* than 65535 long ?!?
276 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
277 Header->SetEntryByNumber(rgb,0x0028,0x0004);
279 /// \todo Drop Palette Color out of the Header?
285 * \brief Allocates necessary memory, copies the pixel data
286 * (image[s]/volume[s]) to newly allocated zone.
287 * Transforms YBR pixels into RGB pixels if any
288 * Transforms 3 planes R, G, B into a single RGB Plane
289 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
290 * @return Pointer to newly allocated pixel data.
291 * \ NULL if alloc fails
293 void * gdcmFile::GetImageDataRaw (void) {
294 if (Header->HasLUT())
295 /// \todo Let gdcmHeadar user a chance to get the right value
296 /// Create a member lgrTotaleRaw ???
298 PixelData = new char[lgrTotale];
301 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
302 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
303 GetHeader()->GetGrPixel(),
304 GetHeader()->GetNumPixel());
306 PixelRead=1; // PixelRaw
312 * \brief Copies at most MaxSize bytes of pixel data to caller's
314 * \warning This function was designed to avoid people that want to build
315 * a volume from an image stack to need first to get the image pixels
316 * and then move them to the volume area.
317 * It's absolutely useless for any VTK user since vtk chooses
318 * to invert the lines of an image, that is the last line comes first
319 * (for some axis related reasons?). Hence he will have
320 * to load the image line by line, starting from the end.
321 * VTK users hace to call GetImageData
322 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
323 * into a single RGB Pixels Plane
324 * the (VTK) user will manage the palettes
326 * @param destination Address (in caller's memory space) at which the
327 * pixel data should be copied
328 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
329 * is not sufficient to hold the pixel data the copy is not
330 * executed (i.e. no partial copy).
331 * @return On success, the number of bytes actually copied. Zero on
332 * failure e.g. MaxSize is lower than necessary.
334 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
336 int nb, nbu, highBit, signe;
337 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
338 PixelRead=1 ; // PixelRaw
340 if ( lgrTotale > MaxSize ) {
341 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
342 "than caller's expected MaxSize");
346 (void)ReadPixelData(destination);
348 // Number of Bits Allocated for storing a Pixel
349 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
350 if (str_nb == GDCM_UNFOUND ) {
353 nb = atoi(str_nb.c_str() );
355 // Number of Bits actually used
356 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
357 if (str_nbu == GDCM_UNFOUND ) {
360 nbu = atoi(str_nbu.c_str() );
363 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
364 if (str_highBit == GDCM_UNFOUND ) {
367 highBit = atoi(str_highBit.c_str() );
372 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
373 if (str_signe == GDCM_UNFOUND ) {
374 signe = 0; // default is unsigned
376 signe = atoi(str_signe.c_str() );
379 // re arange bytes inside the integer (processor endianity)
381 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
383 // to avoid pb with some xmedcon breakers images
384 if (nb==16 && nbu<nb && signe==0) {
385 int l = (int)lgrTotale / (nb/8);
386 guint16 *deb = (guint16 *)destination;
387 for(int i = 0; i<l; i++) {
393 // re arange bits inside the bytes
395 int l = (int)lgrTotale / (nb/8);
397 guint16 mask = 0xffff;
398 mask = mask >> (nb-nbu);
399 guint16 *deb = (guint16 *)destination;
400 for(int i = 0; i<l; i++) {
401 *deb = (*deb >> (nbu-highBit-1)) & mask;
404 } else if (nb == 32 ) {
405 guint32 mask = 0xffffffff;
406 mask = mask >> (nb-nbu);
407 guint32 *deb = (guint32 *)destination;
408 for(int i = 0; i<l; i++) {
409 *deb = (*deb >> (nbu-highBit-1)) & mask;
413 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
417 // DO NOT remove this commented out code .
418 // Nobody knows what's expecting you ...
419 // Just to 'see' what was actually read on disk :-(
422 // f2 = fopen("SpuriousFile.RAW","wb");
423 // fwrite(destination,lgrTotale,1,f2);
426 // Deal with the color
427 // -------------------
429 std::string str_PhotometricInterpretation =
430 Header->GetEntryByNumber(0x0028,0x0004);
432 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
433 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
437 // Planar configuration = 0 : Pixels are already RGB
438 // Planar configuration = 1 : 3 planes : R, G, B
439 // Planar configuration = 2 : 1 gray Plane + 3 LUT
441 // Well ... supposed to be !
442 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
443 // PhotometricInterpretation=PALETTE COLOR
444 // and heuristic has to be found :-(
446 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
448 // Whatever Planar Configuration is,
449 // "PALETTE COLOR " implies that we deal with the palette.
450 if (str_PhotometricInterpretation == "PALETTE COLOR ")
455 // Pixels are already RGB
461 if (str_PhotometricInterpretation == "YBR_FULL") {
463 // Warning : YBR_FULL_422 acts as RGB
464 // : we need to make RGB Pixels from Planes Y,cB,cR
466 // to see the tricks about YBR_FULL, YBR_FULL_422,
467 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
468 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
469 // and be *very* affraid
471 int l = Header->GetXSize()*Header->GetYSize();
472 int nbFrames = Header->GetZSize();
474 unsigned char *newDest = new unsigned char[lgrTotale];
475 unsigned char *x = newDest;
476 unsigned char *a = (unsigned char *)destination;
477 unsigned char *b = a + l;
478 unsigned char *c = b + l;
481 /// \todo : Replace by the 'well known' integer computation
483 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
484 /// for code optimisation
486 for (int i=0;i<nbFrames;i++) {
487 for (int j=0;j<l; j++) {
488 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
489 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
490 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
495 if (R>255.0) R=255.0;
496 if (G>255.0) G=255.0;
497 if (B>255.0) B=255.0;
499 *(x++) = (unsigned char)R;
500 *(x++) = (unsigned char)G;
501 *(x++) = (unsigned char)B;
505 memmove(destination,newDest,lgrTotale);
510 // need to make RGB Pixels from R,G,B Planes
511 // (all the Frames at a time)
513 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
515 char *newDest = new char[lgrTotale];
517 char *a = (char *)destination;
521 for (int j=0;j<l; j++) {
526 memmove(destination,newDest,lgrTotale);
532 // Palettes were found
533 // Let the user deal with them !
536 // now, it's an RGB image
537 // Lets's write it in the Header
539 // CreateOrReplaceIfExist ?
541 std::string spp = "3"; // Samples Per Pixel
542 Header->SetEntryByNumber(spp,0x0028,0x0002);
543 std::string rgb="RGB "; // Photometric Interpretation
544 Header->SetEntryByNumber(rgb,0x0028,0x0004);
546 std::string planConfig = "0"; // Planar Configuration
547 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
549 /// \todo Drop Palette Color out of the Header?
555 * \brief performs a shadow copy (not a deep copy) of the user given
557 * 'image' Pixels are presented as C-like 2D arrays : line per line.
558 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
559 * \warning user is kindly requested NOT TO 'free' the Pixel area
560 * @param inData user supplied pixel area
561 * @param ExpectedSize total image size, in Bytes
565 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
566 Header->SetImageDataSize(ExpectedSize);
568 lgrTotale = ExpectedSize;
575 * \brief Writes on disk A SINGLE Dicom file
576 * NO test is performed on processor "Endiannity".
577 * It's up to the user to call his Reader properly
578 * @param fileName name of the file to be created
579 * (any already existing file is over written)
580 * @return false if write fails
583 bool gdcmFile::WriteRawData (std::string fileName) {
585 fp1 = fopen(fileName.c_str(),"wb");
587 printf("Fail to open (write) file [%s] \n",fileName.c_str());
590 fwrite (PixelData,lgrTotale, 1, fp1);
597 * \brief Writes on disk A SINGLE Dicom file,
598 * using the Implicit Value Representation convention
599 * NO test is performed on processor "Endiannity".
600 * @param fileName name of the file to be created
601 * (any already existing file is overwritten)
602 * @return false if write fails
605 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
606 return WriteBase(fileName, gdcmImplicitVR);
611 * \brief Writes on disk A SINGLE Dicom file,
612 * using the Implicit Value Representation convention
613 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
614 * (any already existing file is overwritten)
615 * @return false if write fails
618 bool gdcmFile::WriteDcmImplVR (const char *fileName) {
619 return WriteDcmImplVR (std::string (fileName));
624 * \brief Writes on disk A SINGLE Dicom file,
625 * using the Explicit Value Representation convention
626 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
627 * (any already existing file is overwritten)
628 * @return false if write fails
631 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
632 return WriteBase(fileName, gdcmExplicitVR);
637 * \brief Writes on disk A SINGLE Dicom file,
638 * using the ACR-NEMA convention
639 * NO test is performed on processor "Endiannity".
640 * (a l'attention des logiciels cliniques
641 * qui ne prennent en entrée QUE des images ACR ...
642 * \warning if a DICOM_V3 header is supplied,
643 * groups < 0x0008 and shadow groups are ignored
644 * \warning NO TEST is performed on processor "Endiannity".
645 * @param fileName name of the file to be created
646 * (any already existing file is overwritten)
647 * @return false if write fails
650 bool gdcmFile::WriteAcr (std::string fileName) {
651 return WriteBase(fileName, gdcmACR);
654 //-----------------------------------------------------------------------------
658 * \brief NOT a end user inteded function
659 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
660 * @param fileName name of the file to be created
661 * (any already existing file is overwritten)
662 * @param type file type (ExplicitVR, ImplicitVR, ...)
663 * @return false if write fails
665 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
669 if (PixelRead==-1 && type != gdcmExplicitVR) {
673 fp1 = fopen(fileName.c_str(),"wb");
675 printf("Failed to open (write) File [%s] \n",fileName.c_str());
679 if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
681 // writing Dicom File Preamble
682 filePreamble=new char[128];
683 memset(filePreamble,0,128);
684 fwrite(filePreamble,128,1,fp1);
685 fwrite("DICM",4,1,fp1);
686 delete[] filePreamble;
689 // --------------------------------------------------------------
690 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
692 // if recognition code tells us we dealt with a LibIDO image
693 // we reproduce on disk the switch between lineNumber and columnNumber
694 // just before writting ...
696 /// \todo the best trick would be *change* the recognition code
697 /// but pb expected if user deals with, e.g. COMPLEX images
699 std::string rows, columns;
700 if ( Header->GetFileType() == gdcmACR_LIBIDO){
701 rows = Header->GetEntryByNumber(0x0028, 0x0010);
702 columns = Header->GetEntryByNumber(0x0028, 0x0011);
703 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
704 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
706 // ----------------- End of Special Patch ----------------
708 /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
710 guint16 grPixel =Header->GetGrPixel();
711 guint16 numPixel=Header->GetNumPixel();;
713 // Update Pixel Data Length
714 // the *last* of the (GrPixel, NumPixel), if many.
716 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
717 TagDocEntryHT::iterator p2;
718 gdcmDocEntry *PixelElement;
720 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
722 if (Header->GetEntry().count(key) == 1) // only the first is significant
723 p2=it.first; // iterator on the first (unique) synonym
725 p2=it.second;// iterator on the last synonym
727 PixelElement=p2->second; // H Table target column (2-nd col)
728 // PixelElement->SetPrintLevel(2);
729 // PixelElement->Print();
732 PixelElement->SetLength(lgrTotaleRaw);
733 else if (PixelRead==0)
734 PixelElement->SetLength(lgrTotale);
736 //PixelElement->SetPrintLevel(2);
737 //PixelElement->Print();
738 Header->Write(fp1, type);
740 // --------------------------------------------------------------
741 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
743 // ...and we restore the Header to be Dicom Compliant again
744 // just after writting
746 if (Header->GetFileType() == gdcmACR_LIBIDO){
747 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
748 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
750 // ----------------- End of Special Patch ----------------
752 // fwrite(PixelData, lgrTotale, 1, fp1); // should be useless, now
757 //-----------------------------------------------------------------------------
761 * \brief Swap the bytes, according to swap code.
762 * \warning not end user intended
763 * @param im area to deal with
764 * @param swap swap code
765 * @param lgr Area Length
766 * @param nb Pixels Bit number
768 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
785 for(i=0;i<lgr/2;i++) {
786 ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
787 | ((((unsigned short int *)im)[i])<<8);
792 printf("SWAP value (16 bits) not allowed : %d\n", swap);
802 for(i=0;i<lgr/4;i++) {
803 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 4321 */
804 fort =((unsigned long int *)im)[i]>>16;
805 fort= (fort>>8) | (fort<<8);
806 faible=(faible>>8) | (faible<<8);
808 ((unsigned long int *)im)[i]=(s32<<16)|fort;
813 for(i=0;i<lgr/4;i++) {
814 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 2143 */
815 fort=((unsigned long int *)im)[i]>>16;
816 fort= (fort>>8) | (fort<<8);
817 faible=(faible>>8) | (faible<<8);
819 ((unsigned long int *)im)[i]=(s32<<16)|faible;
824 for(i=0;i<lgr/4;i++) {
825 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 3412 */
826 fort=((unsigned long int *)im)[i]>>16;
828 ((unsigned long int *)im)[i]=(s32<<16)|fort;
833 printf("SWAP value (32 bits) not allowed : %d\n", swap);
840 * \brief Read pixel data from disk (optionaly decompressing) into the
841 * caller specified memory location.
842 * @param destination where the pixel data should be stored.
845 bool gdcmFile::ReadPixelData(void *destination) {
849 if ( !(fp=Header->OpenFile()))
851 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
855 // ---------------------- Compacted File (12 Bits Per Pixel)
856 /* unpack 12 Bits pixels into 16 Bits pixels */
857 /* 2 pixels 12bit = [0xABCDEF] */
858 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
860 if (Header->GetBitsAllocated()==12) {
861 int nbPixels = Header->GetXSize() * Header->GetYSize();
862 unsigned char b0, b1, b2;
864 unsigned short int *pdestination = (unsigned short int*)destination;
865 for(int p=0;p<nbPixels;p+=2) {
869 //Two steps is necessary to please VC++
870 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
871 /* A */ /* B */ /* D */
872 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
873 /* F */ /* C */ /* E */
875 // Troubles expected on Big-Endian processors ?
882 // ---------------------- Uncompressed File
883 if ( !Header->IsDicomV3() ||
884 Header->IsImplicitVRLittleEndianTransferSyntax() ||
885 Header->IsExplicitVRLittleEndianTransferSyntax() ||
886 Header->IsExplicitVRBigEndianTransferSyntax() ||
887 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
889 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
890 if ( ItemRead != 1 ) {
899 // ---------------------- Run Length Encoding
900 if (Header->IsRLELossLessTransferSyntax()) {
901 bool res = (bool)gdcm_read_RLE_file (fp,destination);
906 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
908 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
909 if (str_nb == GDCM_UNFOUND ) {
912 nb = atoi(str_nb.c_str() );
913 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
918 int taille = Header->GetXSize() * Header->GetYSize()
919 * Header->GetSamplesPerPixel();
920 long fragmentBegining; // for ftell, fseek
922 bool jpg2000 = Header->IsJPEG2000();
923 bool jpgLossless = Header->IsJPEGLossless();
926 guint16 ItemTagGr,ItemTagEl;
929 // Position on begining of Jpeg Pixels
931 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
932 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
933 if(Header->GetSwapCode()) {
934 ItemTagGr=Header->SwapShort(ItemTagGr);
935 ItemTagEl=Header->SwapShort(ItemTagEl);
938 if(Header->GetSwapCode())
939 ln=Header->SwapLong(ln); // Basic Offset Table Item length
942 // What is it used for ?!?
943 char *BasicOffsetTableItemValue = new char[ln+1];
944 fread(BasicOffsetTableItemValue,ln,1,fp);
947 // first Fragment initialisation
948 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
949 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
950 if(Header->GetSwapCode()) {
951 ItemTagGr=Header->SwapShort(ItemTagGr);
952 ItemTagEl=Header->SwapShort(ItemTagEl);
955 // parsing fragments until Sequence Delim. Tag found
956 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
957 // --- for each Fragment
960 if(Header->GetSwapCode())
961 ln=Header->SwapLong(ln); // Fragment Item length
963 fragmentBegining=ftell(fp);
965 if (jpg2000) { // JPEG 2000 : call to ???
967 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
969 } // ------------------------------------- endif (JPEG2000)
971 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
973 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
974 (unsigned short *)destination,
975 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(),
977 res=1; // in order not to break the loop
979 } // ------------------------------------- endif (JPEGLossless)
981 else { // JPEG Lossy : call to IJG 6b
983 if (Header->GetBitsStored() == 8) {
984 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
986 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
988 } // ------------------------------------- endif (JPEGLossy)
992 destination = (char *)destination + taille * nBytes; // location in user's memory
993 // for next fragment (if any)
995 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
996 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
998 ItemTagGr = ItemTagEl =0;
999 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1000 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1001 if(Header->GetSwapCode()) {
1002 ItemTagGr=Header->SwapShort(ItemTagGr);
1003 ItemTagEl=Header->SwapShort(ItemTagEl);
1006 } // endWhile parsing fragments until Sequence Delim. Tag found
1008 Header->CloseFile();
1011 //-----------------------------------------------------------------------------