1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/06/21 04:52:08 $
7 Version: $Revision: 1.104 $
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 //-----------------------------------------------------------------------------
107 * \brief returns the gdcmHeader *Header
110 gdcmHeader *gdcmFile::GetHeader(void) {
116 * \brief computes the length (in bytes) to ALLOCATE to receive the
117 * image(s) pixels (multiframes taken into account)
118 * \warning : it is NOT the group 7FE0 length
119 * (no interest for compressed images).
120 * @return length to allocate
122 void gdcmFile::SetPixelDataSizeFromHeader(void) {
123 // see PS 3.3-2003 : C.7.6.3.2.1
133 // YBR_FULL_422 (no LUT, no Palette)
139 // ex : gdcm-US-ALOKA-16.dcm
140 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
141 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
142 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
144 // ex : OT-PAL-8-face.dcm
145 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
146 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
147 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
151 str_nb=Header->GetEntryByNumber(0x0028,0x0100);
152 if (str_nb == GDCM_UNFOUND ) {
155 nb = atoi(str_nb.c_str() );
156 if (nb == 12) nb =16;
158 lgrTotale = lgrTotaleRaw = Header->GetXSize() * Header->GetYSize()
159 * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
160 std::string str_PhotometricInterpretation =
161 Header->GetEntryByNumber(0x0028,0x0004);
163 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
164 // pb when undealt Segmented Palette Color
166 if (Header->HasLUT()) {
173 * \brief Returns the size (in bytes) of required memory to hold
174 * the pixel data represented in this file.
175 * @return The size of pixel data in bytes.
177 size_t gdcmFile::GetImageDataSize(void) {
183 * \brief Returns the size (in bytes) of required memory to hold
184 * the pixel data represented in this file, when user DOESN'T want
185 * to get RGB pixels image when it's stored as a PALETTE COLOR image
186 * -the (vtk) user is supposed to know how deal with LUTs-
187 * \warning to be used with GetImagePixelsRaw()
188 * @return The size of pixel data in bytes.
190 size_t gdcmFile::GetImageDataSizeRaw(void) {
191 return (lgrTotaleRaw);
196 * \brief Allocates necessary memory, copies the pixel data
197 * (image[s]/volume[s]) to newly allocated zone.
198 * Transforms YBR pixels into RGB pixels if any
199 * Transforms 3 planes R, G, B into a single RGB Plane
200 * Transforms single Grey plane + 3 Palettes into a RGB Plane
201 * @return Pointer to newly allocated pixel data.
202 * NULL if alloc fails
204 void * gdcmFile::GetImageData (void) {
205 PixelData = new char[lgrTotale];
207 GetImageDataIntoVector(PixelData, lgrTotale);
208 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
209 GetHeader()->GetGrPixel(),
210 GetHeader()->GetNumPixel());
212 PixelRead=0; // no PixelRaw
219 * \brief Copies at most MaxSize bytes of pixel data to caller's
221 * \warning This function was designed to avoid people that want to build
222 * a volume from an image stack to need first to get the image pixels
223 * and then move them to the volume area.
224 * It's absolutely useless for any VTK user since vtk chooses
225 * to invert the lines of an image, that is the last line comes first
226 * (for some axis related reasons?). Hence he will have
227 * to load the image line by line, starting from the end.
228 * VTK users have to call GetImageData
230 * @param destination Address (in caller's memory space) at which the
231 * pixel data should be copied
232 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
233 * is not sufficient to hold the pixel data the copy is not
234 * executed (i.e. no partial copy).
235 * @return On success, the number of bytes actually copied. Zero on
236 * failure e.g. MaxSize is lower than necessary.
238 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
239 //size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
240 GetImageDataIntoVectorRaw (destination, MaxSize);
241 PixelRead=0 ; // no PixelRaw
242 if (!Header->HasLUT())
245 // from Lut R + Lut G + Lut B
246 unsigned char *newDest = new unsigned char[lgrTotale];
247 unsigned char *a = (unsigned char *)destination;
248 unsigned char *lutRGBA = Header->GetLUTRGBA();
250 int l = lgrTotaleRaw;
251 memmove(newDest, destination, l);// move Gray pixels to temp area
253 for (int i=0;i<l; i++) { // Build RGB Pixels
261 // now, it's an RGB image
262 // Lets's write it in the Header
264 // CreateOrReplaceIfExist ?
266 std::string spp = "3"; // Samples Per Pixel
267 Header->SetEntryByNumber(spp,0x0028,0x0002);
268 std::string rgb= "RGB "; // Photometric Interpretation
269 Header->SetEntryByNumber(rgb,0x0028,0x0004);
270 std::string planConfig = "0"; // Planar Configuration
271 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
274 // need to make RGB Pixels (?)
275 // from grey Pixels (?!)
276 // and Gray Lut (!?!)
277 // or Segmented xxx Palette Color Lookup Table Data and so on
279 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
280 // No idea how to manage such an image
281 // It seems that *no Dicom Viewer* has any idea :-(
282 // Segmented xxx Palette Color are *more* than 65535 long ?!?
284 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
285 Header->SetEntryByNumber(rgb,0x0028,0x0004);
287 /// \todo Drop Palette Color out of the Header?
293 * \brief Allocates necessary memory, copies the pixel data
294 * (image[s]/volume[s]) to newly allocated zone.
295 * Transforms YBR pixels into RGB pixels if any
296 * Transforms 3 planes R, G, B into a single RGB Plane
297 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
298 * @return Pointer to newly allocated pixel data.
299 * \ NULL if alloc fails
301 void * gdcmFile::GetImageDataRaw (void) {
302 if (Header->HasLUT())
303 /// \todo Let gdcmHeadar user a chance to get the right value
304 /// Create a member lgrTotaleRaw ???
306 PixelData = new char[lgrTotale];
309 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
310 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
311 GetHeader()->GetGrPixel(),
312 GetHeader()->GetNumPixel());
314 PixelRead=1; // PixelRaw
320 * \brief Copies at most MaxSize bytes of pixel data to caller's
322 * \warning This function was designed to avoid people that want to build
323 * a volume from an image stack to need first to get the image pixels
324 * and then move them to the volume area.
325 * It's absolutely useless for any VTK user since vtk chooses
326 * to invert the lines of an image, that is the last line comes first
327 * (for some axis related reasons?). Hence he will have
328 * to load the image line by line, starting from the end.
329 * VTK users hace to call GetImageData
330 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
331 * into a single RGB Pixels Plane
332 * the (VTK) user will manage the palettes
334 * @param destination Address (in caller's memory space) at which the
335 * pixel data should be copied
336 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
337 * is not sufficient to hold the pixel data the copy is not
338 * executed (i.e. no partial copy).
339 * @return On success, the number of bytes actually copied. Zero on
340 * failure e.g. MaxSize is lower than necessary.
342 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
344 int nb, nbu, highBit, signe;
345 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
346 PixelRead=1 ; // PixelRaw
348 if ( lgrTotale > MaxSize ) {
349 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
350 "than caller's expected MaxSize");
354 (void)ReadPixelData(destination);
356 // Number of Bits Allocated for storing a Pixel
357 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
358 if (str_nb == GDCM_UNFOUND ) {
361 nb = atoi(str_nb.c_str() );
363 // Number of Bits actually used
364 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
365 if (str_nbu == GDCM_UNFOUND ) {
368 nbu = atoi(str_nbu.c_str() );
371 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
372 if (str_highBit == GDCM_UNFOUND ) {
375 highBit = atoi(str_highBit.c_str() );
380 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
381 if (str_signe == GDCM_UNFOUND ) {
382 signe = 0; // default is unsigned
384 signe = atoi(str_signe.c_str() );
387 // re arange bytes inside the integer (processor endianity)
389 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
391 // to avoid pb with some xmedcon breakers images
392 if (nb==16 && nbu<nb && signe==0) {
393 int l = (int)lgrTotale / (nb/8);
394 guint16 *deb = (guint16 *)destination;
395 for(int i = 0; i<l; i++) {
401 // re arange bits inside the bytes
403 int l = (int)lgrTotale / (nb/8);
405 guint16 mask = 0xffff;
406 mask = mask >> (nb-nbu);
407 guint16 *deb = (guint16 *)destination;
408 for(int i = 0; i<l; i++) {
409 *deb = (*deb >> (nbu-highBit-1)) & mask;
412 } else if (nb == 32 ) {
413 guint32 mask = 0xffffffff;
414 mask = mask >> (nb-nbu);
415 guint32 *deb = (guint32 *)destination;
416 for(int i = 0; i<l; i++) {
417 *deb = (*deb >> (nbu-highBit-1)) & mask;
421 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
425 // DO NOT remove this commented out code .
426 // Nobody knows what's expecting you ...
427 // Just to 'see' what was actually read on disk :-(
430 // f2 = fopen("SpuriousFile.RAW","wb");
431 // fwrite(destination,lgrTotale,1,f2);
434 // Deal with the color
435 // -------------------
437 std::string str_PhotometricInterpretation =
438 Header->GetEntryByNumber(0x0028,0x0004);
440 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
441 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
445 // Planar configuration = 0 : Pixels are already RGB
446 // Planar configuration = 1 : 3 planes : R, G, B
447 // Planar configuration = 2 : 1 gray Plane + 3 LUT
449 // Well ... supposed to be !
450 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
451 // PhotometricInterpretation=PALETTE COLOR
452 // and heuristic has to be found :-(
454 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
456 // Whatever Planar Configuration is,
457 // "PALETTE COLOR " implies that we deal with the palette.
458 if (str_PhotometricInterpretation == "PALETTE COLOR ")
463 // Pixels are already RGB
469 if (str_PhotometricInterpretation == "YBR_FULL") {
471 // Warning : YBR_FULL_422 acts as RGB
472 // : we need to make RGB Pixels from Planes Y,cB,cR
474 // to see the tricks about YBR_FULL, YBR_FULL_422,
475 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
476 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
477 // and be *very* affraid
479 int l = Header->GetXSize()*Header->GetYSize();
480 int nbFrames = Header->GetZSize();
482 unsigned char *newDest = new unsigned char[lgrTotale];
483 unsigned char *x = newDest;
484 unsigned char *a = (unsigned char *)destination;
485 unsigned char *b = a + l;
486 unsigned char *c = b + l;
489 /// \todo : Replace by the 'well known' integer computation
491 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
492 /// for code optimisation
494 for (int i=0;i<nbFrames;i++) {
495 for (int j=0;j<l; j++) {
496 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
497 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
498 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
503 if (R>255.0) R=255.0;
504 if (G>255.0) G=255.0;
505 if (B>255.0) B=255.0;
507 *(x++) = (unsigned char)R;
508 *(x++) = (unsigned char)G;
509 *(x++) = (unsigned char)B;
513 memmove(destination,newDest,lgrTotale);
518 // need to make RGB Pixels from R,G,B Planes
519 // (all the Frames at a time)
521 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
523 char *newDest = new char[lgrTotale];
525 char *a = (char *)destination;
529 for (int j=0;j<l; j++) {
534 memmove(destination,newDest,lgrTotale);
540 // Palettes were found
541 // Let the user deal with them !
544 // now, it's an RGB image
545 // Lets's write it in the Header
547 // CreateOrReplaceIfExist ?
549 std::string spp = "3"; // Samples Per Pixel
550 Header->SetEntryByNumber(spp,0x0028,0x0002);
551 std::string rgb="RGB "; // Photometric Interpretation
552 Header->SetEntryByNumber(rgb,0x0028,0x0004);
554 std::string planConfig = "0"; // Planar Configuration
555 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
557 /// \todo Drop Palette Color out of the Header?
563 * \brief performs a shadow copy (not a deep copy) of the user given
565 * 'image' Pixels are presented as C-like 2D arrays : line per line.
566 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
567 * \warning user is kindly requested NOT TO 'free' the Pixel area
568 * @param inData user supplied pixel area
569 * @param ExpectedSize total image size, in Bytes
573 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
574 Header->SetImageDataSize(ExpectedSize);
576 lgrTotale = ExpectedSize;
583 * \brief Writes on disk A SINGLE Dicom file
584 * NO test is performed on processor "Endiannity".
585 * It's up to the user to call his Reader properly
586 * @param fileName name of the file to be created
587 * (any already existing file is over written)
588 * @return false if write fails
591 bool gdcmFile::WriteRawData (std::string fileName) {
593 fp1 = fopen(fileName.c_str(),"wb");
595 printf("Fail to open (write) file [%s] \n",fileName.c_str());
598 fwrite (PixelData,lgrTotale, 1, fp1);
605 * \brief Writes on disk A SINGLE Dicom file,
606 * using the Implicit Value Representation convention
607 * NO test is performed on processor "Endiannity".
608 * @param fileName name of the file to be created
609 * (any already existing file is overwritten)
610 * @return false if write fails
613 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
614 return WriteBase(fileName, gdcmImplicitVR);
619 * \brief Writes on disk A SINGLE Dicom file,
620 * using the Implicit Value Representation convention
621 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
622 * (any already existing file is overwritten)
623 * @return false if write fails
626 bool gdcmFile::WriteDcmImplVR (const char *fileName) {
627 return WriteDcmImplVR (std::string (fileName));
632 * \brief Writes on disk A SINGLE Dicom file,
633 * using the Explicit Value Representation convention
634 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
635 * (any already existing file is overwritten)
636 * @return false if write fails
639 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
640 return WriteBase(fileName, gdcmExplicitVR);
645 * \brief Writes on disk A SINGLE Dicom file,
646 * using the ACR-NEMA convention
647 * NO test is performed on processor "Endiannity".
648 * (a l'attention des logiciels cliniques
649 * qui ne prennent en entrée QUE des images ACR ...
650 * \warning if a DICOM_V3 header is supplied,
651 * groups < 0x0008 and shadow groups are ignored
652 * \warning NO TEST is performed on processor "Endiannity".
653 * @param fileName name of the file to be created
654 * (any already existing file is overwritten)
655 * @return false if write fails
658 bool gdcmFile::WriteAcr (std::string fileName) {
659 return WriteBase(fileName, gdcmACR);
662 //-----------------------------------------------------------------------------
666 * \brief NOT a end user inteded function
667 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
668 * @param fileName name of the file to be created
669 * (any already existing file is overwritten)
670 * @param type file type (ExplicitVR, ImplicitVR, ...)
671 * @return false if write fails
673 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
677 if (PixelRead==-1 && type != gdcmExplicitVR) {
681 fp1 = fopen(fileName.c_str(),"wb");
683 printf("Failed to open (write) File [%s] \n",fileName.c_str());
687 if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
689 // writing Dicom File Preamble
690 filePreamble=new char[128];
691 memset(filePreamble,0,128);
692 fwrite(filePreamble,128,1,fp1);
693 fwrite("DICM",4,1,fp1);
694 delete[] filePreamble;
697 // --------------------------------------------------------------
698 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
700 // if recognition code tells us we dealt with a LibIDO image
701 // we reproduce on disk the switch between lineNumber and columnNumber
702 // just before writting ...
704 /// \todo the best trick would be *change* the recognition code
705 /// but pb expected if user deals with, e.g. COMPLEX images
707 std::string rows, columns;
708 if ( Header->GetFileType() == gdcmACR_LIBIDO){
709 rows = Header->GetEntryByNumber(0x0028, 0x0010);
710 columns = Header->GetEntryByNumber(0x0028, 0x0011);
711 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
712 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
714 // ----------------- End of Special Patch ----------------
716 /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
718 guint16 grPixel =Header->GetGrPixel();
719 guint16 numPixel=Header->GetNumPixel();;
721 // Update Pixel Data Length
722 // the *last* of the (GrPixel, NumPixel), if many.
724 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
725 TagDocEntryHT::iterator p2;
726 gdcmDocEntry *PixelElement;
728 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
730 if (Header->GetEntry().count(key) == 1) // only the first is significant
731 p2=it.first; // iterator on the first (unique) synonym
733 p2=it.second;// iterator on the last synonym
735 PixelElement=p2->second; // H Table target column (2-nd col)
736 // PixelElement->SetPrintLevel(2);
737 // PixelElement->Print();
740 PixelElement->SetLength(lgrTotaleRaw);
741 else if (PixelRead==0)
742 PixelElement->SetLength(lgrTotale);
744 //PixelElement->SetPrintLevel(2);
745 //PixelElement->Print();
746 Header->Write(fp1, type);
748 // --------------------------------------------------------------
749 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
751 // ...and we restore the Header to be Dicom Compliant again
752 // just after writting
754 if (Header->GetFileType() == gdcmACR_LIBIDO){
755 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
756 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
758 // ----------------- End of Special Patch ----------------
760 // fwrite(PixelData, lgrTotale, 1, fp1); // should be useless, now
765 //-----------------------------------------------------------------------------
769 * \brief Swap the bytes, according to swap code.
770 * \warning not end user intended
771 * @param im area to deal with
772 * @param swap swap code
773 * @param lgr Area Length
774 * @param nb Pixels Bit number
776 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
793 for(i=0;i<lgr/2;i++) {
794 ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
795 | ((((unsigned short int *)im)[i])<<8);
800 printf("SWAP value (16 bits) not allowed : %d\n", swap);
810 for(i=0;i<lgr/4;i++) {
811 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 4321 */
812 fort =((unsigned long int *)im)[i]>>16;
813 fort= (fort>>8) | (fort<<8);
814 faible=(faible>>8) | (faible<<8);
816 ((unsigned long int *)im)[i]=(s32<<16)|fort;
821 for(i=0;i<lgr/4;i++) {
822 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 2143 */
823 fort=((unsigned long int *)im)[i]>>16;
824 fort= (fort>>8) | (fort<<8);
825 faible=(faible>>8) | (faible<<8);
827 ((unsigned long int *)im)[i]=(s32<<16)|faible;
832 for(i=0;i<lgr/4;i++) {
833 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 3412 */
834 fort=((unsigned long int *)im)[i]>>16;
836 ((unsigned long int *)im)[i]=(s32<<16)|fort;
841 printf("SWAP value (32 bits) not allowed : %d\n", swap);
848 * \brief Read pixel data from disk (optionaly decompressing) into the
849 * caller specified memory location.
850 * @param destination where the pixel data should be stored.
853 bool gdcmFile::ReadPixelData(void *destination) {
857 if ( !(fp=Header->OpenFile()))
859 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
863 // ---------------------- Compacted File (12 Bits Per Pixel)
864 /* unpack 12 Bits pixels into 16 Bits pixels */
865 /* 2 pixels 12bit = [0xABCDEF] */
866 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
868 if (Header->GetBitsAllocated()==12) {
869 int nbPixels = Header->GetXSize() * Header->GetYSize();
870 unsigned char b0, b1, b2;
872 unsigned short int *pdestination = (unsigned short int*)destination;
873 for(int p=0;p<nbPixels;p+=2) {
877 //Two steps is necessary to please VC++
878 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
879 /* A */ /* B */ /* D */
880 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
881 /* F */ /* C */ /* E */
883 // Troubles expected on Big-Endian processors ?
890 // ---------------------- Uncompressed File
891 if ( !Header->IsDicomV3() ||
892 Header->IsImplicitVRLittleEndianTransferSyntax() ||
893 Header->IsExplicitVRLittleEndianTransferSyntax() ||
894 Header->IsExplicitVRBigEndianTransferSyntax() ||
895 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
897 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
898 if ( ItemRead != 1 ) {
907 // ---------------------- Run Length Encoding
908 if (Header->IsRLELossLessTransferSyntax()) {
909 bool res = (bool)gdcm_read_RLE_file (fp,destination);
914 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
916 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
917 if (str_nb == GDCM_UNFOUND ) {
920 nb = atoi(str_nb.c_str() );
921 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
926 int taille = Header->GetXSize() * Header->GetYSize()
927 * Header->GetSamplesPerPixel();
928 long fragmentBegining; // for ftell, fseek
930 bool jpg2000 = Header->IsJPEG2000();
931 bool jpgLossless = Header->IsJPEGLossless();
934 guint16 ItemTagGr,ItemTagEl;
937 // Position on begining of Jpeg Pixels
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 if(Header->GetSwapCode())
947 ln=Header->SwapLong(ln); // Basic Offset Table Item length
950 // What is it used for ?!?
951 char *BasicOffsetTableItemValue = new char[ln+1];
952 fread(BasicOffsetTableItemValue,ln,1,fp);
955 // first Fragment initialisation
956 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
957 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
958 if(Header->GetSwapCode()) {
959 ItemTagGr=Header->SwapShort(ItemTagGr);
960 ItemTagEl=Header->SwapShort(ItemTagEl);
963 // parsing fragments until Sequence Delim. Tag found
964 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
965 // --- for each Fragment
968 if(Header->GetSwapCode())
969 ln=Header->SwapLong(ln); // Fragment Item length
971 fragmentBegining=ftell(fp);
973 if (jpg2000) { // JPEG 2000 : call to ???
975 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
977 } // ------------------------------------- endif (JPEG2000)
979 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
981 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
982 (unsigned short *)destination,
983 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(),
985 res=1; // in order not to break the loop
987 } // ------------------------------------- endif (JPEGLossless)
989 else { // JPEG Lossy : call to IJG 6b
991 if (Header->GetBitsStored() == 8) {
992 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
994 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
996 } // ------------------------------------- endif (JPEGLossy)
1000 destination = (char *)destination + taille * nBytes; // location in user's memory
1001 // for next fragment (if any)
1003 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
1004 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1006 ItemTagGr = ItemTagEl =0;
1007 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1008 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1009 if(Header->GetSwapCode()) {
1010 ItemTagGr=Header->SwapShort(ItemTagGr);
1011 ItemTagEl=Header->SwapShort(ItemTagEl);
1014 } // endWhile parsing fragments until Sequence Delim. Tag found
1016 Header->CloseFile();
1019 //-----------------------------------------------------------------------------