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 Header=new gdcmHeader(filename.c_str());
50 PixelRead=-1; // no ImageData read yet.
52 if (Header->IsReadable())
53 SetPixelDataSizeFromHeader();
58 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
59 * file (see SetFileName, SetDcmTag and Write)
60 * Opens (in read only and when possible) an existing file and checks
61 * for DICOM compliance. Returns NULL on failure.
62 * \note the in-memory representation of all available tags found in
63 * the DICOM header is post-poned to first header information access.
64 * This avoid a double parsing of public part of the header when
65 * one sets an a posteriori shadow dictionary (efficiency can be
66 * seen as a side effect).
67 * @param filename file to be opened for parsing
69 gdcmFile::gdcmFile(const char * filename) {
70 Header=new gdcmHeader(filename);
72 PixelRead=-1; // no ImageData read yet.
74 if (Header->IsReadable())
75 SetPixelDataSizeFromHeader();
80 * \brief canonical destructor
81 * \note If the gdcmHeader is created by the gdcmFile, it is destroyed
84 gdcmFile::~gdcmFile(void) {
90 //-----------------------------------------------------------------------------
93 //-----------------------------------------------------------------------------
97 * \brief returns the gdcmHeader *Header
100 gdcmHeader *gdcmFile::GetHeader(void) {
106 * \brief computes the length (in bytes) to ALLOCATE to receive the
107 * image(s) pixels (multiframes taken into account)
108 * \warning : it is NOT the group 7FE0 length
109 * (no interest for compressed images).
110 * @return length to allocate
112 void gdcmFile::SetPixelDataSizeFromHeader(void) {
113 // see PS 3.3-2003 : C.7.6.3.2.1
123 // YBR_FULL_422 (no LUT, no Palette)
129 // ex : gdcm-US-ALOKA-16.dcm
130 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
131 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
132 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
134 // ex : OT-PAL-8-face.dcm
135 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
136 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
137 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
141 str_nb=Header->GetEntryByNumber(0x0028,0x0100);
142 if (str_nb == GDCM_UNFOUND ) {
145 nb = atoi(str_nb.c_str() );
146 if (nb == 12) nb =16;
148 lgrTotale = lgrTotaleRaw = Header->GetXSize() * Header->GetYSize()
149 * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
150 std::string str_PhotometricInterpretation =
151 Header->GetEntryByNumber(0x0028,0x0004);
153 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
154 // pb when undealt Segmented Palette Color
156 if (Header->HasLUT()) {
163 * \brief Returns the size (in bytes) of required memory to hold
164 * the pixel data represented in this file.
165 * @return The size of pixel data in bytes.
167 size_t gdcmFile::GetImageDataSize(void) {
173 * \brief Returns the size (in bytes) of required memory to hold
174 * the pixel data represented in this file, when user DOESN'T want
175 * to get RGB pixels image when it's stored as a PALETTE COLOR image
176 * -the (vtk) user is supposed to know how deal with LUTs-
177 * \warning to be used with GetImagePixelsRaw()
178 * @return The size of pixel data in bytes.
180 size_t gdcmFile::GetImageDataSizeRaw(void) {
181 return (lgrTotaleRaw);
186 * \brief Allocates necessary memory, copies the pixel data
187 * (image[s]/volume[s]) to newly allocated zone.
188 * Transforms YBR pixels into RGB pixels if any
189 * Transforms 3 planes R, G, B into a single RGB Plane
190 * Transforms single Grey plane + 3 Palettes into a RGB Plane
191 * @return Pointer to newly allocated pixel data.
192 * NULL if alloc fails
194 void * gdcmFile::GetImageData (void) {
195 PixelData = (void *) malloc(lgrTotale);
197 GetImageDataIntoVector(PixelData, lgrTotale);
199 PixelRead=0; // no PixelRaw
205 * \brief Copies at most MaxSize bytes of pixel data to caller's
207 * \warning This function was designed to avoid people that want to build
208 * a volume from an image stack to need first to get the image pixels
209 * and then move them to the volume area.
210 * It's absolutely useless for any VTK user since vtk chooses
211 * to invert the lines of an image, that is the last line comes first
212 * (for some axis related reasons?). Hence he will have
213 * to load the image line by line, starting from the end.
214 * VTK users have to call GetImageData
216 * @param destination Address (in caller's memory space) at which the
217 * pixel data should be copied
218 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
219 * is not sufficient to hold the pixel data the copy is not
220 * executed (i.e. no partial copy).
221 * @return On success, the number of bytes actually copied. Zero on
222 * failure e.g. MaxSize is lower than necessary.
224 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
225 size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
226 PixelRead=0 ; // no PixelRaw
227 if (!Header->HasLUT())
230 // from Lut R + Lut G + Lut B
231 unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
232 unsigned char * a = (unsigned char *)destination;
233 unsigned char * lutRGBA = Header->GetLUTRGBA();
235 int l = lgrTotaleRaw;
236 memmove(newDest, destination, l);// move Gray pixels to temp area
238 for (int i=0;i<l; i++) { // Build RGB Pixels
246 // now, it's an RGB image
247 // Lets's write it in the Header
249 // CreateOrReplaceIfExist ?
251 std::string spp = "3"; // Samples Per Pixel
252 Header->SetEntryByNumber(spp,0x0028,0x0002);
253 std::string rgb= "RGB "; // Photometric Interpretation
254 Header->SetEntryByNumber(rgb,0x0028,0x0004);
255 std::string planConfig = "0"; // Planar Configuration
256 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
259 // need to make RGB Pixels (?)
260 // from grey Pixels (?!)
261 // and Gray Lut (!?!)
262 // or Segmented xxx Palette Color Lookup Table Data and so on
264 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
265 // No idea how to manage such an image
266 // It seems that *no Dicom Viewer* has any idea :-(
267 // Segmented xxx Palette Color are *more* than 65535 long ?!?
269 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
270 Header->SetEntryByNumber(rgb,0x0028,0x0004);
272 // TODO : Drop Palette Color out of the Header?
278 * \brief Allocates necessary memory, copies the pixel data
279 * (image[s]/volume[s]) to newly allocated zone.
280 * Transforms YBR pixels into RGB pixels if any
281 * Transforms 3 planes R, G, B into a single RGB Plane
282 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
283 * @return Pointer to newly allocated pixel data.
284 * \ NULL if alloc fails
286 void * gdcmFile::GetImageDataRaw (void) {
287 if (Header->HasLUT())
288 lgrTotale /= 3; // TODO Let gdcmHeadar user a chance
289 // to get the right value
290 // Create a member lgrTotaleRaw ???
291 PixelData = (void *) malloc(lgrTotale);
293 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
294 PixelRead=1; // PixelRaw
300 * \brief Copies at most MaxSize bytes of pixel data to caller's
302 * \warning This function was designed to avoid people that want to build
303 * a volume from an image stack to need first to get the image pixels
304 * and then move them to the volume area.
305 * It's absolutely useless for any VTK user since vtk chooses
306 * to invert the lines of an image, that is the last line comes first
307 * (for some axis related reasons?). Hence he will have
308 * to load the image line by line, starting from the end.
309 * VTK users hace to call GetImageData
310 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
311 * into a single RGB Pixels Plane
312 * the (VTK) user will manage the palettes
314 * @param destination Address (in caller's memory space) at which the
315 * pixel data should be copied
316 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
317 * is not sufficient to hold the pixel data the copy is not
318 * executed (i.e. no partial copy).
319 * @return On success, the number of bytes actually copied. Zero on
320 * failure e.g. MaxSize is lower than necessary.
322 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t MaxSize) {
324 int nb, nbu, highBit, signe;
325 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
326 PixelRead=1 ; // PixelRaw
328 if ( lgrTotale > MaxSize ) {
329 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
330 "than caller's expected MaxSize");
334 (void)ReadPixelData(destination);
336 // Number of Bits Allocated for storing a Pixel
337 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
338 if (str_nb == GDCM_UNFOUND ) {
341 nb = atoi(str_nb.c_str() );
343 // Number of Bits actually used
344 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
345 if (str_nbu == GDCM_UNFOUND ) {
348 nbu = atoi(str_nbu.c_str() );
351 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
352 if (str_highBit == GDCM_UNFOUND ) {
355 highBit = atoi(str_highBit.c_str() );
360 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
361 if (str_signe == GDCM_UNFOUND ) {
362 signe = 0; // default is unsigned
364 signe = atoi(str_signe.c_str() );
367 // re arange bytes inside the integer (processor endianity)
369 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
371 // to avoid pb with some xmedcon breakers images
372 if (nb==16 && nbu<nb && signe==0) {
373 int l = (int)lgrTotale / (nb/8);
374 guint16 *deb = (guint16 *)destination;
375 for(int i = 0; i<l; i++) {
381 // re arange bits inside the bytes
383 int l = (int)lgrTotale / (nb/8);
385 guint16 mask = 0xffff;
386 mask = mask >> (nb-nbu);
387 guint16 *deb = (guint16 *)destination;
388 for(int i = 0; i<l; i++) {
389 *deb = (*deb >> (nbu-highBit-1)) & mask;
392 } else if (nb == 32 ) {
393 guint32 mask = 0xffffffff;
394 mask = mask >> (nb-nbu);
395 guint32 *deb = (guint32 *)destination;
396 for(int i = 0; i<l; i++) {
397 *deb = (*deb >> (nbu-highBit-1)) & mask;
401 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
405 // DO NOT remove this commented out code .
406 // Nobody knows what's expecting you ...
407 // Just to 'see' what was actually read on disk :-(
410 // f2 = fopen("SpuriousFile.RAW","wb");
411 // fwrite(destination,lgrTotale,1,f2);
414 // Deal with the color
415 // -------------------
417 std::string str_PhotometricInterpretation =
418 Header->GetEntryByNumber(0x0028,0x0004);
420 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
421 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
425 // Planar configuration = 0 : Pixels are already RGB
426 // Planar configuration = 1 : 3 planes : R, G, B
427 // Planar configuration = 2 : 1 gray Plane + 3 LUT
429 // Well ... supposed to be !
430 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
431 // PhotometricInterpretation=PALETTE COLOR
432 // and heuristic has to be found :-(
434 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
436 // Whatever Planar Configuration is,
437 // "PALETTE COLOR " implies that we deal with the palette.
438 if (str_PhotometricInterpretation == "PALETTE COLOR ")
443 // Pixels are already RGB
449 if (str_PhotometricInterpretation == "YBR_FULL") {
451 // Warning : YBR_FULL_422 acts as RGB
452 // : we need to make RGB Pixels from Planes Y,cB,cR
454 // to see the tricks about YBR_FULL, YBR_FULL_422,
455 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
456 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
457 // and be *very* affraid
459 int l = Header->GetXSize()*Header->GetYSize();
460 int nbFrames = Header->GetZSize();
462 unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
463 unsigned char *x = newDest;
464 unsigned char * a = (unsigned char *)destination;
465 unsigned char * b = a + l;
466 unsigned char * c = b + l;
469 // TODO : Replace by the 'well known'
470 // integer computation counterpart
471 // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
472 // for code optimisation
474 for (int i=0;i<nbFrames;i++) {
475 for (int j=0;j<l; j++) {
476 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
477 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
478 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
483 if (R>255.0) R=255.0;
484 if (G>255.0) G=255.0;
485 if (B>255.0) B=255.0;
487 *(x++) = (unsigned char)R;
488 *(x++) = (unsigned char)G;
489 *(x++) = (unsigned char)B;
493 memmove(destination,newDest,lgrTotale);
498 // need to make RGB Pixels from R,G,B Planes
499 // (all the Frames at a time)
501 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
503 char * newDest = (char*) malloc(lgrTotale);
505 char * a = (char *)destination;
509 for (int j=0;j<l; j++) {
514 memmove(destination,newDest,lgrTotale);
520 // Palettes were found
521 // Let the user deal with them !
524 // now, it's an RGB image
525 // Lets's write it in the Header
527 // CreateOrReplaceIfExist ?
529 std::string spp = "3"; // Samples Per Pixel
530 Header->SetEntryByNumber(spp,0x0028,0x0002);
531 std::string rgb="RGB "; // Photometric Interpretation
532 Header->SetEntryByNumber(rgb,0x0028,0x0004);
534 std::string planConfig = "0"; // Planar Configuration
535 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
537 // TODO : Drop Palette Color out of the Header?
543 * \brief performs a shadow copy (not a deep copy) of the user given
545 * 'image' Pixels are presented as C-like 2D arrays : line per line.
546 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
547 * \warning user is kindly requested NOT TO 'free' the Pixel area
548 * @param inData user supplied pixel area
549 * @param ExpectedSize total image size, in Bytes
553 bool gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
554 Header->SetImageDataSize(ExpectedSize);
556 lgrTotale = ExpectedSize;
562 * \brief Writes on disk A SINGLE Dicom file
563 * NO test is performed on processor "Endiannity".
564 * It's up to the user to call his Reader properly
565 * @param fileName name of the file to be created
566 * (any already existing file is over written)
567 * @return false if write fails
570 bool gdcmFile::WriteRawData (std::string fileName) {
572 fp1 = fopen(fileName.c_str(),"wb");
574 printf("Fail to open (write) file [%s] \n",fileName.c_str());
577 fwrite (PixelData,lgrTotale, 1, fp1);
584 * \brief Writes on disk A SINGLE Dicom file,
585 * using the Implicit Value Representation convention
586 * NO test is performed on processor "Endiannity".
587 * @param fileName name of the file to be created
588 * (any already existing file is overwritten)
589 * @return false if write fails
592 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
593 return WriteBase(fileName, ImplicitVR);
598 * \brief Writes on disk A SINGLE Dicom file,
599 * using the Implicit Value Representation convention
600 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
601 * (any already existing file is overwritten)
602 * @return false if write fails
605 bool gdcmFile::WriteDcmImplVR (const char* fileName) {
606 return WriteDcmImplVR (std::string (fileName));
611 * \brief Writes on disk A SINGLE Dicom file,
612 * using the Explicit Value Representation convention
613 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
614 * (any already existing file is overwritten)
615 * @return false if write fails
618 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
619 return WriteBase(fileName, ExplicitVR);
624 * \brief Writes on disk A SINGLE Dicom file,
625 * using the ACR-NEMA convention
626 * NO test is performed on processor "Endiannity".
627 * (a l'attention des logiciels cliniques
628 * qui ne prennent en entrée QUE des images ACR ...
629 * \warning if a DICOM_V3 header is supplied,
630 * groups < 0x0008 and shadow groups are ignored
631 * \warning NO TEST is performed on processor "Endiannity".
632 * @param fileName name of the file to be created
633 * (any already existing file is overwritten)
634 * @return false if write fails
637 bool gdcmFile::WriteAcr (std::string fileName) {
638 return WriteBase(fileName, ACR);
641 //-----------------------------------------------------------------------------
645 * \brief NOT a end user inteded function
646 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
647 * @param fileName name of the file to be created
648 * (any already existing file is overwritten)
649 * @param type file type (ExplicitVR, ImplicitVR, ...)
650 * @return false if write fails
652 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
656 if (PixelRead==-1 && type != ExplicitVR) {
660 fp1 = fopen(fileName.c_str(),"wb");
662 printf("Failed to open (write) File [%s] \n",fileName.c_str());
666 if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
668 // writing Dicom File Preamble
669 filePreamble=(char*)calloc(128,1);
670 fwrite(filePreamble,128,1,fp1);
671 fwrite("DICM",4,1,fp1);
675 // --------------------------------------------------------------
676 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
678 // if recognition code tells us we dealt with a LibIDO image
679 // we reproduce on disk the switch between lineNumber and columnNumber
680 // just before writting ...
682 // TODO : the best trick would be *change* the recognition code
683 // but pb expected if user deals with, e.g. COMPLEX images
685 std::string rows, columns;
686 if ( Header->GetFileType() == ACR_LIBIDO){
687 rows = Header->GetEntryByNumber(0x0028, 0x0010);
688 columns = Header->GetEntryByNumber(0x0028, 0x0011);
689 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
690 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
692 // ----------------- End of Special Patch ----------------
694 // TODO : get the grPixel, numPixel values (for some ACR-NEMA images only)
696 guint16 grPixel =Header->GetGrPixel();
697 guint16 numPixel=Header->GetNumPixel();;
699 // Update Pixel Data Length
700 // the *last* of the (GrPixel, NumPixel), if many.
702 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
703 TagHeaderEntryHT::iterator p2;
704 gdcmHeaderEntry * PixelElement;
706 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
708 if (Header->GetEntry().count(key) == 1) // only the first is significant
709 p2=it.first; // iterator on the first (unique) synonym
711 p2=it.second;// iterator on the last synonym
713 PixelElement=p2->second; // H Table target column (2-nd col)
714 // PixelElement->SetPrintLevel(2);
715 // PixelElement->Print();
718 PixelElement->SetLength(lgrTotaleRaw);
719 else if (PixelRead==0)
720 PixelElement->SetLength(lgrTotale);
722 //PixelElement->SetPrintLevel(2);
723 //PixelElement->Print();
724 Header->Write(fp1, type);
726 // --------------------------------------------------------------
727 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
729 // ...and we restore the Header to be Dicom Compliant again
730 // just after writting
732 if (Header->GetFileType() == ACR_LIBIDO){
733 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
734 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
736 // ----------------- End of Special Patch ----------------
738 fwrite(PixelData, lgrTotale, 1, fp1);
743 //-----------------------------------------------------------------------------
747 * \brief Swap the bytes, according to swap code.
748 * \warning not end user intended
749 * @param im area to deal with
750 * @param swap swap code
751 * @param lgr Area Length
752 * @param nb Pixels Bit number
754 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
771 for(i=0;i<lgr/2;i++) {
772 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
773 | ((((unsigned short int*)im)[i])<<8);
778 printf("SWAP value (16 bits) not allowed : %d\n", swap);
788 for(i=0;i<lgr/4;i++) {
789 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 4321 */
790 fort =((unsigned long int*)im)[i]>>16;
791 fort= (fort>>8) | (fort<<8);
792 faible=(faible>>8) | (faible<<8);
794 ((unsigned long int*)im)[i]=(s32<<16)|fort;
799 for(i=0;i<lgr/4;i++) {
800 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 2143 */
801 fort=((unsigned long int*)im)[i]>>16;
802 fort= (fort>>8) | (fort<<8);
803 faible=(faible>>8) | (faible<<8);
805 ((unsigned long int*)im)[i]=(s32<<16)|faible;
810 for(i=0;i<lgr/4;i++) {
811 faible= ((unsigned long int*)im)[i]&0x0000ffff; /* 3412 */
812 fort=((unsigned long int*)im)[i]>>16;
814 ((unsigned long int*)im)[i]=(s32<<16)|fort;
819 printf("SWAP value (32 bits) not allowed : %d\n", swap);
826 * \brief Read pixel data from disk (optionaly decompressing) into the
827 * caller specified memory location.
828 * @param destination where the pixel data should be stored.
831 bool gdcmFile::ReadPixelData(void* destination) {
835 if ( !(fp=Header->OpenFile()))
837 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
841 // ---------------------- Compacted File (12 Bits Per Pixel)
842 /* unpack 12 Bits pixels into 16 Bits pixels */
843 /* 2 pixels 12bit = [0xABCDEF] */
844 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
846 if (Header->GetBitsAllocated()==12) {
847 int nbPixels = Header->GetXSize() * Header->GetYSize();
848 unsigned char b0, b1, b2;
850 unsigned short int* pdestination = (unsigned short int*)destination;
851 for(int p=0;p<nbPixels;p+=2) {
855 //Two steps is necessary to please VC++
856 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
857 /* A */ /* B */ /* D */
858 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
859 /* F */ /* C */ /* E */
861 // Troubles expected on Big-Endian processors ?
868 // ---------------------- Uncompressed File
869 if ( !Header->IsDicomV3() ||
870 Header->IsImplicitVRLittleEndianTransferSyntax() ||
871 Header->IsExplicitVRLittleEndianTransferSyntax() ||
872 Header->IsExplicitVRBigEndianTransferSyntax() ||
873 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
875 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
876 if ( ItemRead != 1 ) {
885 // ---------------------- Run Length Encoding
886 if (Header->IsRLELossLessTransferSyntax()) {
887 bool res = (bool)gdcm_read_RLE_file (fp,destination);
892 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
894 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
895 if (str_nb == GDCM_UNFOUND ) {
898 nb = atoi(str_nb.c_str() );
899 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
904 int taille = Header->GetXSize() * Header->GetYSize()
905 * Header->GetSamplesPerPixel();
906 long fragmentBegining; // for ftell, fseek
908 bool jpg2000 = Header->IsJPEG2000();
909 bool jpgLossless = Header->IsJPEGLossless();
912 guint16 ItemTagGr,ItemTagEl;
915 // Position on begining of Jpeg Pixels
917 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
918 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
919 if(Header->GetSwapCode()) {
920 ItemTagGr=Header->SwapShort(ItemTagGr);
921 ItemTagEl=Header->SwapShort(ItemTagEl);
924 if(Header->GetSwapCode())
925 ln=Header->SwapLong(ln); // Basic Offset Table Item length
928 // What is it used for ?!?
929 char *BasicOffsetTableItemValue = (char *)malloc(ln+1);
930 fread(BasicOffsetTableItemValue,ln,1,fp);
933 // first Fragment initialisation
934 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
935 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
936 if(Header->GetSwapCode()) {
937 ItemTagGr=Header->SwapShort(ItemTagGr);
938 ItemTagEl=Header->SwapShort(ItemTagEl);
941 // parsing fragments until Sequence Delim. Tag found
942 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
943 // --- for each Fragment
946 if(Header->GetSwapCode())
947 ln=Header->SwapLong(ln); // Fragment Item length
949 fragmentBegining=ftell(fp);
951 if (jpg2000) { // JPEG 2000 : call to ???
953 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
955 } // ------------------------------------- endif (JPEG2000)
957 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
959 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
960 (unsigned short *)destination,
961 Header->GetPixelSize()*8* Header->GetSamplesPerPixel(),
963 res=1; // in order not to break the loop
965 } // ------------------------------------- endif (JPEGLossless)
967 else { // JPEG Lossy : call to IJG 6b
969 if (Header->GetBitsStored() == 8) {
970 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
972 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
974 } // ------------------------------------- endif (JPEGLossy)
978 destination = (char *)destination + taille * nBytes; // location in user's memory
979 // for next fragment (if any)
981 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
982 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
984 ItemTagGr = ItemTagEl =0;
985 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
986 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
987 if(Header->GetSwapCode()) {
988 ItemTagGr=Header->SwapShort(ItemTagGr);
989 ItemTagEl=Header->SwapShort(ItemTagEl);
992 } // endWhile parsing fragments until Sequence Delim. Tag found
997 //-----------------------------------------------------------------------------