1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/12/16 13:46:37 $
7 Version: $Revision: 1.179 $
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"
24 #include "gdcmHeader.h"
25 #include "gdcmPixelReadConvert.h"
26 #include "gdcmPixelWriteConvert.h"
27 #include "gdcmDocEntryArchive.h"
33 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
35 //-------------------------------------------------------------------------
36 // Constructor / Destructor
38 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
39 * file (Header only deals with the ... header)
40 * Opens (in read only and when possible) an existing file and checks
41 * for DICOM compliance. Returns NULL on failure.
42 * It will be up to the user to load the pixels into memory
43 * (see GetImageData, GetImageDataRaw)
44 * \note the in-memory representation of all available tags found in
45 * the DICOM header is post-poned to first header information access.
46 * This avoid a double parsing of public part of the header when
47 * one sets an a posteriori shadow dictionary (efficiency can be
48 * seen as a side effect).
52 HeaderInternal = new Header( );
58 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
59 * file (Header only deals with the ... header)
60 * Opens (in read only and when possible) an existing file and checks
61 * for DICOM compliance. Returns NULL on failure.
62 * It will be up to the user to load the pixels into memory
63 * (see GetImageData, GetImageDataRaw)
64 * \note the in-memory representation of all available tags found in
65 * the DICOM header is post-poned to first header information access.
66 * This avoid a double parsing of public part of the header when
67 * user sets an a posteriori shadow dictionary (efficiency can be
68 * seen as a side effect).
69 * @param header already built Header
71 File::File(Header *header)
73 HeaderInternal = header;
79 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
80 * file (Header only deals with the ... header)
81 * Opens (in read only and when possible) an existing file and checks
82 * for DICOM compliance. Returns NULL on failure.
83 * It will be up to the user to load the pixels into memory
84 * (see GetImageData, GetImageDataRaw)
85 * \note the in-memory representation of all available tags found in
86 * the DICOM header is post-poned to first header information access.
87 * This avoid a double parsing of public part of the header when
88 * one sets an a posteriori shadow dictionary (efficiency can be
89 * seen as a side effect).
90 * @param filename file to be opened for parsing
92 File::File(std::string const & filename )
94 HeaderInternal = new Header( filename );
100 * \brief canonical destructor
101 * \note If the Header was created by the File constructor,
102 * it is destroyed by the File
106 if( PixelReadConverter )
108 delete PixelReadConverter;
110 if( PixelWriteConverter )
112 delete PixelWriteConverter;
121 delete HeaderInternal;
126 //-----------------------------------------------------------------------------
128 void File::Print(std::ostream &os)
130 HeaderInternal->SetPrintLevel(PrintLevel);
131 HeaderInternal->Print(os);
133 PixelReadConverter->SetPrintLevel(PrintLevel);
134 PixelReadConverter->Print(os);
137 //-----------------------------------------------------------------------------
140 * \brief Get the size of the image data
142 * If the image can be RGB (with a lut or by default), the size
143 * corresponds to the RGB image
144 * @return The image size
146 size_t File::GetImageDataSize()
148 if ( PixelWriteConverter->GetUserData() )
150 return PixelWriteConverter->GetUserDataSize();
153 return PixelReadConverter->GetRGBSize();
157 * \brief Get the size of the image data
159 * If the image can be RGB by transformation in a LUT, this
160 * transformation isn't considered
161 * @return The raw image size
163 size_t File::GetImageDataRawSize()
165 if ( PixelWriteConverter->GetUserData() )
167 return PixelWriteConverter->GetUserDataSize();
170 return PixelReadConverter->GetRawSize();
174 * \brief - Allocates necessary memory,
175 * - Reads the pixels from disk (uncompress if necessary),
176 * - Transforms YBR pixels, if any, into RGB pixels
177 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
178 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
179 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
180 * @return Pointer to newly allocated pixel data.
181 * NULL if alloc fails
183 uint8_t* File::GetImageData()
185 if ( PixelWriteConverter->GetUserData() )
187 return PixelWriteConverter->GetUserData();
192 // If the decompression failed nothing can be done.
196 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
198 return PixelReadConverter->GetRGB();
202 // When no LUT or LUT conversion fails, return the Raw
203 return PixelReadConverter->GetRaw();
208 * \brief Allocates necessary memory,
209 * Transforms YBR pixels (if any) into RGB pixels
210 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
211 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
212 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
213 * @return Pointer to newly allocated pixel data.
214 * \ NULL if alloc fails
216 uint8_t* File::GetImageDataRaw ()
223 * Read the pixels from disk (uncompress if necessary),
224 * Transforms YBR pixels, if any, into RGB pixels
225 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
226 * Transforms single Grey plane + 3 Palettes into a RGB Plane
227 * Copies at most MaxSize bytes of pixel data to caller allocated
229 * \warning This function allows people that want to build a volume
230 * from an image stack *not to* have, first to get the image pixels,
231 * and then move them to the volume area.
232 * It's absolutely useless for any VTK user since vtk chooses
233 * to invert the lines of an image, that is the last line comes first
234 * (for some axis related reasons?). Hence he will have
235 * to load the image line by line, starting from the end.
236 * VTK users have to call GetImageData
238 * @param destination Address (in caller's memory space) at which the
239 * pixel data should be copied
240 * @param maxSize Maximum number of bytes to be copied. When MaxSize
241 * is not sufficient to hold the pixel data the copy is not
242 * executed (i.e. no partial copy).
243 * @return On success, the number of bytes actually copied. Zero on
244 * failure e.g. MaxSize is lower than necessary.
246 size_t File::GetImageDataIntoVector (void* destination, size_t maxSize)
250 // If the decompression failed nothing can be done.
254 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
256 if ( PixelReadConverter->GetRGBSize() > maxSize )
258 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
259 "than caller's expected MaxSize");
263 (void*)PixelReadConverter->GetRGB(),
264 PixelReadConverter->GetRGBSize() );
265 return PixelReadConverter->GetRGBSize();
268 // Either no LUT conversion necessary or LUT conversion failed
269 if ( PixelReadConverter->GetRawSize() > maxSize )
271 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
272 "than caller's expected MaxSize");
276 (void*)PixelReadConverter->GetRaw(),
277 PixelReadConverter->GetRawSize() );
278 return PixelReadConverter->GetRawSize();
282 * \brief Points the internal pointer to the callers inData
283 * image representation, BUT WITHOUT COPYING THE DATA.
284 * 'image' Pixels are presented as C-like 2D arrays : line per line.
285 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
286 * \warning Since the pixels are not copied, it is the caller's responsability
287 * not to deallocate it's data before gdcm uses them (e.g. with
288 * the Write() method.
289 * @param inData user supplied pixel area
290 * @param expectedSize total image size, in Bytes
294 void File::SetImageData(uint8_t* inData, size_t expectedSize)
296 SetUserData(inData,expectedSize);
300 * \brief Set the image datas defined by the user
301 * \warning When writting the file, this datas are get as default datas to write
303 void File::SetUserData(uint8_t* data, size_t expectedSize)
305 PixelWriteConverter->SetUserData(data,expectedSize);
309 * \brief Get the image datas defined by the user
310 * \warning When writting the file, this datas are get as default datas to write
312 uint8_t* File::GetUserData()
314 return PixelWriteConverter->GetUserData();
318 * \brief Get the image data size defined by the user
319 * \warning When writting the file, this datas are get as default datas to write
321 size_t File::GetUserDataSize()
323 return PixelWriteConverter->GetUserDataSize();
327 * \brief Get the image datas from the file.
328 * If a LUT is found, the datas are expanded to be RGB
330 uint8_t* File::GetRGBData()
332 return PixelReadConverter->GetRGB();
336 * \brief Get the image data size from the file.
337 * If a LUT is found, the datas are expanded to be RGB
339 size_t File::GetRGBDataSize()
341 return PixelReadConverter->GetRGBSize();
345 * \brief Get the image datas from the file.
346 * If a LUT is found, the datas are not expanded !
348 uint8_t* File::GetRawData()
350 return PixelReadConverter->GetRaw();
354 * \brief Get the image data size from the file.
355 * If a LUT is found, the datas are not expanded !
357 size_t File::GetRawDataSize()
359 return PixelReadConverter->GetRawSize();
363 * \brief Writes on disk A SINGLE Dicom file
364 * NO test is performed on processor "Endiannity".
365 * It's up to the user to call his Reader properly
366 * @param fileName name of the file to be created
367 * (any already existing file is over written)
368 * @return false if write fails
371 bool File::WriteRawData(std::string const & fileName)
373 std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
376 dbg.Verbose(2, "Fail to open (write) file:", fileName.c_str());
380 if(PixelWriteConverter->GetUserData())
381 fp1.write((char*)PixelWriteConverter->GetUserData(), PixelWriteConverter->GetUserDataSize());
382 else if(PixelReadConverter->GetRGB())
383 fp1.write((char*)PixelReadConverter->GetRGB(), PixelReadConverter->GetRGBSize());
384 else if(PixelReadConverter->GetRaw())
385 fp1.write((char*)PixelReadConverter->GetRaw(), PixelReadConverter->GetRawSize());
393 * \brief Writes on disk A SINGLE Dicom file,
394 * using the Implicit Value Representation convention
395 * NO test is performed on processor "Endiannity".
396 * @param fileName name of the file to be created
397 * (any already existing file is overwritten)
398 * @return false if write fails
401 bool File::WriteDcmImplVR (std::string const & fileName)
403 SetWriteTypeToDcmImplVR();
404 return Write(fileName);
408 * \brief Writes on disk A SINGLE Dicom file,
409 * using the Explicit Value Representation convention
410 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
411 * (any already existing file is overwritten)
412 * @return false if write fails
415 bool File::WriteDcmExplVR (std::string const & fileName)
417 SetWriteTypeToDcmExplVR();
418 return Write(fileName);
422 * \brief Writes on disk A SINGLE Dicom file,
423 * using the ACR-NEMA convention
424 * NO test is performed on processor "Endiannity".
425 * (a l'attention des logiciels cliniques
426 * qui ne prennent en entrée QUE des images ACR ...
427 * \warning if a DICOM_V3 header is supplied,
428 * groups < 0x0008 and shadow groups are ignored
429 * \warning NO TEST is performed on processor "Endiannity".
430 * @param fileName name of the file to be created
431 * (any already existing file is overwritten)
432 * @return false if write fails
435 bool File::WriteAcr (std::string const & fileName)
438 return Write(fileName);
441 bool File::Write(std::string const& fileName)
443 return WriteBase(fileName);
446 bool File::SetEntryByNumber(std::string const& content,
447 uint16_t group, uint16_t element)
449 return HeaderInternal->SetEntryByNumber(content,group,element);
452 bool File::SetEntryByNumber(uint8_t* content, int lgth,
453 uint16_t group, uint16_t element)
455 return HeaderInternal->SetEntryByNumber(content,lgth,group,element);
458 bool File::ReplaceOrCreateByNumber(std::string const& content,
459 uint16_t group, uint16_t element)
461 return HeaderInternal->ReplaceOrCreateByNumber(content,group,element) != NULL;
464 bool File::ReplaceOrCreateByNumber(uint8_t* binArea, int lgth,
465 uint16_t group, uint16_t element)
467 return HeaderInternal->ReplaceOrCreateByNumber(binArea,lgth,group,element) != NULL;
471 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
473 uint8_t* File::GetLutRGBA()
475 return PixelReadConverter->GetLutRGBA();
478 //-----------------------------------------------------------------------------
481 * \brief NOT a end user inteded function
482 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
483 * @param fileName name of the file to be created
484 * (any already existing file is overwritten)
485 * @param type file type (ExplicitVR, ImplicitVR, ...)
486 * @return false if write fails
488 bool File::WriteBase (std::string const & fileName)
493 SetWriteFileTypeToImplicitVR();
496 SetWriteFileTypeToExplicitVR();
500 SetWriteFileTypeToACR();
503 SetWriteFileTypeToExplicitVR();
506 // --------------------------------------------------------------
507 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
509 // if recognition code tells us we dealt with a LibIDO image
510 // we reproduce on disk the switch between lineNumber and columnNumber
511 // just before writting ...
512 /// \todo the best trick would be *change* the recognition code
513 /// but pb expected if user deals with, e.g. COMPLEX images
514 if( WriteType == ACR_LIBIDO )
520 SetWriteToNoLibido();
522 // ----------------- End of Special Patch ----------------
534 bool check = CheckWriteIntegrity();
537 check = HeaderInternal->Write(fileName,WriteType);
541 RestoreWriteFileType();
543 // --------------------------------------------------------------
544 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
546 // ...and we restore the Header to be Dicom Compliant again
547 // just after writting
548 RestoreWriteOfLibido();
549 // ----------------- End of Special Patch ----------------
555 * \brief Check the write integrity
557 * The tests made are :
558 * - verify the size of the image to write with the possible write
559 * when the user set an image data
560 * @return true if the check successfulls
562 bool File::CheckWriteIntegrity()
564 if(PixelWriteConverter->GetUserData())
566 int numberBitsAllocated = HeaderInternal->GetBitsAllocated();
567 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
569 numberBitsAllocated = 16;
572 size_t decSize = HeaderInternal->GetXSize()
573 * HeaderInternal->GetYSize()
574 * HeaderInternal->GetZSize()
575 * ( numberBitsAllocated / 8 )
576 * HeaderInternal->GetSamplesPerPixel();
577 size_t rgbSize = decSize;
578 if( HeaderInternal->HasLUT() )
579 rgbSize = decSize * 3;
584 if( decSize!=PixelWriteConverter->GetUserDataSize() )
586 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect (Raw)");
587 //std::cerr << "File::CheckWriteIntegrity: Data size is incorrect (Raw)\n"
588 // << decSize << " / " << PixelWriteConverter->GetUserDataSize() << "\n";
593 if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
595 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect (RGB)");
596 //std::cerr << "File::CheckWriteIntegrity: Data size is incorrect (RGB)\n"
597 // << decSize << " / " << PixelWriteConverter->GetUserDataSize() << "\n";
607 void File::SetWriteToRaw()
609 if(HeaderInternal->GetNumberOfScalarComponents()==3 && !HeaderInternal->HasLUT())
615 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
616 if(HeaderInternal->HasLUT())
618 photInt->SetValue("PALETTE COLOR ");
622 photInt->SetValue("MONOCHROME1 ");
625 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
626 PixelReadConverter->GetRawSize());
628 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
629 pixel->SetValue(GDCM_BINLOADED);
630 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
631 pixel->SetLength(PixelWriteConverter->GetDataSize());
633 Archive->Push(photInt);
634 Archive->Push(pixel);
638 void File::SetWriteToRGB()
640 if(HeaderInternal->GetNumberOfScalarComponents()==3)
642 PixelReadConverter->BuildRGBImage();
644 ValEntry* spp = CopyValEntry(0x0028,0x0002);
647 ValEntry* planConfig = CopyValEntry(0x0028,0x0006);
648 planConfig->SetValue("0 ");
650 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
651 photInt->SetValue("RGB ");
653 if(PixelReadConverter->GetRGB())
655 PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
656 PixelReadConverter->GetRGBSize());
660 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
661 PixelReadConverter->GetRawSize());
664 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
665 pixel->SetValue(GDCM_BINLOADED);
666 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
667 pixel->SetLength(PixelWriteConverter->GetDataSize());
670 Archive->Push(planConfig);
671 Archive->Push(photInt);
672 Archive->Push(pixel);
675 Archive->Push(0x0028,0x1101);
676 Archive->Push(0x0028,0x1102);
677 Archive->Push(0x0028,0x1103);
678 Archive->Push(0x0028,0x1201);
679 Archive->Push(0x0028,0x1202);
680 Archive->Push(0x0028,0x1203);
683 // Thus, we have a RGB image and the bits allocated = 24 and
684 // samples per pixels = 1 (in the read file)
685 if(HeaderInternal->GetBitsAllocated()==24)
687 ValEntry* bitsAlloc = CopyValEntry(0x0028,0x0100);
688 bitsAlloc->SetValue("8 ");
690 ValEntry* bitsStored = CopyValEntry(0x0028,0x0101);
691 bitsStored->SetValue("8 ");
693 ValEntry* highBit = CopyValEntry(0x0028,0x0102);
694 highBit->SetValue("7 ");
696 Archive->Push(bitsAlloc);
697 Archive->Push(bitsStored);
698 Archive->Push(highBit);
707 void File::RestoreWrite()
709 Archive->Restore(0x0028,0x0002);
710 Archive->Restore(0x0028,0x0004);
711 Archive->Restore(0x0028,0x0006);
712 Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
714 // For old ACR-NEMA (24 bits problem)
715 Archive->Restore(0x0028,0x0100);
716 Archive->Restore(0x0028,0x0101);
717 Archive->Restore(0x0028,0x0102);
720 Archive->Restore(0x0028,0x1101);
721 Archive->Restore(0x0028,0x1102);
722 Archive->Restore(0x0028,0x1103);
723 Archive->Restore(0x0028,0x1201);
724 Archive->Restore(0x0028,0x1202);
725 Archive->Restore(0x0028,0x1203);
728 void File::SetWriteFileTypeToACR()
730 Archive->Push(0x0002,0x0010);
733 void File::SetWriteFileTypeToExplicitVR()
735 std::string ts = Util::DicomString(
736 Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
738 ValEntry* tss = CopyValEntry(0x0002,0x0010);
744 void File::SetWriteFileTypeToImplicitVR()
746 std::string ts = Util::DicomString(
747 Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
749 ValEntry* tss = CopyValEntry(0x0002,0x0010);
755 void File::RestoreWriteFileType()
757 Archive->Restore(0x0002,0x0010);
760 void File::SetWriteToLibido()
762 ValEntry *oldRow = dynamic_cast<ValEntry *>
763 (HeaderInternal->GetDocEntryByNumber(0x0028, 0x0010));
764 ValEntry *oldCol = dynamic_cast<ValEntry *>
765 (HeaderInternal->GetDocEntryByNumber(0x0028, 0x0011));
767 if( oldRow && oldCol )
769 std::string rows, columns;
771 ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
772 ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
774 newRow->Copy(oldCol);
775 newCol->Copy(oldRow);
777 newRow->SetValue(oldCol->GetValue());
778 newCol->SetValue(oldRow->GetValue());
780 Archive->Push(newRow);
781 Archive->Push(newCol);
784 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
785 libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
786 Archive->Push(libidoCode);
789 void File::SetWriteToNoLibido()
791 ValEntry *recCode = dynamic_cast<ValEntry *>
792 (HeaderInternal->GetDocEntryByNumber(0x0008,0x0010));
795 if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
797 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
798 libidoCode->SetValue("");
799 Archive->Push(libidoCode);
804 void File::RestoreWriteOfLibido()
806 Archive->Restore(0x0028,0x0010);
807 Archive->Restore(0x0028,0x0011);
808 Archive->Restore(0x0008,0x0010);
811 ValEntry* File::CopyValEntry(uint16_t group,uint16_t element)
813 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
818 newE = new ValEntry(oldE->GetDictEntry());
823 newE = GetHeader()->NewValEntryByNumber(group,element);
829 BinEntry* File::CopyBinEntry(uint16_t group,uint16_t element)
831 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
836 newE = new BinEntry(oldE->GetDictEntry());
841 newE = GetHeader()->NewBinEntryByNumber(group,element);
847 //-----------------------------------------------------------------------------
850 * \brief Factorization for various forms of constructors.
852 void File::Initialise()
854 WriteMode = WMODE_RAW;
855 WriteType = ExplicitVR;
857 PixelReadConverter = new PixelReadConvert;
858 PixelWriteConverter = new PixelWriteConvert;
859 Archive = new DocEntryArchive( HeaderInternal );
861 if ( HeaderInternal->IsReadable() )
863 PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
867 uint8_t* File::GetRaw()
869 uint8_t* raw = PixelReadConverter->GetRaw();
872 // The Raw image migth not be loaded yet:
873 std::ifstream* fp = HeaderInternal->OpenFile();
874 PixelReadConverter->ReadAndDecompressPixelData( fp );
876 HeaderInternal->CloseFile();
878 raw = PixelReadConverter->GetRaw();
881 dbg.Verbose(0, "File::GetRaw: read/decompress of "
882 "pixel data apparently went wrong.");
890 //-----------------------------------------------------------------------------
893 //-----------------------------------------------------------------------------
894 } // end namespace gdcm