1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/12/10 13:49:07 $
7 Version: $Revision: 1.175 $
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 //-----------------------------------------------------------------------------
129 //-----------------------------------------------------------------------------
132 * \brief Get the size of the image data
134 * If the image can be RGB (with a lut or by default), the size
135 * corresponds to the RGB image
136 * @return The image size
138 size_t File::GetImageDataSize()
140 if ( PixelWriteConverter->GetUserData() )
142 return PixelWriteConverter->GetUserDataSize();
145 return PixelReadConverter->GetRGBSize();
149 * \brief Get the size of the image data
151 * If the image can be RGB by transformation in a LUT, this
152 * transformation isn't considered
153 * @return The raw image size
155 size_t File::GetImageDataRawSize()
157 if ( PixelWriteConverter->GetUserData() )
159 return PixelWriteConverter->GetUserDataSize();
162 return PixelReadConverter->GetRawSize();
166 * \brief - Allocates necessary memory,
167 * - Reads the pixels from disk (uncompress if necessary),
168 * - Transforms YBR pixels, if any, into RGB pixels
169 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
170 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
171 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
172 * @return Pointer to newly allocated pixel data.
173 * NULL if alloc fails
175 uint8_t* File::GetImageData()
177 if ( PixelWriteConverter->GetUserData() )
179 return PixelWriteConverter->GetUserData();
184 // If the decompression failed nothing can be done.
188 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
190 return PixelReadConverter->GetRGB();
194 // When no LUT or LUT conversion fails, return the Raw
195 return PixelReadConverter->GetRaw();
200 * \brief Allocates necessary memory,
201 * Transforms YBR pixels (if any) into RGB pixels
202 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
203 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
204 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
205 * @return Pointer to newly allocated pixel data.
206 * \ NULL if alloc fails
208 uint8_t* File::GetImageDataRaw ()
215 * Read the pixels from disk (uncompress if necessary),
216 * Transforms YBR pixels, if any, into RGB pixels
217 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
218 * Transforms single Grey plane + 3 Palettes into a RGB Plane
219 * Copies at most MaxSize bytes of pixel data to caller allocated
221 * \warning This function allows people that want to build a volume
222 * from an image stack *not to* have, first to get the image pixels,
223 * and then move them to the volume area.
224 * It's absolutely useless for any VTK user since vtk chooses
225 * to invert the lines of an image, that is the last line comes first
226 * (for some axis related reasons?). Hence he will have
227 * to load the image line by line, starting from the end.
228 * VTK users have to call GetImageData
230 * @param destination Address (in caller's memory space) at which the
231 * pixel data should be copied
232 * @param maxSize Maximum number of bytes to be copied. When MaxSize
233 * is not sufficient to hold the pixel data the copy is not
234 * executed (i.e. no partial copy).
235 * @return On success, the number of bytes actually copied. Zero on
236 * failure e.g. MaxSize is lower than necessary.
238 size_t File::GetImageDataIntoVector (void* destination, size_t maxSize)
242 // If the decompression failed nothing can be done.
246 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
248 if ( PixelReadConverter->GetRGBSize() > maxSize )
250 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
251 "than caller's expected MaxSize");
255 (void*)PixelReadConverter->GetRGB(),
256 PixelReadConverter->GetRGBSize() );
257 return PixelReadConverter->GetRGBSize();
260 // Either no LUT conversion necessary or LUT conversion failed
261 if ( PixelReadConverter->GetRawSize() > maxSize )
263 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
264 "than caller's expected MaxSize");
268 (void*)PixelReadConverter->GetRaw(),
269 PixelReadConverter->GetRawSize() );
270 return PixelReadConverter->GetRawSize();
274 * \brief Points the internal pointer to the callers inData
275 * image representation, BUT WITHOUT COPYING THE DATA.
276 * 'image' Pixels are presented as C-like 2D arrays : line per line.
277 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
278 * \warning Since the pixels are not copied, it is the caller's responsability
279 * not to deallocate it's data before gdcm uses them (e.g. with
280 * the Write() method.
281 * @param inData user supplied pixel area
282 * @param expectedSize total image size, in Bytes
286 void File::SetImageData(uint8_t* inData, size_t expectedSize)
288 SetUserData(inData,expectedSize);
292 * \brief Set the image datas defined by the user
293 * \warning When writting the file, this datas are get as default datas to write
295 void File::SetUserData(uint8_t* data, size_t expectedSize)
297 PixelWriteConverter->SetUserData(data,expectedSize);
301 * \brief Get the image datas defined by the user
302 * \warning When writting the file, this datas are get as default datas to write
304 uint8_t* File::GetUserData()
306 return PixelWriteConverter->GetUserData();
310 * \brief Get the image data size defined by the user
311 * \warning When writting the file, this datas are get as default datas to write
313 size_t File::GetUserDataSize()
315 return PixelWriteConverter->GetUserDataSize();
319 * \brief Get the image datas from the file.
320 * If a LUT is found, the datas are expanded to be RGB
322 uint8_t* File::GetRGBData()
324 return PixelReadConverter->GetRGB();
328 * \brief Get the image data size from the file.
329 * If a LUT is found, the datas are expanded to be RGB
331 size_t File::GetRGBDataSize()
333 return PixelReadConverter->GetRGBSize();
337 * \brief Get the image datas from the file.
338 * If a LUT is found, the datas are not expanded !
340 uint8_t* File::GetRawData()
342 return PixelReadConverter->GetRaw();
346 * \brief Get the image data size from the file.
347 * If a LUT is found, the datas are not expanded !
349 size_t File::GetRawDataSize()
351 return PixelReadConverter->GetRawSize();
355 * \brief Writes on disk A SINGLE Dicom file
356 * NO test is performed on processor "Endiannity".
357 * It's up to the user to call his Reader properly
358 * @param fileName name of the file to be created
359 * (any already existing file is over written)
360 * @return false if write fails
363 bool File::WriteRawData(std::string const & fileName)
365 std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
368 dbg.Verbose(2, "Fail to open (write) file:", fileName.c_str());
372 if(PixelWriteConverter->GetUserData())
373 fp1.write((char*)PixelWriteConverter->GetUserData(), PixelWriteConverter->GetUserDataSize());
374 else if(PixelReadConverter->GetRGB())
375 fp1.write((char*)PixelReadConverter->GetRGB(), PixelReadConverter->GetRGBSize());
376 else if(PixelReadConverter->GetRaw())
377 fp1.write((char*)PixelReadConverter->GetRaw(), PixelReadConverter->GetRawSize());
385 * \brief Writes on disk A SINGLE Dicom file,
386 * using the Implicit Value Representation convention
387 * NO test is performed on processor "Endiannity".
388 * @param fileName name of the file to be created
389 * (any already existing file is overwritten)
390 * @return false if write fails
393 bool File::WriteDcmImplVR (std::string const & fileName)
395 SetWriteTypeToDcmImplVR();
396 return Write(fileName);
400 * \brief Writes on disk A SINGLE Dicom file,
401 * using the Explicit Value Representation convention
402 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
403 * (any already existing file is overwritten)
404 * @return false if write fails
407 bool File::WriteDcmExplVR (std::string const & fileName)
409 SetWriteTypeToDcmExplVR();
410 return Write(fileName);
414 * \brief Writes on disk A SINGLE Dicom file,
415 * using the ACR-NEMA convention
416 * NO test is performed on processor "Endiannity".
417 * (a l'attention des logiciels cliniques
418 * qui ne prennent en entrée QUE des images ACR ...
419 * \warning if a DICOM_V3 header is supplied,
420 * groups < 0x0008 and shadow groups are ignored
421 * \warning NO TEST is performed on processor "Endiannity".
422 * @param fileName name of the file to be created
423 * (any already existing file is overwritten)
424 * @return false if write fails
427 bool File::WriteAcr (std::string const & fileName)
430 return Write(fileName);
433 bool File::Write(std::string const& fileName)
435 return WriteBase(fileName);
438 bool File::SetEntryByNumber(std::string const& content,
439 uint16_t group, uint16_t element)
441 return HeaderInternal->SetEntryByNumber(content,group,element);
444 bool File::SetEntryByNumber(uint8_t* content, int lgth,
445 uint16_t group, uint16_t element)
447 return HeaderInternal->SetEntryByNumber(content,lgth,group,element);
450 bool File::ReplaceOrCreateByNumber(std::string const& content,
451 uint16_t group, uint16_t element)
453 return HeaderInternal->ReplaceOrCreateByNumber(content,group,element) != NULL;
457 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
459 uint8_t* File::GetLutRGBA()
461 return PixelReadConverter->GetLutRGBA();
464 //-----------------------------------------------------------------------------
467 * \brief NOT a end user inteded function
468 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
469 * @param fileName name of the file to be created
470 * (any already existing file is overwritten)
471 * @param type file type (ExplicitVR, ImplicitVR, ...)
472 * @return false if write fails
474 bool File::WriteBase (std::string const & fileName)
479 SetWriteFileTypeToImplicitVR();
482 SetWriteFileTypeToExplicitVR();
486 SetWriteFileTypeToACR();
489 SetWriteFileTypeToExplicitVR();
492 // --------------------------------------------------------------
493 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
495 // if recognition code tells us we dealt with a LibIDO image
496 // we reproduce on disk the switch between lineNumber and columnNumber
497 // just before writting ...
498 /// \todo the best trick would be *change* the recognition code
499 /// but pb expected if user deals with, e.g. COMPLEX images
500 if( WriteType == ACR_LIBIDO )
506 SetWriteToNoLibido();
508 // ----------------- End of Special Patch ----------------
520 bool check = CheckWriteIntegrity();
523 check = HeaderInternal->Write(fileName,WriteType);
527 RestoreWriteFileType();
529 // --------------------------------------------------------------
530 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
532 // ...and we restore the Header to be Dicom Compliant again
533 // just after writting
534 RestoreWriteOfLibido();
535 // ----------------- End of Special Patch ----------------
541 * \brief Check the write integrity
543 * The tests made are :
544 * - verify the size of the image to write with the possible write
545 * when the user set an image data
546 * @return true if the check successfulls
548 bool File::CheckWriteIntegrity()
550 if(PixelWriteConverter->GetUserData())
552 int numberBitsAllocated = HeaderInternal->GetBitsAllocated();
553 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
555 numberBitsAllocated = 16;
558 size_t decSize = HeaderInternal->GetXSize()
559 * HeaderInternal->GetYSize()
560 * HeaderInternal->GetZSize()
561 * ( numberBitsAllocated / 8 )
562 * HeaderInternal->GetSamplesPerPixel();
563 size_t rgbSize = decSize;
564 if( HeaderInternal->HasLUT() )
565 rgbSize = decSize * 3;
570 if( decSize!=PixelWriteConverter->GetUserDataSize() )
572 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect (Raw)");
573 //std::cerr << "File::CheckWriteIntegrity: Data size is incorrect (Raw)\n"
574 // << decSize << " / " << PixelWriteConverter->GetUserDataSize() << "\n";
579 if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
581 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect (RGB)");
582 //std::cerr << "File::CheckWriteIntegrity: Data size is incorrect (RGB)\n"
583 // << decSize << " / " << PixelWriteConverter->GetUserDataSize() << "\n";
593 void File::SetWriteToRaw()
595 if(HeaderInternal->GetNumberOfScalarComponents()==3 && !HeaderInternal->HasLUT())
601 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
602 if(HeaderInternal->HasLUT())
604 photInt->SetValue("PALETTE COLOR ");
608 photInt->SetValue("MONOCHROME1 ");
611 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
612 PixelReadConverter->GetRawSize());
614 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
615 pixel->SetValue(GDCM_BINLOADED);
616 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
617 pixel->SetLength(PixelWriteConverter->GetDataSize());
619 Archive->Push(photInt);
620 Archive->Push(pixel);
624 void File::SetWriteToRGB()
626 if(HeaderInternal->GetNumberOfScalarComponents()==3)
628 PixelReadConverter->BuildRGBImage();
630 ValEntry* spp = CopyValEntry(0x0028,0x0002);
633 ValEntry* planConfig = CopyValEntry(0x0028,0x0006);
634 planConfig->SetValue("0 ");
636 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
637 photInt->SetValue("RGB ");
639 if(PixelReadConverter->GetRGB())
641 PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
642 PixelReadConverter->GetRGBSize());
646 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
647 PixelReadConverter->GetRawSize());
650 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
651 pixel->SetValue(GDCM_BINLOADED);
652 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
653 pixel->SetLength(PixelWriteConverter->GetDataSize());
656 Archive->Push(planConfig);
657 Archive->Push(photInt);
658 Archive->Push(pixel);
661 Archive->Push(0x0028,0x1101);
662 Archive->Push(0x0028,0x1102);
663 Archive->Push(0x0028,0x1103);
664 Archive->Push(0x0028,0x1201);
665 Archive->Push(0x0028,0x1202);
666 Archive->Push(0x0028,0x1203);
669 // Thus, we have a RGB image and the bits allocated = 24 and
670 // samples per pixels = 1 (in the read file)
671 if(HeaderInternal->GetBitsAllocated()==24)
673 ValEntry* bitsAlloc = CopyValEntry(0x0028,0x0100);
674 bitsAlloc->SetValue("8 ");
676 ValEntry* bitsStored = CopyValEntry(0x0028,0x0101);
677 bitsStored->SetValue("8 ");
679 ValEntry* highBit = CopyValEntry(0x0028,0x0102);
680 highBit->SetValue("7 ");
682 Archive->Push(bitsAlloc);
683 Archive->Push(bitsStored);
684 Archive->Push(highBit);
693 void File::RestoreWrite()
695 Archive->Restore(0x0028,0x0002);
696 Archive->Restore(0x0028,0x0004);
697 Archive->Restore(0x0028,0x0006);
698 Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
700 // For old ACR-NEMA (24 bits problem)
701 Archive->Restore(0x0028,0x0100);
702 Archive->Restore(0x0028,0x0101);
703 Archive->Restore(0x0028,0x0102);
706 Archive->Restore(0x0028,0x1101);
707 Archive->Restore(0x0028,0x1102);
708 Archive->Restore(0x0028,0x1103);
709 Archive->Restore(0x0028,0x1201);
710 Archive->Restore(0x0028,0x1202);
711 Archive->Restore(0x0028,0x1203);
714 void File::SetWriteFileTypeToACR()
716 Archive->Push(0x0002,0x0010);
719 void File::SetWriteFileTypeToExplicitVR()
721 std::string ts = Util::DicomString(
722 Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
724 ValEntry* tss = CopyValEntry(0x0002,0x0010);
730 void File::SetWriteFileTypeToImplicitVR()
732 std::string ts = Util::DicomString(
733 Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
735 ValEntry* tss = CopyValEntry(0x0002,0x0010);
739 void File::RestoreWriteFileType()
741 Archive->Restore(0x0002,0x0010);
744 void File::SetWriteToLibido()
746 ValEntry *oldRow = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0010));
747 ValEntry *oldCol = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0011));
749 if( oldRow && oldCol )
751 std::string rows, columns;
753 ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
754 ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
756 newRow->Copy(oldCol);
757 newCol->Copy(oldRow);
759 newRow->SetValue(oldCol->GetValue());
760 newCol->SetValue(oldRow->GetValue());
762 Archive->Push(newRow);
763 Archive->Push(newCol);
766 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
767 libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
768 Archive->Push(libidoCode);
771 void File::SetWriteToNoLibido()
773 ValEntry *recCode = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0008,0x0010));
776 if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
778 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
779 libidoCode->SetValue("");
780 Archive->Push(libidoCode);
785 void File::RestoreWriteOfLibido()
787 Archive->Restore(0x0028,0x0010);
788 Archive->Restore(0x0028,0x0011);
789 Archive->Restore(0x0008,0x0010);
792 ValEntry* File::CopyValEntry(uint16_t group,uint16_t element)
794 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
799 newE = new ValEntry(oldE->GetDictEntry());
804 newE = GetHeader()->NewValEntryByNumber(group,element);
810 BinEntry* File::CopyBinEntry(uint16_t group,uint16_t element)
812 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
817 newE = new BinEntry(oldE->GetDictEntry());
822 newE = GetHeader()->NewBinEntryByNumber(group,element);
828 //-----------------------------------------------------------------------------
831 * \brief Factorization for various forms of constructors.
833 void File::Initialise()
835 WriteMode = WMODE_RAW;
836 WriteType = ExplicitVR;
838 PixelReadConverter = new PixelReadConvert;
839 PixelWriteConverter = new PixelWriteConvert;
840 Archive = new DocEntryArchive( HeaderInternal );
842 if ( HeaderInternal->IsReadable() )
844 PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
848 uint8_t* File::GetRaw()
850 uint8_t* raw = PixelReadConverter->GetRaw();
853 // The Raw image migth not be loaded yet:
854 std::ifstream* fp = HeaderInternal->OpenFile();
855 PixelReadConverter->ReadAndDecompressPixelData( fp );
857 HeaderInternal->CloseFile();
859 raw = PixelReadConverter->GetRaw();
862 dbg.Verbose(0, "File::GetRaw: read/decompress of "
863 "pixel data apparently went wrong.");
871 //-----------------------------------------------------------------------------
874 //-----------------------------------------------------------------------------
875 } // end namespace gdcm