2 //-----------------------------------------------------------------------------
5 #include "jpeg/ljpg/jpegless.h"
7 typedef std::pair<TagHeaderEntryHT::iterator,TagHeaderEntryHT::iterator> IterHT;
9 //-----------------------------------------------------------------------------
10 // Constructor / Destructor
13 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
14 * file (see SetFileName, SetDcmTag and Write)
15 * Opens (in read only and when possible) an existing file and checks
16 * for DICOM compliance. Returns NULL on failure.
17 * \note the in-memory representation of all available tags found in
18 * the DICOM header is post-poned to first header information access.
19 * This avoid a double parsing of public part of the header when
20 * one sets an a posteriori shadow dictionary (efficiency can be
21 * seen as a side effect).
22 * @param header file to be opened for reading datas
25 gdcmFile::gdcmFile(gdcmHeader *header) {
28 PixelRead=-1; // no ImageData read yet.
30 if (Header->IsReadable())
31 SetPixelDataSizeFromHeader();
36 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
37 * file (see SetFileName, SetDcmTag and Write)
38 * Opens (in read only and when possible) an existing file and checks
39 * for DICOM compliance. Returns NULL on failure.
40 * \note the in-memory representation of all available tags found in
41 * the DICOM header is post-poned to first header information access.
42 * This avoid a double parsing of public part of the header when
43 * one sets an a posteriori shadow dictionary (efficiency can be
44 * seen as a side effect).
45 * @param filename file to be opened for parsing
47 gdcmFile::gdcmFile(std::string & filename,
48 bool exception_on_error,
49 bool enable_sequences,
51 Header=new gdcmHeader(filename.c_str(),
56 PixelRead=-1; // no ImageData read yet.
58 if (Header->IsReadable())
59 SetPixelDataSizeFromHeader();
64 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
65 * file (see SetFileName, SetDcmTag and Write)
66 * Opens (in read only and when possible) an existing file and checks
67 * for DICOM compliance. Returns NULL on failure.
68 * \note the in-memory representation of all available tags found in
69 * the DICOM header is post-poned to first header information access.
70 * This avoid a double parsing of public part of the header when
71 * one sets an a posteriori shadow dictionary (efficiency can be
72 * seen as a side effect).
73 * @param filename file to be opened for parsing
75 gdcmFile::gdcmFile(const char * filename,
76 bool exception_on_error,
77 bool enable_sequences,
79 Header=new gdcmHeader(filename,
84 PixelRead=-1; // no ImageData read yet.
86 if (Header->IsReadable())
87 SetPixelDataSizeFromHeader();
92 * \brief canonical destructor
93 * \note If the gdcmHeader is created by the gdcmFile, it is destroyed
96 gdcmFile::~gdcmFile(void) {
102 //-----------------------------------------------------------------------------
105 //-----------------------------------------------------------------------------
109 * \brief returns the gdcmHeader *Header
112 gdcmHeader *gdcmFile::GetHeader(void) {
118 * \brief computes the length (in bytes) to ALLOCATE to receive the
119 * image(s) pixels (multiframes taken into account)
120 * \warning : it is NOT the group 7FE0 length
121 * (no interest for compressed images).
122 * @return length to allocate
124 void gdcmFile::SetPixelDataSizeFromHeader(void) {
125 // see PS 3.3-2003 : C.7.6.3.2.1
135 // YBR_FULL_422 (no LUT, no Palette)
141 // ex : gdcm-US-ALOKA-16.dcm
142 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
143 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
144 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
146 // ex : OT-PAL-8-face.dcm
147 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
148 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
149 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
153 str_nb=Header->GetEntryByNumber(0x0028,0x0100);
154 if (str_nb == GDCM_UNFOUND ) {
157 nb = atoi(str_nb.c_str() );
158 if (nb == 12) nb =16;
160 lgrTotale = lgrTotaleRaw = Header->GetXSize() * Header->GetYSize()
161 * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
162 std::string str_PhotometricInterpretation =
163 Header->GetEntryByNumber(0x0028,0x0004);
165 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
166 // pb when undealt Segmented Palette Color
168 if (Header->HasLUT()) {
175 * \brief Returns the size (in bytes) of required memory to hold
176 * the pixel data represented in this file.
177 * @return The size of pixel data in bytes.
179 size_t gdcmFile::GetImageDataSize(void) {
185 * \brief Returns the size (in bytes) of required memory to hold
186 * the pixel data represented in this file, when user DOESN'T want
187 * to get RGB pixels image when it's stored as a PALETTE COLOR image
188 * -the (vtk) user is supposed to know how deal with LUTs-
189 * \warning to be used with GetImagePixelsRaw()
190 * @return The size of pixel data in bytes.
192 size_t gdcmFile::GetImageDataSizeRaw(void) {
193 return (lgrTotaleRaw);
198 * \brief Allocates necessary memory, copies the pixel data
199 * (image[s]/volume[s]) to newly allocated zone.
200 * Transforms YBR pixels into RGB pixels if any
201 * Transforms 3 planes R, G, B into a single RGB Plane
202 * Transforms single Grey plane + 3 Palettes into a RGB Plane
203 * @return Pointer to newly allocated pixel data.
204 * NULL if alloc fails
206 void * gdcmFile::GetImageData (void) {
207 PixelData = (void *) malloc(lgrTotale);
209 GetImageDataIntoVector(PixelData, lgrTotale);
211 PixelRead=0; // no PixelRaw
217 * \brief Copies at most MaxSize bytes of pixel data to caller's
219 * \warning This function was designed to avoid people that want to build
220 * a volume from an image stack to need first to get the image pixels
221 * and then move them to the volume area.
222 * It's absolutely useless for any VTK user since vtk chooses
223 * to invert the lines of an image, that is the last line comes first
224 * (for some axis related reasons?). Hence he will have
225 * to load the image line by line, starting from the end.
226 * VTK users have to call GetImageData
228 * @param destination Address (in caller's memory space) at which the
229 * pixel data should be copied
230 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
231 * is not sufficient to hold the pixel data the copy is not
232 * executed (i.e. no partial copy).
233 * @return On success, the number of bytes actually copied. Zero on
234 * failure e.g. MaxSize is lower than necessary.
236 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
237 size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
238 PixelRead=0 ; // no PixelRaw
239 if (!Header->HasLUT())
242 // from Lut R + Lut G + Lut B
243 unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
244 unsigned char * a = (unsigned char *)destination;
245 unsigned char * lutRGBA = Header->GetLUTRGBA();
247 int l = lgrTotaleRaw;
248 memmove(newDest, destination, l);// move Gray pixels to temp area
250 for (int i=0;i<l; i++) { // Build RGB Pixels
258 // now, it's an RGB image
259 // Lets's write it in the Header
261 // CreateOrReplaceIfExist ?
263 std::string spp = "3"; // Samples Per Pixel
264 Header->SetEntryByNumber(spp,0x0028,0x0002);
265 std::string rgb= "RGB "; // Photometric Interpretation
266 Header->SetEntryByNumber(rgb,0x0028,0x0004);
267 std::string planConfig = "0"; // Planar Configuration
268 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
271 // need to make RGB Pixels (?)
272 // from grey Pixels (?!)
273 // and Gray Lut (!?!)
274 // or Segmented xxx Palette Color Lookup Table Data and so on
276 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
277 // No idea how to manage such an image
278 // It seems that *no Dicom Viewer* has any idea :-(
279 // Segmented xxx Palette Color are *more* than 65535 long ?!?
281 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
282 Header->SetEntryByNumber(rgb,0x0028,0x0004);
284 // TODO : Drop Palette Color out of the Header?
290 * \brief Allocates necessary memory, copies the pixel data
291 * (image[s]/volume[s]) to newly allocated zone.
292 * Transforms YBR pixels into RGB pixels if any
293 * Transforms 3 planes R, G, B into a single RGB Plane
294 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
295 * @return Pointer to newly allocated pixel data.
296 * \ NULL if alloc fails
298 void * gdcmFile::GetImageDataRaw (void) {
299 if (Header->HasLUT())
300 lgrTotale /= 3; // TODO Let gdcmHeadar user a chance
301 // to get the right value
302 // Create a member lgrTotaleRaw ???
303 PixelData = (void *) malloc(lgrTotale);
305 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
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 = (unsigned char*) malloc(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'
482 // integer computation counterpart
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 = (char*) malloc(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;
574 * \brief Writes on disk A SINGLE Dicom file
575 * NO test is performed on processor "Endiannity".
576 * It's up to the user to call his Reader properly
577 * @param fileName name of the file to be created
578 * (any already existing file is over written)
579 * @return false if write fails
582 bool gdcmFile::WriteRawData (std::string fileName) {
584 fp1 = fopen(fileName.c_str(),"wb");
586 printf("Fail to open (write) file [%s] \n",fileName.c_str());
589 fwrite (PixelData,lgrTotale, 1, fp1);
596 * \brief Writes on disk A SINGLE Dicom file,
597 * using the Implicit Value Representation convention
598 * NO test is performed on processor "Endiannity".
599 * @param fileName name of the file to be created
600 * (any already existing file is overwritten)
601 * @return false if write fails
604 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
605 return WriteBase(fileName, ImplicitVR);
610 * \brief Writes on disk A SINGLE Dicom file,
611 * using the Implicit Value Representation convention
612 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
613 * (any already existing file is overwritten)
614 * @return false if write fails
617 bool gdcmFile::WriteDcmImplVR (const char* fileName) {
618 return WriteDcmImplVR (std::string (fileName));
623 * \brief Writes on disk A SINGLE Dicom file,
624 * using the Explicit Value Representation convention
625 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
626 * (any already existing file is overwritten)
627 * @return false if write fails
630 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
631 return WriteBase(fileName, ExplicitVR);
636 * \brief Writes on disk A SINGLE Dicom file,
637 * using the ACR-NEMA convention
638 * NO test is performed on processor "Endiannity".
639 * (a l'attention des logiciels cliniques
640 * qui ne prennent en entrée QUE des images ACR ...
641 * \warning if a DICOM_V3 header is supplied,
642 * groups < 0x0008 and shadow groups are ignored
643 * \warning NO TEST is performed on processor "Endiannity".
644 * @param fileName name of the file to be created
645 * (any already existing file is overwritten)
646 * @return false if write fails
649 bool gdcmFile::WriteAcr (std::string fileName) {
650 return WriteBase(fileName, ACR);
653 //-----------------------------------------------------------------------------
657 * \brief NOT a end user inteded function
658 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
659 * @param fileName name of the file to be created
660 * (any already existing file is overwritten)
661 * @param type file type (ExplicitVR, ImplicitVR, ...)
662 * @return false if write fails
664 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
668 if (PixelRead==-1 && type != ExplicitVR) {
672 fp1 = fopen(fileName.c_str(),"wb");
674 printf("Failed to open (write) File [%s] \n",fileName.c_str());
678 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
680 // writing Dicom File Preamble
681 filePreamble=(char*)calloc(128,1);
682 fwrite(filePreamble,128,1,fp1);
683 fwrite("DICM",4,1,fp1);
687 // --------------------------------------------------------------
688 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
690 // if recognition code tells us we dealt with a LibIDO image
691 // we reproduce on disk the switch between lineNumber and columnNumber
692 // just before writting ...
694 // TODO : the best trick would be *change* the recognition code
695 // but pb expected if user deals with, e.g. COMPLEX images
697 std::string rows, columns;
698 if ( Header->GetFileType() == ACR_LIBIDO){
699 rows = Header->GetEntryByNumber(0x0028, 0x0010);
700 columns = Header->GetEntryByNumber(0x0028, 0x0011);
701 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
702 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
704 // ----------------- End of Special Patch ----------------
706 // TODO : get the grPixel, numPixel values (for some ACR-NEMA images only)
708 guint16 grPixel =Header->GetGrPixel();
709 guint16 numPixel=Header->GetNumPixel();;
711 // Update Pixel Data Length
712 // the *last* of the (GrPixel, NumPixel), if many.
714 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
715 TagHeaderEntryHT::iterator p2;
716 gdcmHeaderEntry * PixelElement;
718 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
720 if (Header->GetEntry().count(key) == 1) // only the first is significant
721 p2=it.first; // iterator on the first (unique) synonym
723 p2=it.second;// iterator on the last synonym
725 PixelElement=p2->second; // H Table target column (2-nd col)
726 // PixelElement->SetPrintLevel(2);
727 // PixelElement->Print();
730 PixelElement->SetLength(lgrTotaleRaw);
731 else if (PixelRead==0)
732 PixelElement->SetLength(lgrTotale);
734 //PixelElement->SetPrintLevel(2);
735 //PixelElement->Print();
736 Header->Write(fp1, type);
738 // --------------------------------------------------------------
739 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
741 // ...and we restore the Header to be Dicom Compliant again
742 // just after writting
744 if (Header->GetFileType() == ACR_LIBIDO){
745 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
746 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
748 // ----------------- End of Special Patch ----------------
750 fwrite(PixelData, lgrTotale, 1, fp1);
755 //-----------------------------------------------------------------------------
759 * \brief Swap the bytes, according to swap code.
760 * \warning not end user intended
761 * @param im area to deal with
762 * @param swap swap code
763 * @param lgr Area Length
764 * @param nb Pixels Bit number
766 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
783 for(i=0;i<lgr/2;i++) {
784 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
785 | ((((unsigned short int*)im)[i])<<8);
790 printf("SWAP value (16 bits) not allowed : %d\n", swap);
800 for(i=0;i<lgr/4;i++) {
801 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
802 fort =((unsigned long int*)im)[i]>>16;
803 fort= (fort>>8) | (fort<<8);
804 faible=(faible>>8) | (faible<<8);
806 ((unsigned long int*)im)[i]=(s32<<16)|fort;
811 for(i=0;i<lgr/4;i++) {
812 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
813 fort=((unsigned long int*)im)[i]>>16;
814 fort= (fort>>8) | (fort<<8);
815 faible=(faible>>8) | (faible<<8);
817 ((unsigned long int*)im)[i]=(s32<<16)|faible;
822 for(i=0;i<lgr/4;i++) {
823 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
824 fort=((unsigned long int*)im)[i]>>16;
826 ((unsigned long int*)im)[i]=(s32<<16)|fort;
831 printf("SWAP value (32 bits) not allowed : %d\n", swap);
838 * \brief Read pixel data from disk (optionaly decompressing) into the
839 * caller specified memory location.
840 * @param destination where the pixel data should be stored.
843 bool gdcmFile::ReadPixelData(void* destination) {
847 if ( !(fp=Header->OpenFile()))
849 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
853 // ---------------------- Compacted File (12 Bits Per Pixel)
854 /* unpack 12 Bits pixels into 16 Bits pixels */
855 /* 2 pixels 12bit = [0xABCDEF] */
856 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
858 if (Header->GetBitsAllocated()==12) {
859 int nbPixels = Header->GetXSize() * Header->GetYSize();
860 unsigned char b0, b1, b2;
862 unsigned short int* pdestination = (unsigned short int*)destination;
863 for(int p=0;p<nbPixels;p+=2) {
867 //Two steps is necessary to please VC++
868 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
869 /* A */ /* B */ /* D */
870 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
871 /* F */ /* C */ /* E */
873 // Troubles expected on Big-Endian processors ?
880 // ---------------------- Uncompressed File
881 if ( !Header->IsDicomV3() ||
882 Header->IsImplicitVRLittleEndianTransferSyntax() ||
883 Header->IsExplicitVRLittleEndianTransferSyntax() ||
884 Header->IsExplicitVRBigEndianTransferSyntax() ||
885 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
887 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
888 if ( ItemRead != 1 ) {
897 // ---------------------- Run Length Encoding
898 if (Header->IsRLELossLessTransferSyntax()) {
899 bool res = (bool)gdcm_read_RLE_file (fp,destination);
904 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
906 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
907 if (str_nb == GDCM_UNFOUND ) {
910 nb = atoi(str_nb.c_str() );
911 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
916 int taille = Header->GetXSize() * Header->GetYSize()
917 * Header->GetSamplesPerPixel();
918 long fragmentBegining; // for ftell, fseek
920 bool jpg2000 = Header->IsJPEG2000();
921 bool jpgLossless = Header->IsJPEGLossless();
924 guint16 ItemTagGr,ItemTagEl;
927 // Position on begining of Jpeg Pixels
929 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
930 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
931 if(Header->GetSwapCode()) {
932 ItemTagGr=Header->SwapShort(ItemTagGr);
933 ItemTagEl=Header->SwapShort(ItemTagEl);
936 if(Header->GetSwapCode())
937 ln=Header->SwapLong(ln); // Basic Offset Table Item length
940 // What is it used for ?!?
941 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
942 fread(BasicOffsetTableItemValue,ln,1,fp);
945 // first Fragment initialisation
946 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
947 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
948 if(Header->GetSwapCode()) {
949 ItemTagGr=Header->SwapShort(ItemTagGr);
950 ItemTagEl=Header->SwapShort(ItemTagEl);
953 // parsing fragments until Sequence Delim. Tag found
954 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
955 // --- for each Fragment
958 if(Header->GetSwapCode())
959 ln=Header->SwapLong(ln); // Fragment Item length
961 fragmentBegining=ftell(fp);
963 if (jpg2000) { // JPEG 2000 : call to ???
965 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
967 } // ------------------------------------- endif (JPEG2000)
969 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
971 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
972 (unsigned short *)destination,
973 Header->GetPixelSize()*8* Header->GetSamplesPerPixel(),
975 res=1; // in order not to break the loop
977 } // ------------------------------------- endif (JPEGLossless)
979 else { // JPEG Lossy : call to IJG 6b
981 if (Header->GetBitsStored() == 8) {
982 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
984 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
986 } // ------------------------------------- endif (JPEGLossy)
990 destination = (char *)destination + taille * nBytes; // location in user's memory
991 // for next fragment (if any)
993 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
994 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
996 ItemTagGr = ItemTagEl =0;
997 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
998 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
999 if(Header->GetSwapCode()) {
1000 ItemTagGr=Header->SwapShort(ItemTagGr);
1001 ItemTagEl=Header->SwapShort(ItemTagEl);
1004 } // endWhile parsing fragments until Sequence Delim. Tag found
1006 Header->CloseFile();
1009 //-----------------------------------------------------------------------------