1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/06/23 03:36:24 $
7 Version: $Revision: 1.107 $
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() {
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() {
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() {
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() {
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 () {
197 PixelData = new unsigned char[lgrTotale]; //consistant with GetImageDataIntoVector
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 () {
294 if (Header->HasLUT())
295 /// \todo Let gdcmHeadar user a chance to get the right value
296 /// Create a member lgrTotaleRaw ???
298 PixelData = new unsigned char[lgrTotale];
301 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
302 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
303 GetHeader()->GetGrPixel(),
304 GetHeader()->GetNumPixel());
306 PixelRead=1; // PixelRaw
313 * \brief Copies at most MaxSize bytes of pixel data to caller's
315 * \warning This function was designed to avoid people that want to build
316 * a volume from an image stack to need first to get the image pixels
317 * and then move them to the volume area.
318 * It's absolutely useless for any VTK user since vtk chooses
319 * to invert the lines of an image, that is the last line comes first
320 * (for some axis related reasons?). Hence he will have
321 * to load the image line by line, starting from the end.
322 * VTK users hace to call GetImageData
323 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
324 * into a single RGB Pixels Plane
325 * the (VTK) user will manage the palettes
327 * @param destination Address (in caller's memory space) at which the
328 * pixel data should be copied
329 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
330 * is not sufficient to hold the pixel data the copy is not
331 * executed (i.e. no partial copy).
332 * @return On success, the number of bytes actually copied. Zero on
333 * failure e.g. MaxSize is lower than necessary.
335 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
337 int nb, nbu, highBit, signe;
338 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
339 PixelRead=1 ; // PixelRaw
341 if ( lgrTotale > MaxSize ) {
342 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
343 "than caller's expected MaxSize");
347 ReadPixelData(destination);
349 // Number of Bits Allocated for storing a Pixel
350 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
351 if (str_nb == GDCM_UNFOUND ) {
354 nb = atoi(str_nb.c_str() );
356 // Number of Bits actually used
357 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
358 if (str_nbu == GDCM_UNFOUND ) {
361 nbu = atoi(str_nbu.c_str() );
364 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
365 if (str_highBit == GDCM_UNFOUND ) {
368 highBit = atoi(str_highBit.c_str() );
373 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
374 if (str_signe == GDCM_UNFOUND ) {
375 signe = 0; // default is unsigned
377 signe = atoi(str_signe.c_str() );
380 // re arange bytes inside the integer (processor endianity)
382 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
384 // to avoid pb with some xmedcon breakers images
385 if (nb==16 && nbu<nb && signe==0) {
386 int l = (int)lgrTotale / (nb/8);
387 guint16 *deb = (guint16 *)destination;
388 for(int i = 0; i<l; i++) {
394 // re arange bits inside the bytes
396 int l = (int)lgrTotale / (nb/8);
398 guint16 mask = 0xffff;
399 mask = mask >> (nb-nbu);
400 guint16 *deb = (guint16 *)destination;
401 for(int i = 0; i<l; i++) {
402 *deb = (*deb >> (nbu-highBit-1)) & mask;
405 } else if (nb == 32 ) {
406 guint32 mask = 0xffffffff;
407 mask = mask >> (nb-nbu);
408 guint32 *deb = (guint32 *)destination;
409 for(int i = 0; i<l; i++) {
410 *deb = (*deb >> (nbu-highBit-1)) & mask;
414 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
418 // DO NOT remove this commented out code .
419 // Nobody knows what's expecting you ...
420 // Just to 'see' what was actually read on disk :-(
423 // f2 = fopen("SpuriousFile.RAW","wb");
424 // fwrite(destination,lgrTotale,1,f2);
427 // Deal with the color
428 // -------------------
430 std::string str_PhotometricInterpretation =
431 Header->GetEntryByNumber(0x0028,0x0004);
433 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
434 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
438 // Planar configuration = 0 : Pixels are already RGB
439 // Planar configuration = 1 : 3 planes : R, G, B
440 // Planar configuration = 2 : 1 gray Plane + 3 LUT
442 // Well ... supposed to be !
443 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
444 // PhotometricInterpretation=PALETTE COLOR
445 // and heuristic has to be found :-(
447 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
449 // Whatever Planar Configuration is,
450 // "PALETTE COLOR " implies that we deal with the palette.
451 if (str_PhotometricInterpretation == "PALETTE COLOR ")
456 // Pixels are already RGB
462 if (str_PhotometricInterpretation == "YBR_FULL") {
464 // Warning : YBR_FULL_422 acts as RGB
465 // : we need to make RGB Pixels from Planes Y,cB,cR
467 // to see the tricks about YBR_FULL, YBR_FULL_422,
468 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
469 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
470 // and be *very* affraid
472 int l = Header->GetXSize()*Header->GetYSize();
473 int nbFrames = Header->GetZSize();
475 unsigned char *newDest = new unsigned char[lgrTotale];
476 unsigned char *x = newDest;
477 unsigned char *a = (unsigned char *)destination;
478 unsigned char *b = a + l;
479 unsigned char *c = b + l;
482 /// \todo : Replace by the 'well known' integer computation
484 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
485 /// for code optimisation
487 for (int i=0;i<nbFrames;i++) {
488 for (int j=0;j<l; j++) {
489 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
490 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
491 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
496 if (R>255.0) R=255.0;
497 if (G>255.0) G=255.0;
498 if (B>255.0) B=255.0;
500 *(x++) = (unsigned char)R;
501 *(x++) = (unsigned char)G;
502 *(x++) = (unsigned char)B;
506 memmove(destination,newDest,lgrTotale);
511 // need to make RGB Pixels from R,G,B Planes
512 // (all the Frames at a time)
514 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
516 char *newDest = new char[lgrTotale];
518 char *a = (char *)destination;
522 for (int j=0;j<l; j++) {
527 memmove(destination,newDest,lgrTotale);
533 // Palettes were found
534 // Let the user deal with them !
537 // now, it's an RGB image
538 // Lets's write it in the Header
540 // CreateOrReplaceIfExist ?
542 std::string spp = "3"; // Samples Per Pixel
543 Header->SetEntryByNumber(spp,0x0028,0x0002);
544 std::string rgb="RGB "; // Photometric Interpretation
545 Header->SetEntryByNumber(rgb,0x0028,0x0004);
547 std::string planConfig = "0"; // Planar Configuration
548 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
550 /// \todo Drop Palette Color out of the Header?
556 * \brief performs a shadow copy (not a deep copy) of the user given
558 * 'image' Pixels are presented as C-like 2D arrays : line per line.
559 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
560 * \warning user is kindly requested NOT TO 'free' the Pixel area
561 * @param inData user supplied pixel area
562 * @param ExpectedSize total image size, in Bytes
566 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
567 Header->SetImageDataSize(ExpectedSize);
569 lgrTotale = ExpectedSize;
577 * \brief Writes on disk A SINGLE Dicom file
578 * NO test is performed on processor "Endiannity".
579 * It's up to the user to call his Reader properly
580 * @param fileName name of the file to be created
581 * (any already existing file is over written)
582 * @return false if write fails
585 bool gdcmFile::WriteRawData (std::string const & fileName) {
587 fp1 = fopen(fileName.c_str(),"wb");
589 printf("Fail to open (write) file [%s] \n",fileName.c_str());
592 fwrite (PixelData,lgrTotale, 1, fp1);
600 * \brief Writes on disk A SINGLE Dicom file,
601 * using the Implicit Value Representation convention
602 * NO test is performed on processor "Endiannity".
603 * @param fileName name of the file to be created
604 * (any already existing file is overwritten)
605 * @return false if write fails
608 bool gdcmFile::WriteDcmImplVR (std::string const & fileName) {
609 return WriteBase(fileName, gdcmImplicitVR);
614 * \brief Writes on disk A SINGLE Dicom file,
615 * using the Explicit Value Representation convention
616 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
617 * (any already existing file is overwritten)
618 * @return false if write fails
621 bool gdcmFile::WriteDcmExplVR (std::string const & fileName) {
622 return WriteBase(fileName, gdcmExplicitVR);
627 * \brief Writes on disk A SINGLE Dicom file,
628 * using the ACR-NEMA convention
629 * NO test is performed on processor "Endiannity".
630 * (a l'attention des logiciels cliniques
631 * qui ne prennent en entrée QUE des images ACR ...
632 * \warning if a DICOM_V3 header is supplied,
633 * groups < 0x0008 and shadow groups are ignored
634 * \warning NO TEST is performed on processor "Endiannity".
635 * @param fileName name of the file to be created
636 * (any already existing file is overwritten)
637 * @return false if write fails
640 bool gdcmFile::WriteAcr (std::string const & fileName) {
641 return WriteBase(fileName, gdcmACR);
644 //-----------------------------------------------------------------------------
648 * \brief NOT a end user inteded function
649 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
650 * @param fileName name of the file to be created
651 * (any already existing file is overwritten)
652 * @param type file type (ExplicitVR, ImplicitVR, ...)
653 * @return false if write fails
655 bool gdcmFile::WriteBase (std::string const & fileName, FileType type) {
659 if (PixelRead==-1 && type != gdcmExplicitVR) {
663 fp1 = fopen(fileName.c_str(),"wb");
665 printf("Failed to open (write) File [%s] \n",fileName.c_str());
669 if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
671 // writing Dicom File Preamble
672 filePreamble=new char[128];
673 memset(filePreamble,0,128);
674 fwrite(filePreamble,128,1,fp1);
675 fwrite("DICM",4,1,fp1);
676 delete[] filePreamble;
679 // --------------------------------------------------------------
680 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
682 // if recognition code tells us we dealt with a LibIDO image
683 // we reproduce on disk the switch between lineNumber and columnNumber
684 // just before writting ...
686 /// \todo the best trick would be *change* the recognition code
687 /// but pb expected if user deals with, e.g. COMPLEX images
689 std::string rows, columns;
690 if ( Header->GetFileType() == gdcmACR_LIBIDO){
691 rows = Header->GetEntryByNumber(0x0028, 0x0010);
692 columns = Header->GetEntryByNumber(0x0028, 0x0011);
693 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
694 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
696 // ----------------- End of Special Patch ----------------
698 /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
700 guint16 grPixel =Header->GetGrPixel();
701 guint16 numPixel=Header->GetNumPixel();;
703 // Update Pixel Data Length
704 // the *last* of the (GrPixel, NumPixel), if many.
706 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
707 TagDocEntryHT::iterator p2;
708 gdcmDocEntry *PixelElement;
710 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
712 if (Header->GetEntry().count(key) == 1) // only the first is significant
713 p2=it.first; // iterator on the first (unique) synonym
715 p2=it.second;// iterator on the last synonym
717 PixelElement=p2->second; // H Table target column (2-nd col)
718 // PixelElement->SetPrintLevel(2);
719 // PixelElement->Print();
722 PixelElement->SetLength(lgrTotaleRaw);
723 else if (PixelRead==0)
724 PixelElement->SetLength(lgrTotale);
726 //PixelElement->SetPrintLevel(2);
727 //PixelElement->Print();
728 Header->Write(fp1, type);
730 // --------------------------------------------------------------
731 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
733 // ...and we restore the Header to be Dicom Compliant again
734 // just after writting
736 if (Header->GetFileType() == gdcmACR_LIBIDO){
737 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
738 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
740 // ----------------- End of Special Patch ----------------
742 // fwrite(PixelData, lgrTotale, 1, fp1); // should be useless, now
748 //-----------------------------------------------------------------------------
752 * \brief Swap the bytes, according to swap code.
753 * \warning not end user intended
754 * @param im area to deal with
755 * @param swap swap code
756 * @param lgr Area Length
757 * @param nb Pixels Bit number
759 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
776 for(i=0;i<lgr/2;i++) {
777 ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
778 | ((((unsigned short int *)im)[i])<<8);
783 printf("SWAP value (16 bits) not allowed : %d\n", swap);
793 for(i=0;i<lgr/4;i++) {
794 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 4321 */
795 fort =((unsigned long int *)im)[i]>>16;
796 fort= (fort>>8) | (fort<<8);
797 faible=(faible>>8) | (faible<<8);
799 ((unsigned long int *)im)[i]=(s32<<16)|fort;
804 for(i=0;i<lgr/4;i++) {
805 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 2143 */
806 fort=((unsigned long int *)im)[i]>>16;
807 fort= (fort>>8) | (fort<<8);
808 faible=(faible>>8) | (faible<<8);
810 ((unsigned long int *)im)[i]=(s32<<16)|faible;
815 for(i=0;i<lgr/4;i++) {
816 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 3412 */
817 fort=((unsigned long int *)im)[i]>>16;
819 ((unsigned long int *)im)[i]=(s32<<16)|fort;
824 std::cout << "SWAP value (32 bits) not allowed : " << swap << std::endl;
830 * \brief Read pixel data from disk (optionaly decompressing) into the
831 * caller specified memory location.
832 * @param destination where the pixel data should be stored.
835 bool gdcmFile::ReadPixelData(void *destination) {
839 if ( !(fp=Header->OpenFile()))
841 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
845 // ---------------------- Compacted File (12 Bits Per Pixel)
846 /* unpack 12 Bits pixels into 16 Bits pixels */
847 /* 2 pixels 12bit = [0xABCDEF] */
848 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
850 if (Header->GetBitsAllocated()==12) {
851 int nbPixels = Header->GetXSize() * Header->GetYSize();
852 unsigned char b0, b1, b2;
854 unsigned short int *pdestination = (unsigned short int*)destination;
855 for(int p=0;p<nbPixels;p+=2) {
859 //Two steps is necessary to please VC++
860 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
861 /* A */ /* B */ /* D */
862 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
863 /* F */ /* C */ /* E */
865 // Troubles expected on Big-Endian processors ?
872 // ---------------------- Uncompressed File
873 if ( !Header->IsDicomV3() ||
874 Header->IsImplicitVRLittleEndianTransferSyntax() ||
875 Header->IsExplicitVRLittleEndianTransferSyntax() ||
876 Header->IsExplicitVRBigEndianTransferSyntax() ||
877 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
879 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
880 if ( ItemRead != 1 ) {
889 // ---------------------- Run Length Encoding
890 if (Header->IsRLELossLessTransferSyntax()) {
891 bool res = (bool)gdcm_read_RLE_file (fp,destination);
896 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
898 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
899 if (str_nb == GDCM_UNFOUND ) {
902 nb = atoi(str_nb.c_str() );
903 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
908 int taille = Header->GetXSize() * Header->GetYSize()
909 * Header->GetSamplesPerPixel();
910 long fragmentBegining; // for ftell, fseek
912 bool jpg2000 = Header->IsJPEG2000();
913 bool jpgLossless = Header->IsJPEGLossless();
916 guint16 ItemTagGr,ItemTagEl;
919 // Position on begining of Jpeg Pixels
921 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
922 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
923 if(Header->GetSwapCode()) {
924 ItemTagGr=Header->SwapShort(ItemTagGr);
925 ItemTagEl=Header->SwapShort(ItemTagEl);
928 if(Header->GetSwapCode())
929 ln=Header->SwapLong(ln); // Basic Offset Table Item length
932 // What is it used for ?!?
933 char *BasicOffsetTableItemValue = new char[ln+1];
934 fread(BasicOffsetTableItemValue,ln,1,fp);
937 // first Fragment initialisation
938 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
939 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
940 if(Header->GetSwapCode()) {
941 ItemTagGr=Header->SwapShort(ItemTagGr);
942 ItemTagEl=Header->SwapShort(ItemTagEl);
945 // parsing fragments until Sequence Delim. Tag found
946 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
947 // --- for each Fragment
950 if(Header->GetSwapCode())
951 ln=Header->SwapLong(ln); // Fragment Item length
953 fragmentBegining=ftell(fp);
955 if (jpg2000) { // JPEG 2000 : call to ???
957 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
959 } // ------------------------------------- endif (JPEG2000)
961 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
963 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
964 (unsigned short *)destination,
965 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(),
967 res=1; // in order not to break the loop
969 } // ------------------------------------- endif (JPEGLossless)
971 else { // JPEG Lossy : call to IJG 6b
973 if (Header->GetBitsStored() == 8) {
974 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
976 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
978 } // ------------------------------------- endif (JPEGLossy)
982 destination = (char *)destination + taille * nBytes; // location in user's memory
983 // for next fragment (if any)
985 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
986 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
988 ItemTagGr = ItemTagEl =0;
989 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
990 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
991 if(Header->GetSwapCode()) {
992 ItemTagGr=Header->SwapShort(ItemTagGr);
993 ItemTagEl=Header->SwapShort(ItemTagEl);
996 } // endWhile parsing fragments until Sequence Delim. Tag found
1001 //-----------------------------------------------------------------------------