1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/12/03 10:21:54 $
7 Version: $Revision: 1.168 $
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.html 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 "gdcmDocument.h"
21 #include "gdcmDebug.h"
23 #include "gdcmBinEntry.h"
28 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
30 //-------------------------------------------------------------------------
31 // Constructor / Destructor
33 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
34 * file (Header only deals with the ... header)
35 * Opens (in read only and when possible) an existing file and checks
36 * for DICOM compliance. Returns NULL on failure.
37 * It will be up to the user to load the pixels into memory
38 * (see GetImageData, GetImageDataRaw)
39 * \note the in-memory representation of all available tags found in
40 * the DICOM header is post-poned to first header information access.
41 * This avoid a double parsing of public part of the header when
42 * user sets an a posteriori shadow dictionary (efficiency can be
43 * seen as a side effect).
44 * @param header already built Header
46 File::File(Header *header)
48 HeaderInternal = header;
54 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
55 * file (Header only deals with the ... header)
56 * Opens (in read only and when possible) an existing file and checks
57 * for DICOM compliance. Returns NULL on failure.
58 * It will be up to the user to load the pixels into memory
59 * (see GetImageData, GetImageDataRaw)
60 * \note the in-memory representation of all available tags found in
61 * the DICOM header is post-poned to first header information access.
62 * This avoid a double parsing of public part of the header when
63 * one sets an a posteriori shadow dictionary (efficiency can be
64 * seen as a side effect).
65 * @param filename file to be opened for parsing
67 File::File(std::string const & filename )
69 HeaderInternal = new Header( filename );
75 * \brief Factorization for various forms of constructors.
77 void File::Initialise()
79 WriteMode = WMODE_DECOMPRESSED;
80 WriteType = WTYPE_IMPL_VR;
82 PixelReadConverter = new PixelReadConvert;
83 Archive = new DocEntryArchive( HeaderInternal );
85 if ( HeaderInternal->IsReadable() )
87 PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
95 * \brief canonical destructor
96 * \note If the Header was created by the File constructor,
97 * it is destroyed by the File
101 if( PixelReadConverter )
103 delete PixelReadConverter;
112 delete HeaderInternal;
117 //-----------------------------------------------------------------------------
120 //-----------------------------------------------------------------------------
123 * \brief Get the size of the image data
125 * If the image can be RGB (with a lut or by default), the size
126 * corresponds to the RGB image
127 * @return The image size
129 size_t File::GetImageDataSize()
131 return PixelReadConverter->GetRGBSize();
135 * \brief Get the size of the image data
137 * If the image can be RGB by transformation in a LUT, this
138 * transformation isn't considered
139 * @return The raw image size
141 size_t File::GetImageDataRawSize()
143 return PixelReadConverter->GetDecompressedSize();
147 * \brief - Allocates necessary memory,
148 * - Reads the pixels from disk (uncompress if necessary),
149 * - Transforms YBR pixels, if any, into RGB pixels
150 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
151 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
152 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
153 * @return Pointer to newly allocated pixel data.
154 * NULL if alloc fails
156 uint8_t* File::GetImageData()
158 if ( ! GetDecompressed() )
160 // If the decompression failed nothing can be done.
164 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
166 return PixelReadConverter->GetRGB();
170 // When no LUT or LUT conversion fails, return the decompressed
171 return PixelReadConverter->GetDecompressed();
177 * Read the pixels from disk (uncompress if necessary),
178 * Transforms YBR pixels, if any, into RGB pixels
179 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
180 * Transforms single Grey plane + 3 Palettes into a RGB Plane
181 * Copies at most MaxSize bytes of pixel data to caller allocated
183 * \warning This function allows people that want to build a volume
184 * from an image stack *not to* have, first to get the image pixels,
185 * and then move them to the volume area.
186 * It's absolutely useless for any VTK user since vtk chooses
187 * to invert the lines of an image, that is the last line comes first
188 * (for some axis related reasons?). Hence he will have
189 * to load the image line by line, starting from the end.
190 * VTK users have to call GetImageData
192 * @param destination Address (in caller's memory space) at which the
193 * pixel data should be copied
194 * @param maxSize Maximum number of bytes to be copied. When MaxSize
195 * is not sufficient to hold the pixel data the copy is not
196 * executed (i.e. no partial copy).
197 * @return On success, the number of bytes actually copied. Zero on
198 * failure e.g. MaxSize is lower than necessary.
200 size_t File::GetImageDataIntoVector (void* destination, size_t maxSize)
202 if ( ! GetDecompressed() )
204 // If the decompression failed nothing can be done.
208 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
210 if ( PixelReadConverter->GetRGBSize() > maxSize )
212 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
213 "than caller's expected MaxSize");
217 (void*)PixelReadConverter->GetRGB(),
218 PixelReadConverter->GetRGBSize() );
219 return PixelReadConverter->GetRGBSize();
222 // Either no LUT conversion necessary or LUT conversion failed
223 if ( PixelReadConverter->GetDecompressedSize() > maxSize )
225 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
226 "than caller's expected MaxSize");
230 (void*)PixelReadConverter->GetDecompressed(),
231 PixelReadConverter->GetDecompressedSize() );
232 return PixelReadConverter->GetDecompressedSize();
236 * \brief Allocates necessary memory,
237 * Transforms YBR pixels (if any) into RGB pixels
238 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
239 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
240 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
241 * @return Pointer to newly allocated pixel data.
242 * \ NULL if alloc fails
244 uint8_t* File::GetImageDataRaw ()
246 return GetDecompressed();
249 uint8_t* File::GetDecompressed()
251 uint8_t* decompressed = PixelReadConverter->GetDecompressed();
252 if ( ! decompressed )
254 // The decompressed image migth not be loaded yet:
255 std::ifstream* fp = HeaderInternal->OpenFile();
256 PixelReadConverter->ReadAndDecompressPixelData( fp );
258 HeaderInternal->CloseFile();
260 decompressed = PixelReadConverter->GetDecompressed();
261 if ( ! decompressed )
263 dbg.Verbose(0, "File::GetDecompressed: read/decompress of "
264 "pixel data apparently went wrong.");
273 * \brief Points the internal Pixel_Data pointer to the callers inData
274 * image representation, BUT WITHOUT COPYING THE DATA.
275 * 'image' Pixels are presented as C-like 2D arrays : line per line.
276 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
277 * \warning Since the pixels are not copied, it is the caller's responsability
278 * not to deallocate it's data before gdcm uses them (e.g. with
279 * the Write() method.
280 * @param inData user supplied pixel area
281 * @param expectedSize total image size, in Bytes
285 bool File::SetImageData(uint8_t* inData, size_t expectedSize)
287 // FIXME : if already allocated, memory leak !
289 ImageDataSize = expectedSize;
290 // FIXME : 7fe0, 0010 IS NOT set ...
295 * \brief Writes on disk A SINGLE Dicom file
296 * NO test is performed on processor "Endiannity".
297 * It's up to the user to call his Reader properly
298 * @param fileName name of the file to be created
299 * (any already existing file is over written)
300 * @return false if write fails
303 bool File::WriteRawData(std::string const & fileName)
305 std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
308 dbg.Verbose(2, "Fail to open (write) file:", fileName.c_str());
311 fp1.write((char*)Pixel_Data, ImageDataSize);
318 * \brief Writes on disk A SINGLE Dicom file,
319 * using the Implicit Value Representation convention
320 * NO test is performed on processor "Endiannity".
321 * @param fileName name of the file to be created
322 * (any already existing file is overwritten)
323 * @return false if write fails
326 bool File::WriteDcmImplVR (std::string const & fileName)
328 SetWriteTypeToDcmImplVR();
329 return Write(fileName);
333 * \brief Writes on disk A SINGLE Dicom file,
334 * using the Explicit Value Representation convention
335 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
336 * (any already existing file is overwritten)
337 * @return false if write fails
340 bool File::WriteDcmExplVR (std::string const & fileName)
342 SetWriteTypeToDcmExplVR();
343 return Write(fileName);
347 * \brief Writes on disk A SINGLE Dicom file,
348 * using the ACR-NEMA convention
349 * NO test is performed on processor "Endiannity".
350 * (a l'attention des logiciels cliniques
351 * qui ne prennent en entrée QUE des images ACR ...
352 * \warning if a DICOM_V3 header is supplied,
353 * groups < 0x0008 and shadow groups are ignored
354 * \warning NO TEST is performed on processor "Endiannity".
355 * @param fileName name of the file to be created
356 * (any already existing file is overwritten)
357 * @return false if write fails
360 bool File::WriteAcr (std::string const & fileName)
363 return Write(fileName);
366 bool File::Write(std::string const& fileName)
371 return WriteBase(fileName,ImplicitVR);
373 return WriteBase(fileName,ExplicitVR);
375 return WriteBase(fileName,ACR);
381 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
383 uint8_t* File::GetLutRGBA()
385 return PixelReadConverter->GetLutRGBA();
388 //-----------------------------------------------------------------------------
391 * \brief NOT a end user inteded function
392 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
393 * @param fileName name of the file to be created
394 * (any already existing file is overwritten)
395 * @param type file type (ExplicitVR, ImplicitVR, ...)
396 * @return false if write fails
398 bool File::WriteBase (std::string const & fileName, FileType type)
403 SetWriteFileTypeToImplicitVR();
406 SetWriteFileTypeToExplicitVR();
410 SetWriteFileTypeToACR();
413 SetWriteFileTypeToExplicitVR();
416 // --------------------------------------------------------------
417 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
419 // if recognition code tells us we dealt with a LibIDO image
420 // we reproduce on disk the switch between lineNumber and columnNumber
421 // just before writting ...
422 /// \todo the best trick would be *change* the recognition code
423 /// but pb expected if user deals with, e.g. COMPLEX images
424 if( type == ACR_LIBIDO )
430 SetWriteToNoLibido();
432 // ----------------- End of Special Patch ----------------
436 case WMODE_DECOMPRESSED :
437 SetWriteToDecompressed();
444 bool check = CheckWriteIntegrity();
447 check = HeaderInternal->Write(fileName,type);
451 RestoreWriteFileType();
453 // --------------------------------------------------------------
454 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
456 // ...and we restore the Header to be Dicom Compliant again
457 // just after writting
458 RestoreWriteOfLibido();
459 // ----------------- End of Special Patch ----------------
465 * \brief Check the write integrity
467 * The tests made are :
468 * - verify the size of the image to write with the possible write
469 * when the user set an image data
470 * @return true if the check successfulls
472 bool File::CheckWriteIntegrity()
476 int numberBitsAllocated = HeaderInternal->GetBitsAllocated();
477 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
479 numberBitsAllocated = 16;
482 size_t decSize = HeaderInternal->GetXSize()
483 * HeaderInternal->GetYSize()
484 * HeaderInternal->GetZSize()
485 * ( numberBitsAllocated / 8 )
486 * HeaderInternal->GetSamplesPerPixel();
487 size_t rgbSize = decSize;
488 if( HeaderInternal->HasLUT() )
489 rgbSize = decSize * 3;
493 case WMODE_DECOMPRESSED :
494 if( decSize!=ImageDataSize )
496 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect");
497 //std::cerr<<"Dec : "<<decSize<<" | "<<ImageDataSize<<std::endl;
502 if( rgbSize!=ImageDataSize )
504 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect");
505 //std::cerr<<"RGB : "<<decSize<<" | "<<ImageDataSize<<std::endl;
515 /*void File::SetWriteToNative()
519 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
520 pixel->SetValue(GDCM_BINLOADED);
521 pixel->SetBinArea(Pixel_Data,false);
522 pixel->SetLength(ImageDataSize);
524 Archive->Push(pixel);
528 void File::SetWriteToDecompressed()
530 if(HeaderInternal->GetNumberOfScalarComponents()==3 && !HeaderInternal->HasLUT())
536 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
537 if(HeaderInternal->HasLUT())
539 photInt->SetValue("PALETTE COLOR ");
540 photInt->SetLength(14);
544 photInt->SetValue("MONOCHROME1 ");
545 photInt->SetLength(12);
548 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
549 pixel->SetValue(GDCM_BINLOADED);
552 pixel->SetBinArea(Pixel_Data,false);
553 pixel->SetLength(ImageDataSize);
557 pixel->SetBinArea(PixelReadConverter->GetDecompressed(),false);
558 pixel->SetLength(PixelReadConverter->GetDecompressedSize());
561 Archive->Push(photInt);
562 Archive->Push(pixel);
566 void File::SetWriteToRGB()
568 if(HeaderInternal->GetNumberOfScalarComponents()==3)
570 PixelReadConverter->BuildRGBImage();
572 ValEntry* spp = CopyValEntry(0x0028,0x0002);
576 ValEntry* planConfig = CopyValEntry(0x0028,0x0006);
577 planConfig->SetValue("0 ");
578 planConfig->SetLength(2);
580 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
581 photInt->SetValue("RGB ");
582 photInt->SetLength(4);
584 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
585 pixel->SetValue(GDCM_BINLOADED);
588 pixel->SetBinArea(Pixel_Data,false);
589 pixel->SetLength(ImageDataSize);
591 else if(PixelReadConverter->GetRGB())
593 pixel->SetBinArea(PixelReadConverter->GetRGB(),false);
594 pixel->SetLength(PixelReadConverter->GetRGBSize());
596 else // Decompressed data
598 pixel->SetBinArea(PixelReadConverter->GetDecompressed(),false);
599 pixel->SetLength(PixelReadConverter->GetDecompressedSize());
603 Archive->Push(planConfig);
604 Archive->Push(photInt);
605 Archive->Push(pixel);
608 Archive->Push(0x0028,0x1101);
609 Archive->Push(0x0028,0x1102);
610 Archive->Push(0x0028,0x1103);
611 Archive->Push(0x0028,0x1201);
612 Archive->Push(0x0028,0x1202);
613 Archive->Push(0x0028,0x1203);
616 // Thus, we have a RGB image and the bits allocated = 24 and
617 // samples per pixels = 1 (in the read file)
618 if(HeaderInternal->GetBitsAllocated()==24)
620 ValEntry* bitsAlloc = CopyValEntry(0x0028,0x0100);
621 bitsAlloc->SetValue("8 ");
622 bitsAlloc->SetLength(2);
624 ValEntry* bitsStored = CopyValEntry(0x0028,0x0101);
625 bitsStored->SetValue("8 ");
626 bitsStored->SetLength(2);
628 ValEntry* highBit = CopyValEntry(0x0028,0x0102);
629 highBit->SetValue("7 ");
630 highBit->SetLength(2);
632 Archive->Push(bitsAlloc);
633 Archive->Push(bitsStored);
634 Archive->Push(highBit);
639 SetWriteToDecompressed();
643 void File::RestoreWrite()
645 Archive->Restore(0x0028,0x0002);
646 Archive->Restore(0x0028,0x0004);
647 Archive->Restore(0x0028,0x0006);
648 Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
650 // For old ACR-NEMA (24 bits problem)
651 Archive->Restore(0x0028,0x0100);
652 Archive->Restore(0x0028,0x0101);
653 Archive->Restore(0x0028,0x0102);
656 Archive->Restore(0x0028,0x1101);
657 Archive->Restore(0x0028,0x1102);
658 Archive->Restore(0x0028,0x1103);
659 Archive->Restore(0x0028,0x1201);
660 Archive->Restore(0x0028,0x1202);
661 Archive->Restore(0x0028,0x1203);
664 void File::SetWriteFileTypeToACR()
666 Archive->Push(0x0002,0x0010);
669 void File::SetWriteFileTypeToExplicitVR()
671 std::string ts = Util::DicomString(
672 Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
674 ValEntry* tss = CopyValEntry(0x0002,0x0010);
676 tss->SetLength(ts.length());
681 void File::SetWriteFileTypeToImplicitVR()
683 std::string ts = Util::DicomString(
684 Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
686 ValEntry* tss = CopyValEntry(0x0002,0x0010);
688 tss->SetLength(ts.length());
691 void File::RestoreWriteFileType()
693 Archive->Restore(0x0002,0x0010);
696 void File::SetWriteToLibido()
698 ValEntry *oldRow = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0010));
699 ValEntry *oldCol = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0011));
701 if( oldRow && oldCol )
703 std::string rows, columns;
705 ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
706 ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
708 newRow->Copy(oldCol);
709 newCol->Copy(oldRow);
711 newRow->SetValue(oldCol->GetValue());
712 newCol->SetValue(oldRow->GetValue());
714 Archive->Push(newRow);
715 Archive->Push(newCol);
718 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
719 libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
720 libidoCode->SetLength(10);
721 Archive->Push(libidoCode);
724 void File::SetWriteToNoLibido()
726 ValEntry *recCode = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0008,0x0010));
729 if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
731 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
732 libidoCode->SetValue("");
733 libidoCode->SetLength(0);
734 Archive->Push(libidoCode);
739 void File::RestoreWriteOfLibido()
741 Archive->Restore(0x0028,0x0010);
742 Archive->Restore(0x0028,0x0011);
743 Archive->Restore(0x0008,0x0010);
746 ValEntry* File::CopyValEntry(uint16_t group,uint16_t element)
748 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
753 newE = new ValEntry(oldE->GetDictEntry());
758 newE = GetHeader()->NewValEntryByNumber(group,element);
764 BinEntry* File::CopyBinEntry(uint16_t group,uint16_t element)
766 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
771 newE = new BinEntry(oldE->GetDictEntry());
776 newE = GetHeader()->NewBinEntryByNumber(group,element);
782 //-----------------------------------------------------------------------------
785 //-----------------------------------------------------------------------------
786 } // end namespace gdcm