2 //-----------------------------------------------------------------------------
5 #include "jpeg/ljpg/jpegless.h"
7 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::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
46 * @param exception_on_error whether we throw an exception or not
47 * @param enable_sequences = true to allow the header
48 * to be parsed *inside* the SeQuences,
49 * when they have an actual length
50 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
51 * @param ignore_shadow to allow skipping the shadow elements,
52 * to save memory space.
53 * \warning The TRUE value for this param has to be used
54 * with a FALSE value for the 'enable_sequence' param.
55 * ('public elements' may be embedded in 'shadow Sequences')
57 gdcmFile::gdcmFile(std::string & filename,
58 bool exception_on_error,
59 bool enable_sequences,
61 Header=new gdcmHeader(filename.c_str(),
66 PixelRead=-1; // no ImageData read yet.
68 if (Header->IsReadable())
69 SetPixelDataSizeFromHeader();
74 * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
75 * file (see SetFileName, SetDcmTag and Write)
76 * Opens (in read only and when possible) an existing file and checks
77 * for DICOM compliance. Returns NULL on failure.
78 * \note the in-memory representation of all available tags found in
79 * the DICOM header is post-poned to first header information access.
80 * This avoid a double parsing of public part of the header when
81 * one sets an a posteriori shadow dictionary (efficiency can be
82 * seen as a side effect).
83 * @param filename file to be opened for parsing
84 * @param exception_on_error whether we throw an exception or not
85 * @param enable_sequences = true to allow the header
86 * to be parsed *inside* the SeQuences,
87 * when they have an actual length
88 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
89 * @param ignore_shadow to allow skipping the shadow elements,
90 * to save memory space.
91 * \warning The TRUE value for this param has to be used
92 * with a FALSE value for the 'enable_sequence' param.
93 * ('public elements' may be embedded in 'shadow Sequences')
95 gdcmFile::gdcmFile(const char *filename,
96 bool exception_on_error,
97 bool enable_sequences,
99 Header=new gdcmHeader(filename,
104 PixelRead=-1; // no ImageData read yet.
106 if (Header->IsReadable())
107 SetPixelDataSizeFromHeader();
112 * \brief canonical destructor
113 * \note If the gdcmHeader is created by the gdcmFile, it is destroyed
116 gdcmFile::~gdcmFile(void) {
122 //-----------------------------------------------------------------------------
125 //-----------------------------------------------------------------------------
129 * \brief returns the gdcmHeader *Header
132 gdcmHeader *gdcmFile::GetHeader(void) {
138 * \brief computes the length (in bytes) to ALLOCATE to receive the
139 * image(s) pixels (multiframes taken into account)
140 * \warning : it is NOT the group 7FE0 length
141 * (no interest for compressed images).
142 * @return length to allocate
144 void gdcmFile::SetPixelDataSizeFromHeader(void) {
145 // see PS 3.3-2003 : C.7.6.3.2.1
155 // YBR_FULL_422 (no LUT, no Palette)
161 // ex : gdcm-US-ALOKA-16.dcm
162 // 0028|1221 [OW] [Segmented Red Palette Color Lookup Table Data]
163 // 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
164 // 0028|1223 [OW] [Segmented Blue Palette Color Lookup Table Data]
166 // ex : OT-PAL-8-face.dcm
167 // 0028|1201 [US] [Red Palette Color Lookup Table Data]
168 // 0028|1202 [US] [Green Palette Color Lookup Table Data]
169 // 0028|1203 [US] [Blue Palette Color Lookup Table Data]
173 str_nb=Header->GetEntryByNumber(0x0028,0x0100);
174 if (str_nb == GDCM_UNFOUND ) {
177 nb = atoi(str_nb.c_str() );
178 if (nb == 12) nb =16;
180 lgrTotale = lgrTotaleRaw = Header->GetXSize() * Header->GetYSize()
181 * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
182 std::string str_PhotometricInterpretation =
183 Header->GetEntryByNumber(0x0028,0x0004);
185 /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
186 // pb when undealt Segmented Palette Color
188 if (Header->HasLUT()) {
195 * \brief Returns the size (in bytes) of required memory to hold
196 * the pixel data represented in this file.
197 * @return The size of pixel data in bytes.
199 size_t gdcmFile::GetImageDataSize(void) {
205 * \brief Returns the size (in bytes) of required memory to hold
206 * the pixel data represented in this file, when user DOESN'T want
207 * to get RGB pixels image when it's stored as a PALETTE COLOR image
208 * -the (vtk) user is supposed to know how deal with LUTs-
209 * \warning to be used with GetImagePixelsRaw()
210 * @return The size of pixel data in bytes.
212 size_t gdcmFile::GetImageDataSizeRaw(void) {
213 return (lgrTotaleRaw);
218 * \brief Allocates necessary memory, copies the pixel data
219 * (image[s]/volume[s]) to newly allocated zone.
220 * Transforms YBR pixels into RGB pixels if any
221 * Transforms 3 planes R, G, B into a single RGB Plane
222 * Transforms single Grey plane + 3 Palettes into a RGB Plane
223 * @return Pointer to newly allocated pixel data.
224 * NULL if alloc fails
226 void * gdcmFile::GetImageData (void) {
227 PixelData = new char[lgrTotale];
229 GetImageDataIntoVector(PixelData, lgrTotale);
230 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
231 GetHeader()->GetGrPixel(),
232 GetHeader()->GetNumPixel());
234 PixelRead=0; // no PixelRaw
241 * \brief Copies at most MaxSize bytes of pixel data to caller's
243 * \warning This function was designed to avoid people that want to build
244 * a volume from an image stack to need first to get the image pixels
245 * and then move them to the volume area.
246 * It's absolutely useless for any VTK user since vtk chooses
247 * to invert the lines of an image, that is the last line comes first
248 * (for some axis related reasons?). Hence he will have
249 * to load the image line by line, starting from the end.
250 * VTK users have to call GetImageData
252 * @param destination Address (in caller's memory space) at which the
253 * pixel data should be copied
254 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
255 * is not sufficient to hold the pixel data the copy is not
256 * executed (i.e. no partial copy).
257 * @return On success, the number of bytes actually copied. Zero on
258 * failure e.g. MaxSize is lower than necessary.
260 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
261 //size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
262 GetImageDataIntoVectorRaw (destination, MaxSize);
263 PixelRead=0 ; // no PixelRaw
264 if (!Header->HasLUT())
267 // from Lut R + Lut G + Lut B
268 unsigned char *newDest = new unsigned char[lgrTotale];
269 unsigned char *a = (unsigned char *)destination;
270 unsigned char *lutRGBA = Header->GetLUTRGBA();
272 int l = lgrTotaleRaw;
273 memmove(newDest, destination, l);// move Gray pixels to temp area
275 for (int i=0;i<l; i++) { // Build RGB Pixels
283 // now, it's an RGB image
284 // Lets's write it in the Header
286 // CreateOrReplaceIfExist ?
288 std::string spp = "3"; // Samples Per Pixel
289 Header->SetEntryByNumber(spp,0x0028,0x0002);
290 std::string rgb= "RGB "; // Photometric Interpretation
291 Header->SetEntryByNumber(rgb,0x0028,0x0004);
292 std::string planConfig = "0"; // Planar Configuration
293 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
296 // need to make RGB Pixels (?)
297 // from grey Pixels (?!)
298 // and Gray Lut (!?!)
299 // or Segmented xxx Palette Color Lookup Table Data and so on
301 // Oops! I get one (gdcm-US-ALOKA-16.dcm)
302 // No idea how to manage such an image
303 // It seems that *no Dicom Viewer* has any idea :-(
304 // Segmented xxx Palette Color are *more* than 65535 long ?!?
306 std::string rgb= "MONOCHROME1 "; // Photometric Interpretation
307 Header->SetEntryByNumber(rgb,0x0028,0x0004);
309 /// \todo Drop Palette Color out of the Header?
315 * \brief Allocates necessary memory, copies the pixel data
316 * (image[s]/volume[s]) to newly allocated zone.
317 * Transforms YBR pixels into RGB pixels if any
318 * Transforms 3 planes R, G, B into a single RGB Plane
319 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
320 * @return Pointer to newly allocated pixel data.
321 * \ NULL if alloc fails
323 void * gdcmFile::GetImageDataRaw (void) {
324 if (Header->HasLUT())
325 /// \todo Let gdcmHeadar user a chance to get the right value
326 /// Create a member lgrTotaleRaw ???
328 PixelData = new char[lgrTotale];
331 GetImageDataIntoVectorRaw(PixelData, lgrTotale);
332 GetHeader()->SetEntryVoidAreaByNumber(PixelData,
333 GetHeader()->GetGrPixel(),
334 GetHeader()->GetNumPixel());
336 PixelRead=1; // PixelRaw
342 * \brief Copies at most MaxSize bytes of pixel data to caller's
344 * \warning This function was designed to avoid people that want to build
345 * a volume from an image stack to need first to get the image pixels
346 * and then move them to the volume area.
347 * It's absolutely useless for any VTK user since vtk chooses
348 * to invert the lines of an image, that is the last line comes first
349 * (for some axis related reasons?). Hence he will have
350 * to load the image line by line, starting from the end.
351 * VTK users hace to call GetImageData
352 * \warning DOES NOT transform the Grey Plane + Palette Color (if any)
353 * into a single RGB Pixels Plane
354 * the (VTK) user will manage the palettes
356 * @param destination Address (in caller's memory space) at which the
357 * pixel data should be copied
358 * @param MaxSize Maximum number of bytes to be copied. When MaxSize
359 * is not sufficient to hold the pixel data the copy is not
360 * executed (i.e. no partial copy).
361 * @return On success, the number of bytes actually copied. Zero on
362 * failure e.g. MaxSize is lower than necessary.
364 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
366 int nb, nbu, highBit, signe;
367 std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
368 PixelRead=1 ; // PixelRaw
370 if ( lgrTotale > MaxSize ) {
371 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
372 "than caller's expected MaxSize");
376 (void)ReadPixelData(destination);
378 // Number of Bits Allocated for storing a Pixel
379 str_nb = Header->GetEntryByNumber(0x0028,0x0100);
380 if (str_nb == GDCM_UNFOUND ) {
383 nb = atoi(str_nb.c_str() );
385 // Number of Bits actually used
386 str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
387 if (str_nbu == GDCM_UNFOUND ) {
390 nbu = atoi(str_nbu.c_str() );
393 str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
394 if (str_highBit == GDCM_UNFOUND ) {
397 highBit = atoi(str_highBit.c_str() );
402 str_signe=Header->GetEntryByNumber(0x0028,0x0103);
403 if (str_signe == GDCM_UNFOUND ) {
404 signe = 0; // default is unsigned
406 signe = atoi(str_signe.c_str() );
409 // re arange bytes inside the integer (processor endianity)
411 SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
413 // to avoid pb with some xmedcon breakers images
414 if (nb==16 && nbu<nb && signe==0) {
415 int l = (int)lgrTotale / (nb/8);
416 guint16 *deb = (guint16 *)destination;
417 for(int i = 0; i<l; i++) {
423 // re arange bits inside the bytes
425 int l = (int)lgrTotale / (nb/8);
427 guint16 mask = 0xffff;
428 mask = mask >> (nb-nbu);
429 guint16 *deb = (guint16 *)destination;
430 for(int i = 0; i<l; i++) {
431 *deb = (*deb >> (nbu-highBit-1)) & mask;
434 } else if (nb == 32 ) {
435 guint32 mask = 0xffffffff;
436 mask = mask >> (nb-nbu);
437 guint32 *deb = (guint32 *)destination;
438 for(int i = 0; i<l; i++) {
439 *deb = (*deb >> (nbu-highBit-1)) & mask;
443 dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
447 // DO NOT remove this commented out code .
448 // Nobody knows what's expecting you ...
449 // Just to 'see' what was actually read on disk :-(
452 // f2 = fopen("SpuriousFile.RAW","wb");
453 // fwrite(destination,lgrTotale,1,f2);
456 // Deal with the color
457 // -------------------
459 std::string str_PhotometricInterpretation =
460 Header->GetEntryByNumber(0x0028,0x0004);
462 if ( (str_PhotometricInterpretation == "MONOCHROME1 ")
463 || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
467 // Planar configuration = 0 : Pixels are already RGB
468 // Planar configuration = 1 : 3 planes : R, G, B
469 // Planar configuration = 2 : 1 gray Plane + 3 LUT
471 // Well ... supposed to be !
472 // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
473 // PhotometricInterpretation=PALETTE COLOR
474 // and heuristic has to be found :-(
476 int planConf=Header->GetPlanarConfiguration(); // 0028,0006
478 // Whatever Planar Configuration is,
479 // "PALETTE COLOR " implies that we deal with the palette.
480 if (str_PhotometricInterpretation == "PALETTE COLOR ")
485 // Pixels are already RGB
491 if (str_PhotometricInterpretation == "YBR_FULL") {
493 // Warning : YBR_FULL_422 acts as RGB
494 // : we need to make RGB Pixels from Planes Y,cB,cR
496 // to see the tricks about YBR_FULL, YBR_FULL_422,
497 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
498 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
499 // and be *very* affraid
501 int l = Header->GetXSize()*Header->GetYSize();
502 int nbFrames = Header->GetZSize();
504 unsigned char *newDest = new unsigned char[lgrTotale];
505 unsigned char *x = newDest;
506 unsigned char *a = (unsigned char *)destination;
507 unsigned char *b = a + l;
508 unsigned char *c = b + l;
511 /// \todo : Replace by the 'well known' integer computation
513 /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
514 /// for code optimisation
516 for (int i=0;i<nbFrames;i++) {
517 for (int j=0;j<l; j++) {
518 R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
519 G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
520 B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
525 if (R>255.0) R=255.0;
526 if (G>255.0) G=255.0;
527 if (B>255.0) B=255.0;
529 *(x++) = (unsigned char)R;
530 *(x++) = (unsigned char)G;
531 *(x++) = (unsigned char)B;
535 memmove(destination,newDest,lgrTotale);
540 // need to make RGB Pixels from R,G,B Planes
541 // (all the Frames at a time)
543 int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
545 char *newDest = new char[lgrTotale];
547 char *a = (char *)destination;
551 for (int j=0;j<l; j++) {
556 memmove(destination,newDest,lgrTotale);
562 // Palettes were found
563 // Let the user deal with them !
566 // now, it's an RGB image
567 // Lets's write it in the Header
569 // CreateOrReplaceIfExist ?
571 std::string spp = "3"; // Samples Per Pixel
572 Header->SetEntryByNumber(spp,0x0028,0x0002);
573 std::string rgb="RGB "; // Photometric Interpretation
574 Header->SetEntryByNumber(rgb,0x0028,0x0004);
576 std::string planConfig = "0"; // Planar Configuration
577 Header->SetEntryByNumber(planConfig,0x0028,0x0006);
579 /// \todo Drop Palette Color out of the Header?
585 * \brief performs a shadow copy (not a deep copy) of the user given
587 * 'image' Pixels are presented as C-like 2D arrays : line per line.
588 * 'volume'Pixels are presented as C-like 3D arrays : lane per plane
589 * \warning user is kindly requested NOT TO 'free' the Pixel area
590 * @param inData user supplied pixel area
591 * @param ExpectedSize total image size, in Bytes
595 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
596 Header->SetImageDataSize(ExpectedSize);
598 lgrTotale = ExpectedSize;
605 * \brief Writes on disk A SINGLE Dicom file
606 * NO test is performed on processor "Endiannity".
607 * It's up to the user to call his Reader properly
608 * @param fileName name of the file to be created
609 * (any already existing file is over written)
610 * @return false if write fails
613 bool gdcmFile::WriteRawData (std::string fileName) {
615 fp1 = fopen(fileName.c_str(),"wb");
617 printf("Fail to open (write) file [%s] \n",fileName.c_str());
620 fwrite (PixelData,lgrTotale, 1, fp1);
627 * \brief Writes on disk A SINGLE Dicom file,
628 * using the Implicit Value Representation convention
629 * NO test is performed on processor "Endiannity".
630 * @param fileName name of the file to be created
631 * (any already existing file is overwritten)
632 * @return false if write fails
635 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
636 return WriteBase(fileName, gdcmImplicitVR);
641 * \brief Writes on disk A SINGLE Dicom file,
642 * using the Implicit Value Representation convention
643 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
644 * (any already existing file is overwritten)
645 * @return false if write fails
648 bool gdcmFile::WriteDcmImplVR (const char *fileName) {
649 return WriteDcmImplVR (std::string (fileName));
654 * \brief Writes on disk A SINGLE Dicom file,
655 * using the Explicit Value Representation convention
656 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
657 * (any already existing file is overwritten)
658 * @return false if write fails
661 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
662 return WriteBase(fileName, gdcmExplicitVR);
667 * \brief Writes on disk A SINGLE Dicom file,
668 * using the ACR-NEMA convention
669 * NO test is performed on processor "Endiannity".
670 * (a l'attention des logiciels cliniques
671 * qui ne prennent en entrée QUE des images ACR ...
672 * \warning if a DICOM_V3 header is supplied,
673 * groups < 0x0008 and shadow groups are ignored
674 * \warning NO TEST is performed on processor "Endiannity".
675 * @param fileName name of the file to be created
676 * (any already existing file is overwritten)
677 * @return false if write fails
680 bool gdcmFile::WriteAcr (std::string fileName) {
681 return WriteBase(fileName, gdcmACR);
684 //-----------------------------------------------------------------------------
688 * \brief NOT a end user inteded function
689 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
690 * @param fileName name of the file to be created
691 * (any already existing file is overwritten)
692 * @param type file type (ExplicitVR, ImplicitVR, ...)
693 * @return false if write fails
695 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
699 if (PixelRead==-1 && type != gdcmExplicitVR) {
703 fp1 = fopen(fileName.c_str(),"wb");
705 printf("Failed to open (write) File [%s] \n",fileName.c_str());
709 if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
711 // writing Dicom File Preamble
712 filePreamble=new char[128];
713 memset(filePreamble,0,128);
714 fwrite(filePreamble,128,1,fp1);
715 fwrite("DICM",4,1,fp1);
716 delete[] filePreamble;
719 // --------------------------------------------------------------
720 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
722 // if recognition code tells us we dealt with a LibIDO image
723 // we reproduce on disk the switch between lineNumber and columnNumber
724 // just before writting ...
726 /// \todo the best trick would be *change* the recognition code
727 /// but pb expected if user deals with, e.g. COMPLEX images
729 std::string rows, columns;
730 if ( Header->GetFileType() == gdcmACR_LIBIDO){
731 rows = Header->GetEntryByNumber(0x0028, 0x0010);
732 columns = Header->GetEntryByNumber(0x0028, 0x0011);
733 Header->SetEntryByNumber(columns, 0x0028, 0x0010);
734 Header->SetEntryByNumber(rows , 0x0028, 0x0011);
736 // ----------------- End of Special Patch ----------------
738 /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
740 guint16 grPixel =Header->GetGrPixel();
741 guint16 numPixel=Header->GetNumPixel();;
743 // Update Pixel Data Length
744 // the *last* of the (GrPixel, NumPixel), if many.
746 TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel);
747 TagDocEntryHT::iterator p2;
748 gdcmDocEntry *PixelElement;
750 IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym
752 if (Header->GetEntry().count(key) == 1) // only the first is significant
753 p2=it.first; // iterator on the first (unique) synonym
755 p2=it.second;// iterator on the last synonym
757 PixelElement=p2->second; // H Table target column (2-nd col)
758 // PixelElement->SetPrintLevel(2);
759 // PixelElement->Print();
762 PixelElement->SetLength(lgrTotaleRaw);
763 else if (PixelRead==0)
764 PixelElement->SetLength(lgrTotale);
766 //PixelElement->SetPrintLevel(2);
767 //PixelElement->Print();
768 Header->Write(fp1, type);
770 // --------------------------------------------------------------
771 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
773 // ...and we restore the Header to be Dicom Compliant again
774 // just after writting
776 if (Header->GetFileType() == gdcmACR_LIBIDO){
777 Header->SetEntryByNumber(rows , 0x0028, 0x0010);
778 Header->SetEntryByNumber(columns, 0x0028, 0x0011);
780 // ----------------- End of Special Patch ----------------
782 // fwrite(PixelData, lgrTotale, 1, fp1); // should be useless, now
787 //-----------------------------------------------------------------------------
791 * \brief Swap the bytes, according to swap code.
792 * \warning not end user intended
793 * @param im area to deal with
794 * @param swap swap code
795 * @param lgr Area Length
796 * @param nb Pixels Bit number
798 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
815 for(i=0;i<lgr/2;i++) {
816 ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
817 | ((((unsigned short int *)im)[i])<<8);
822 printf("SWAP value (16 bits) not allowed : %d\n", swap);
832 for(i=0;i<lgr/4;i++) {
833 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 4321 */
834 fort =((unsigned long int *)im)[i]>>16;
835 fort= (fort>>8) | (fort<<8);
836 faible=(faible>>8) | (faible<<8);
838 ((unsigned long int *)im)[i]=(s32<<16)|fort;
843 for(i=0;i<lgr/4;i++) {
844 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 2143 */
845 fort=((unsigned long int *)im)[i]>>16;
846 fort= (fort>>8) | (fort<<8);
847 faible=(faible>>8) | (faible<<8);
849 ((unsigned long int *)im)[i]=(s32<<16)|faible;
854 for(i=0;i<lgr/4;i++) {
855 faible= ((unsigned long int *)im)[i]&0x0000ffff; /* 3412 */
856 fort=((unsigned long int *)im)[i]>>16;
858 ((unsigned long int *)im)[i]=(s32<<16)|fort;
863 printf("SWAP value (32 bits) not allowed : %d\n", swap);
870 * \brief Read pixel data from disk (optionaly decompressing) into the
871 * caller specified memory location.
872 * @param destination where the pixel data should be stored.
875 bool gdcmFile::ReadPixelData(void *destination) {
879 if ( !(fp=Header->OpenFile()))
881 if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
885 // ---------------------- Compacted File (12 Bits Per Pixel)
886 /* unpack 12 Bits pixels into 16 Bits pixels */
887 /* 2 pixels 12bit = [0xABCDEF] */
888 /* 2 pixels 16bit = [0x0ABD] + [0x0FCE] */
890 if (Header->GetBitsAllocated()==12) {
891 int nbPixels = Header->GetXSize() * Header->GetYSize();
892 unsigned char b0, b1, b2;
894 unsigned short int *pdestination = (unsigned short int*)destination;
895 for(int p=0;p<nbPixels;p+=2) {
899 //Two steps is necessary to please VC++
900 *pdestination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
901 /* A */ /* B */ /* D */
902 *pdestination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
903 /* F */ /* C */ /* E */
905 // Troubles expected on Big-Endian processors ?
912 // ---------------------- Uncompressed File
913 if ( !Header->IsDicomV3() ||
914 Header->IsImplicitVRLittleEndianTransferSyntax() ||
915 Header->IsExplicitVRLittleEndianTransferSyntax() ||
916 Header->IsExplicitVRBigEndianTransferSyntax() ||
917 Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
919 size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
920 if ( ItemRead != 1 ) {
929 // ---------------------- Run Length Encoding
930 if (Header->IsRLELossLessTransferSyntax()) {
931 bool res = (bool)gdcm_read_RLE_file (fp,destination);
936 // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000
938 std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
939 if (str_nb == GDCM_UNFOUND ) {
942 nb = atoi(str_nb.c_str() );
943 if (nb == 12) nb =16; // ?? 12 should be ACR-NEMA only ?
948 int taille = Header->GetXSize() * Header->GetYSize()
949 * Header->GetSamplesPerPixel();
950 long fragmentBegining; // for ftell, fseek
952 bool jpg2000 = Header->IsJPEG2000();
953 bool jpgLossless = Header->IsJPEGLossless();
956 guint16 ItemTagGr,ItemTagEl;
959 // Position on begining of Jpeg Pixels
961 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
962 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
963 if(Header->GetSwapCode()) {
964 ItemTagGr=Header->SwapShort(ItemTagGr);
965 ItemTagEl=Header->SwapShort(ItemTagEl);
968 if(Header->GetSwapCode())
969 ln=Header->SwapLong(ln); // Basic Offset Table Item length
972 // What is it used for ?!?
973 char *BasicOffsetTableItemValue = new char[ln+1];
974 fread(BasicOffsetTableItemValue,ln,1,fp);
977 // first Fragment initialisation
978 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
979 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
980 if(Header->GetSwapCode()) {
981 ItemTagGr=Header->SwapShort(ItemTagGr);
982 ItemTagEl=Header->SwapShort(ItemTagEl);
985 // parsing fragments until Sequence Delim. Tag found
986 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
987 // --- for each Fragment
990 if(Header->GetSwapCode())
991 ln=Header->SwapLong(ln); // Fragment Item length
993 fragmentBegining=ftell(fp);
995 if (jpg2000) { // JPEG 2000 : call to ???
997 res = (bool)gdcm_read_JPEG2000_file (fp,destination); // Not Yet written
999 } // ------------------------------------- endif (JPEG2000)
1001 else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
1003 JPEGLosslessDecodeImage (fp, // Reading Fragment pixels
1004 (unsigned short *)destination,
1005 Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(),
1007 res=1; // in order not to break the loop
1009 } // ------------------------------------- endif (JPEGLossless)
1011 else { // JPEG Lossy : call to IJG 6b
1013 if (Header->GetBitsStored() == 8) {
1014 res = (bool)gdcm_read_JPEG_file (fp,destination); // Reading Fragment pixels
1016 res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels
1018 } // ------------------------------------- endif (JPEGLossy)
1022 destination = (char *)destination + taille * nBytes; // location in user's memory
1023 // for next fragment (if any)
1025 fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start
1026 fseek(fp,ln,SEEK_CUR); // at the begining of next fragment
1028 ItemTagGr = ItemTagEl =0;
1029 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
1030 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
1031 if(Header->GetSwapCode()) {
1032 ItemTagGr=Header->SwapShort(ItemTagGr);
1033 ItemTagEl=Header->SwapShort(ItemTagEl);
1036 } // endWhile parsing fragments until Sequence Delim. Tag found
1038 Header->CloseFile();
1041 //-----------------------------------------------------------------------------