1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/06/23 16:22:21 $
7 Version: $Revision: 1.109 $
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();
243 int l = lgrTotaleRaw;
244 memmove(newDest, destination, l);// move Gray pixels to temp area
246 for (int i=0;i<l; i++) { // Build RGB Pixels
254 // now, it's an RGB image
255 // Lets's write it in the Header
257 // CreateOrReplaceIfExist ?
259 std::string spp = "3"; // Samples Per Pixel
260 Header->SetEntryByNumber(spp,0x0028,0x0002);
261 std::string rgb= "RGB "; // Photometric Interpretation
262 Header->SetEntryByNumber(rgb,0x0028,0x0004);
263 std::string planConfig = "0"; // Planar Configuration
264 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
267 // need to make RGB Pixels (?)
268 // from grey Pixels (?!)
269 // and Gray Lut (!?!)
270 // or Segmented xxx Palette Color Lookup Table Data and so on
272 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
273 // No idea how to manage such an image
274 // It seems that *no Dicom Viewer* has any idea :-(
275 // Segmented xxx Palette Color are *more* than 65535 long ?!?
277 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
278 Header->SetEntryByNumber(rgb,0x0028,0x0004);
280 /// \todo Drop Palette Color out of the Header?
286 * \brief Allocates necessary memory, copies the pixel data
287 * (image[s]/volume[s]) to newly allocated zone.
288 * Transforms YBR pixels into RGB pixels if any
289 * Transforms 3 planes R, G, B into a single RGB Plane
290 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
291 * @return Pointer to newly allocated pixel data.
292 * \ NULL if alloc fails
294 void * gdcmFile::GetImageDataRaw () {
295 if (Header->HasLUT())
296 /// \todo Let gdcmHeadar user a chance to get the right value
297 /// Create a member lgrTotaleRaw ???
299 PixelData = new unsigned char[lgrTotale];
302 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
303 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
304 GetHeader()->GetGrPixel(),
305 GetHeader()->GetNumPixel());
307 PixelRead=1; // PixelRaw
314 * \brief Copies at most MaxSize bytes of pixel data to caller's
316 * \warning This function was designed to avoid people that want to build
317 * a volume from an image stack to need first to get the image pixels
318 * and then move them to the volume area.
319 * It's absolutely useless for any VTK user since vtk chooses
320 * to invert the lines of an image, that is the last line comes first
321 * (for some axis related reasons?). Hence he will have
322 * to load the image line by line, starting from the end.
323 * VTK users hace to call GetImageData
324 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
325 * into a single RGB Pixels Plane
326 * the (VTK) user will manage the palettes
328 * @param destination Address (in caller's memory space) at which the
329 * pixel data should be copied
330 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
331 * is not sufficient to hold the pixel data the copy is not
332 * executed (i.e. no partial copy).
333 * @return On success, the number of bytes actually copied. Zero on
334 * failure e.g. MaxSize is lower than necessary.
336 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
338 int nb, nbu, highBit, signe;
339 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
340 PixelRead=1 ; // PixelRaw
342 if ( lgrTotale > MaxSize ) {
343 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
344 "than caller's expected MaxSize");
348 ReadPixelData(destination);
350 // Number of Bits Allocated for storing a Pixel
351 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
352 if (str_nb == GDCM_UNFOUND ) {
355 nb = atoi(str_nb.c_str() );
357 // Number of Bits actually used
358 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
359 if (str_nbu == GDCM_UNFOUND ) {
362 nbu = atoi(str_nbu.c_str() );
365 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
366 if (str_highBit == GDCM_UNFOUND ) {
369 highBit = atoi(str_highBit.c_str() );
374 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
375 if (str_signe == GDCM_UNFOUND ) {
376 signe = 0; // default is unsigned
378 signe = atoi(str_signe.c_str() );
381 // re arange bytes inside the integer (processor endianity)
383 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
385 // to avoid pb with some xmedcon breakers images
386 if (nb==16 && nbu<nb && signe==0) {
387 int l = (int)lgrTotale / (nb/8);
388 guint16 *deb = (guint16 *)destination;
389 for(int i = 0; i<l; i++) {
395 // re arange bits inside the bytes
397 int l = (int)lgrTotale / (nb/8);
399 guint16 mask = 0xffff;
400 mask = mask >> (nb-nbu);
401 guint16 *deb = (guint16 *)destination;
402 for(int i = 0; i<l; i++) {
403 *deb = (*deb >> (nbu-highBit-1)) & mask;
406 } else if (nb == 32 ) {
407 guint32 mask = 0xffffffff;
408 mask = mask >> (nb-nbu);
409 guint32 *deb = (guint32 *)destination;
410 for(int i = 0; i<l; i++) {
411 *deb = (*deb >> (nbu-highBit-1)) & mask;
415 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
419 // DO NOT remove this commented out code .
420 // Nobody knows what's expecting you ...
421 // Just to 'see' what was actually read on disk :-(
424 // f2 = fopen("SpuriousFile.RAW","wb");
425 // fwrite(destination,lgrTotale,1,f2);
428 // Deal with the color
429 // -------------------
431 std::string str_PhotometricInterpretation =
432 Header->GetEntryByNumber(0x0028,0x0004);
434 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
435 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
439 // Planar configuration = 0 : Pixels are already RGB
440 // Planar configuration = 1 : 3 planes : R, G, B
441 // Planar configuration = 2 : 1 gray Plane + 3 LUT
443 // Well ... supposed to be !
444 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
445 // PhotometricInterpretation=PALETTE COLOR
446 // and heuristic has to be found :-(
448 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
450 // Whatever Planar Configuration is,
451 // "PALETTE COLOR " implies that we deal with the palette.
452 if (str_PhotometricInterpretation == "PALETTE COLOR ")
457 // Pixels are already RGB
463 if (str_PhotometricInterpretation == "YBR_FULL") {
465 // Warning : YBR_FULL_422 acts as RGB
466 // : we need to make RGB Pixels from Planes Y,cB,cR
468 // to see the tricks about YBR_FULL, YBR_FULL_422,
469 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
470 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
471 // and be *very* affraid
473 int l = Header->GetXSize()*Header->GetYSize();
474 int nbFrames = Header->GetZSize();
476 unsigned char *newDest = new unsigned char[lgrTotale];
477 unsigned char *x = newDest;
478 unsigned char *a = (unsigned char *)destination;
479 unsigned char *b = a + l;
480 unsigned char *c = b + l;
483 /// \todo : Replace by the 'well known' integer computation
485 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
486 /// for code optimisation
488 for (int i=0;i<nbFrames;i++) {
489 for (int j=0;j<l; j++) {
490 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
491 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
492 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
497 if (R>255.0) R=255.0;
498 if (G>255.0) G=255.0;
499 if (B>255.0) B=255.0;
501 *(x++) = (unsigned char)R;
502 *(x++) = (unsigned char)G;
503 *(x++) = (unsigned char)B;
507 memmove(destination,newDest,lgrTotale);
512 // need to make RGB Pixels from R,G,B Planes
513 // (all the Frames at a time)
515 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
517 char *newDest = new char[lgrTotale];
519 char *a = (char *)destination;
523 for (int j=0;j<l; j++) {
528 memmove(destination,newDest,lgrTotale);
534 // Palettes were found
535 // Let the user deal with them !
538 // now, it's an RGB image
539 // Lets's write it in the Header
541 // CreateOrReplaceIfExist ?
543 std::string spp = "3"; // Samples Per Pixel
544 Header->SetEntryByNumber(spp,0x0028,0x0002);
545 std::string rgb="RGB "; // Photometric Interpretation
546 Header->SetEntryByNumber(rgb,0x0028,0x0004);
548 std::string planConfig = "0"; // Planar Configuration
549 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
551 /// \todo Drop Palette Color out of the Header?
557 * \brief performs a shalow copy (not a deep copy) of the user given
559 * 'image' Pixels are presented as C-like 2D arrays : line per line.
560 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
561 * \warning user is kindly requested NOT TO 'free' the Pixel area
562 * @param inData user supplied pixel area
563 * @param ExpectedSize total image size, in Bytes
567 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
568 Header->SetImageDataSize(ExpectedSize);
570 lgrTotale = ExpectedSize;
578 * \brief Writes on disk A SINGLE Dicom file
579 * NO test is performed on processor "Endiannity".
580 * It's up to the user to call his Reader properly
581 * @param fileName name of the file to be created
582 * (any already existing file is over written)
583 * @return false if write fails
586 bool gdcmFile::WriteRawData (std::string const & fileName) {
588 fp1 = fopen(fileName.c_str(),"wb");
590 printf("Fail to open (write) file [%s] \n",fileName.c_str());
593 fwrite (PixelData,lgrTotale, 1, fp1);
601 * \brief Writes on disk A SINGLE Dicom file,
602 * using the Implicit Value Representation convention
603 * NO test is performed on processor "Endiannity".
604 * @param fileName name of the file to be created
605 * (any already existing file is overwritten)
606 * @return false if write fails
609 bool gdcmFile::WriteDcmImplVR (std::string const & fileName) {
610 return WriteBase(fileName, gdcmImplicitVR);
615 * \brief Writes on disk A SINGLE Dicom file,
616 * using the Explicit Value Representation convention
617 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
618 * (any already existing file is overwritten)
619 * @return false if write fails
622 bool gdcmFile::WriteDcmExplVR (std::string const & fileName) {
623 return WriteBase(fileName, gdcmExplicitVR);
628 * \brief Writes on disk A SINGLE Dicom file,
629 * using the ACR-NEMA convention
630 * NO test is performed on processor "Endiannity".
631 * (a l'attention des logiciels cliniques
632 * qui ne prennent en entrée QUE des images ACR ...
633 * \warning if a DICOM_V3 header is supplied,
634 * groups < 0x0008 and shadow groups are ignored
635 * \warning NO TEST is performed on processor "Endiannity".
636 * @param fileName name of the file to be created
637 * (any already existing file is overwritten)
638 * @return false if write fails
641 bool gdcmFile::WriteAcr (std::string const & fileName) {
642 return WriteBase(fileName, gdcmACR);
645 //-----------------------------------------------------------------------------
649 * \brief NOT a end user inteded function
650 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
651 * @param fileName name of the file to be created
652 * (any already existing file is overwritten)
653 * @param type file type (ExplicitVR, ImplicitVR, ...)
654 * @return false if write fails
656 bool gdcmFile::WriteBase (std::string const & fileName, FileType type) {
660 if (PixelRead==-1 && type != gdcmExplicitVR) {
664 fp1 = fopen(fileName.c_str(),"wb");
666 printf("Failed to open (write) File [%s] \n",fileName.c_str());
670 if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
672 // writing Dicom File Preamble
673 filePreamble=new char[128];
674 memset(filePreamble,0,128);
675 fwrite(filePreamble,128,1,fp1);
676 fwrite("DICM",4,1,fp1);
677 delete[] filePreamble;
680 // --------------------------------------------------------------
681 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
683 // if recognition code tells us we dealt with a LibIDO image
684 // we reproduce on disk the switch between lineNumber and columnNumber
685 // just before writting ...
687 /// \todo the best trick would be *change* the recognition code
688 /// but pb expected if user deals with, e.g. COMPLEX images
690 std::string rows, columns;
691 if ( Header->GetFileType() == gdcmACR_LIBIDO){
692 rows = Header->GetEntryByNumber(0x0028, 0x0010);
693 columns = Header->GetEntryByNumber(0x0028, 0x0011);
694 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
695 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
697 // ----------------- End of Special Patch ----------------
699 /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
701 guint16 grPixel =Header->GetGrPixel();
702 guint16 numPixel=Header->GetNumPixel();;
704 // Update Pixel Data Length
705 // the *last* of the (GrPixel, NumPixel), if many.
707 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
708 TagDocEntryHT::iterator p2;
709 gdcmDocEntry *PixelElement;
711 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
713 if (Header->GetEntry().count(key) == 1) // only the first is significant
714 p2=it.first; // iterator on the first (unique) synonym
716 p2=it.second;// iterator on the last synonym
718 PixelElement=p2->second; // H Table target column (2-nd col)
719 // PixelElement->SetPrintLevel(2);
720 // PixelElement->Print();
723 PixelElement->SetLength(lgrTotaleRaw);
724 else if (PixelRead==0)
725 PixelElement->SetLength(lgrTotale);
727 //PixelElement->SetPrintLevel(2);
728 //PixelElement->Print();
729 Header->Write(fp1, type);
731 // --------------------------------------------------------------
732 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
734 // ...and we restore the Header to be Dicom Compliant again
735 // just after writting
737 if (Header->GetFileType() == gdcmACR_LIBIDO){
738 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
739 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
741 // ----------------- End of Special Patch ----------------
743 // fwrite(PixelData, lgrTotale, 1, fp1); // should be useless, now
749 //-----------------------------------------------------------------------------
753 * \brief Swap the bytes, according to swap code.
754 * \warning not end user intended
755 * @param im area to deal with
756 * @param swap swap code
757 * @param lgr Area Length
758 * @param nb Pixels Bit number
760 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
777 for(i=0;i<lgr/2;i++) {
778 ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
779 | ((((unsigned short int *)im)[i])<<8);
784 std::cout << "SWAP value (16 bits) not allowed :i" << swap << std::endl;
794 for(i=0;i<lgr/4;i++) {
795 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 4321 */
796 fort =((unsigned long int *)im)[i]>>16;
797 fort= (fort>>8) | (fort<<8);
798 faible=(faible>>8) | (faible<<8);
800 ((unsigned long int *)im)[i]=(s32<<16)|fort;
805 for(i=0;i<lgr/4;i++) {
806 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 2143 */
807 fort=((unsigned long int *)im)[i]>>16;
808 fort= (fort>>8) | (fort<<8);
809 faible=(faible>>8) | (faible<<8);
811 ((unsigned long int *)im)[i]=(s32<<16)|faible;
816 for(i=0;i<lgr/4;i++) {
817 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 3412 */
818 fort=((unsigned long int *)im)[i]>>16;
820 ((unsigned long int *)im)[i]=(s32<<16)|fort;
825 std::cout << "SWAP value (32 bits) not allowed : " << swap << std::endl;
831 * \brief Read pixel data from disk (optionaly decompressing) into the
832 * caller specified memory location.
833 * @param destination where the pixel data should be stored.
836 bool gdcmFile::ReadPixelData(void *destination) {
840 if ( !(fp=Header->OpenFile()))
842 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
846 // ---------------------- Compacted File (12 Bits Per Pixel)
847 /* unpack 12 Bits pixels into 16 Bits pixels */
848 /* 2 pixels 12bit = [0xABCDEF] */
849 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
851 if (Header->GetBitsAllocated()==12) {
852 int nbPixels = Header->GetXSize() * Header->GetYSize();
853 unsigned char b0, b1, b2;
855 unsigned short int *pdestination = (unsigned short int*)destination;
856 for(int p=0;p<nbPixels;p+=2) {
860 //Two steps is necessary to please VC++
861 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
862 /* A */ /* B */ /* D */
863 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
864 /* F */ /* C */ /* E */
866 // Troubles expected on Big-Endian processors ?
873 // ---------------------- Uncompressed File
874 if ( !Header->IsDicomV3() ||
875 Header->IsImplicitVRLittleEndianTransferSyntax() ||
876 Header->IsExplicitVRLittleEndianTransferSyntax() ||
877 Header->IsExplicitVRBigEndianTransferSyntax() ||
878 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
880 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
881 if ( ItemRead != 1 ) {
890 // ---------------------- Run Length Encoding
891 if (Header->IsRLELossLessTransferSyntax()) {
892 bool res = (bool)gdcm_read_RLE_file (fp,destination);
897 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
899 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
900 if (str_nb == GDCM_UNFOUND ) {
903 nb = atoi(str_nb.c_str() );
904 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
909 int taille = Header->GetXSize() * Header->GetYSize()
910 * Header->GetSamplesPerPixel();
911 long fragmentBegining; // for ftell, fseek
913 bool jpg2000 = Header->IsJPEG2000();
914 bool jpgLossless = Header->IsJPEGLossless();
917 guint16 ItemTagGr,ItemTagEl;
920 // Position on begining of Jpeg Pixels
922 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
923 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
924 if(Header->GetSwapCode()) {
925 ItemTagGr=Header->SwapShort(ItemTagGr);
926 ItemTagEl=Header->SwapShort(ItemTagEl);
929 if(Header->GetSwapCode())
930 ln=Header->SwapLong(ln); // Basic Offset Table Item length
933 // What is it used for ?!?
934 char *BasicOffsetTableItemValue = new char[ln+1];
935 fread(BasicOffsetTableItemValue,ln,1,fp);
938 // first Fragment initialisation
939 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
940 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
941 if(Header->GetSwapCode()) {
942 ItemTagGr=Header->SwapShort(ItemTagGr);
943 ItemTagEl=Header->SwapShort(ItemTagEl);
946 // parsing fragments until Sequence Delim. Tag found
947 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
948 // --- for each Fragment
951 if(Header->GetSwapCode())
952 ln=Header->SwapLong(ln); // Fragment Item length
954 fragmentBegining=ftell(fp);
956 if (jpg2000) { // JPEG 2000 : call to ???
958 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
960 } // ------------------------------------- endif (JPEG2000)
962 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 //-----------------------------------------------------------------------------