1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2004/12/03 14:22:40 $
7 Version: $Revision: 1.170 $
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 = ImplicitVR;
82 PixelReadConverter = new PixelReadConvert;
83 PixelWriteConverter = new PixelWriteConvert;
84 Archive = new DocEntryArchive( HeaderInternal );
86 if ( HeaderInternal->IsReadable() )
88 PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
93 * \brief canonical destructor
94 * \note If the Header was created by the File constructor,
95 * it is destroyed by the File
99 if( PixelReadConverter )
101 delete PixelReadConverter;
103 if( PixelWriteConverter )
105 delete PixelWriteConverter;
114 delete HeaderInternal;
119 //-----------------------------------------------------------------------------
122 //-----------------------------------------------------------------------------
125 * \brief Get the size of the image data
127 * If the image can be RGB (with a lut or by default), the size
128 * corresponds to the RGB image
129 * @return The image size
131 size_t File::GetImageDataSize()
133 return PixelReadConverter->GetRGBSize();
137 * \brief Get the size of the image data
139 * If the image can be RGB by transformation in a LUT, this
140 * transformation isn't considered
141 * @return The raw image size
143 size_t File::GetImageDataRawSize()
145 return PixelReadConverter->GetDecompressedSize();
149 * \brief - Allocates necessary memory,
150 * - Reads the pixels from disk (uncompress if necessary),
151 * - Transforms YBR pixels, if any, into RGB pixels
152 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
153 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
154 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
155 * @return Pointer to newly allocated pixel data.
156 * NULL if alloc fails
158 uint8_t* File::GetImageData()
160 if ( ! GetDecompressed() )
162 // If the decompression failed nothing can be done.
166 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
168 return PixelReadConverter->GetRGB();
172 // When no LUT or LUT conversion fails, return the decompressed
173 return PixelReadConverter->GetDecompressed();
179 * Read the pixels from disk (uncompress if necessary),
180 * Transforms YBR pixels, if any, into RGB pixels
181 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
182 * Transforms single Grey plane + 3 Palettes into a RGB Plane
183 * Copies at most MaxSize bytes of pixel data to caller allocated
185 * \warning This function allows people that want to build a volume
186 * from an image stack *not to* have, first to get the image pixels,
187 * and then move them to the volume area.
188 * It's absolutely useless for any VTK user since vtk chooses
189 * to invert the lines of an image, that is the last line comes first
190 * (for some axis related reasons?). Hence he will have
191 * to load the image line by line, starting from the end.
192 * VTK users have to call GetImageData
194 * @param destination Address (in caller's memory space) at which the
195 * pixel data should be copied
196 * @param maxSize Maximum number of bytes to be copied. When MaxSize
197 * is not sufficient to hold the pixel data the copy is not
198 * executed (i.e. no partial copy).
199 * @return On success, the number of bytes actually copied. Zero on
200 * failure e.g. MaxSize is lower than necessary.
202 size_t File::GetImageDataIntoVector (void* destination, size_t maxSize)
204 if ( ! GetDecompressed() )
206 // If the decompression failed nothing can be done.
210 if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
212 if ( PixelReadConverter->GetRGBSize() > maxSize )
214 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
215 "than caller's expected MaxSize");
219 (void*)PixelReadConverter->GetRGB(),
220 PixelReadConverter->GetRGBSize() );
221 return PixelReadConverter->GetRGBSize();
224 // Either no LUT conversion necessary or LUT conversion failed
225 if ( PixelReadConverter->GetDecompressedSize() > maxSize )
227 dbg.Verbose(0, "File::GetImageDataIntoVector: pixel data bigger"
228 "than caller's expected MaxSize");
232 (void*)PixelReadConverter->GetDecompressed(),
233 PixelReadConverter->GetDecompressedSize() );
234 return PixelReadConverter->GetDecompressedSize();
238 * \brief Allocates necessary memory,
239 * Transforms YBR pixels (if any) into RGB pixels
240 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
241 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
242 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
243 * @return Pointer to newly allocated pixel data.
244 * \ NULL if alloc fails
246 uint8_t* File::GetImageDataRaw ()
248 return GetDecompressed();
251 uint8_t* File::GetDecompressed()
253 uint8_t* decompressed = PixelReadConverter->GetDecompressed();
254 if ( ! decompressed )
256 // The decompressed image migth not be loaded yet:
257 std::ifstream* fp = HeaderInternal->OpenFile();
258 PixelReadConverter->ReadAndDecompressPixelData( fp );
260 HeaderInternal->CloseFile();
262 decompressed = PixelReadConverter->GetDecompressed();
263 if ( ! decompressed )
265 dbg.Verbose(0, "File::GetDecompressed: read/decompress of "
266 "pixel data apparently went wrong.");
275 * \brief Points the internal pointer to the callers inData
276 * image representation, BUT WITHOUT COPYING THE DATA.
277 * 'image' Pixels are presented as C-like 2D arrays : line per line.
278 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
279 * \warning Since the pixels are not copied, it is the caller's responsability
280 * not to deallocate it's data before gdcm uses them (e.g. with
281 * the Write() method.
282 * @param inData user supplied pixel area
283 * @param expectedSize total image size, in Bytes
287 bool File::SetImageData(uint8_t* inData, size_t expectedSize)
289 PixelWriteConverter->SetUserData(inData,expectedSize);
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());
312 if(PixelWriteConverter->GetUserData())
313 fp1.write((char*)PixelWriteConverter->GetUserData(), PixelWriteConverter->GetUserDataSize());
314 else if(PixelReadConverter->GetRGB())
315 fp1.write((char*)PixelReadConverter->GetRGB(), PixelReadConverter->GetRGBSize());
316 else if(PixelReadConverter->GetDecompressed())
317 fp1.write((char*)PixelReadConverter->GetDecompressed(), PixelReadConverter->GetDecompressedSize());
325 * \brief Writes on disk A SINGLE Dicom file,
326 * using the Implicit Value Representation convention
327 * NO test is performed on processor "Endiannity".
328 * @param fileName name of the file to be created
329 * (any already existing file is overwritten)
330 * @return false if write fails
333 bool File::WriteDcmImplVR (std::string const & fileName)
335 SetWriteTypeToDcmImplVR();
336 return Write(fileName);
340 * \brief Writes on disk A SINGLE Dicom file,
341 * using the Explicit Value Representation convention
342 * NO test is performed on processor "Endiannity". * @param fileName name of the file to be created
343 * (any already existing file is overwritten)
344 * @return false if write fails
347 bool File::WriteDcmExplVR (std::string const & fileName)
349 SetWriteTypeToDcmExplVR();
350 return Write(fileName);
354 * \brief Writes on disk A SINGLE Dicom file,
355 * using the ACR-NEMA convention
356 * NO test is performed on processor "Endiannity".
357 * (a l'attention des logiciels cliniques
358 * qui ne prennent en entrée QUE des images ACR ...
359 * \warning if a DICOM_V3 header is supplied,
360 * groups < 0x0008 and shadow groups are ignored
361 * \warning NO TEST is performed on processor "Endiannity".
362 * @param fileName name of the file to be created
363 * (any already existing file is overwritten)
364 * @return false if write fails
367 bool File::WriteAcr (std::string const & fileName)
370 return Write(fileName);
373 bool File::Write(std::string const& fileName)
375 return WriteBase(fileName);
379 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
381 uint8_t* File::GetLutRGBA()
383 return PixelReadConverter->GetLutRGBA();
386 //-----------------------------------------------------------------------------
389 * \brief NOT a end user inteded function
390 * (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
391 * @param fileName name of the file to be created
392 * (any already existing file is overwritten)
393 * @param type file type (ExplicitVR, ImplicitVR, ...)
394 * @return false if write fails
396 bool File::WriteBase (std::string const & fileName)
401 SetWriteFileTypeToImplicitVR();
404 SetWriteFileTypeToExplicitVR();
408 SetWriteFileTypeToACR();
411 SetWriteFileTypeToExplicitVR();
414 // --------------------------------------------------------------
415 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
417 // if recognition code tells us we dealt with a LibIDO image
418 // we reproduce on disk the switch between lineNumber and columnNumber
419 // just before writting ...
420 /// \todo the best trick would be *change* the recognition code
421 /// but pb expected if user deals with, e.g. COMPLEX images
422 if( WriteType == ACR_LIBIDO )
428 SetWriteToNoLibido();
430 // ----------------- End of Special Patch ----------------
434 case WMODE_DECOMPRESSED :
435 SetWriteToDecompressed();
442 bool check = CheckWriteIntegrity();
445 check = HeaderInternal->Write(fileName,WriteType);
449 RestoreWriteFileType();
451 // --------------------------------------------------------------
452 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
454 // ...and we restore the Header to be Dicom Compliant again
455 // just after writting
456 RestoreWriteOfLibido();
457 // ----------------- End of Special Patch ----------------
463 * \brief Check the write integrity
465 * The tests made are :
466 * - verify the size of the image to write with the possible write
467 * when the user set an image data
468 * @return true if the check successfulls
470 bool File::CheckWriteIntegrity()
472 if(PixelWriteConverter->GetUserData())
474 int numberBitsAllocated = HeaderInternal->GetBitsAllocated();
475 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
477 numberBitsAllocated = 16;
480 size_t decSize = HeaderInternal->GetXSize()
481 * HeaderInternal->GetYSize()
482 * HeaderInternal->GetZSize()
483 * ( numberBitsAllocated / 8 )
484 * HeaderInternal->GetSamplesPerPixel();
485 size_t rgbSize = decSize;
486 if( HeaderInternal->HasLUT() )
487 rgbSize = decSize * 3;
491 case WMODE_DECOMPRESSED :
492 if( decSize!=PixelWriteConverter->GetUserDataSize() )
494 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect");
499 if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
501 dbg.Verbose(0, "File::CheckWriteIntegrity: Data size is incorrect");
511 void File::SetWriteToDecompressed()
513 if(HeaderInternal->GetNumberOfScalarComponents()==3 && !HeaderInternal->HasLUT())
519 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
520 if(HeaderInternal->HasLUT())
522 photInt->SetValue("PALETTE COLOR ");
523 photInt->SetLength(14);
527 photInt->SetValue("MONOCHROME1 ");
528 photInt->SetLength(12);
531 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
532 pixel->SetValue(GDCM_BINLOADED);
533 if(PixelWriteConverter->GetUserData())
535 pixel->SetBinArea(PixelWriteConverter->GetUserData(),false);
536 pixel->SetLength(PixelWriteConverter->GetUserDataSize());
540 pixel->SetBinArea(PixelReadConverter->GetDecompressed(),false);
541 pixel->SetLength(PixelReadConverter->GetDecompressedSize());
544 Archive->Push(photInt);
545 Archive->Push(pixel);
549 void File::SetWriteToRGB()
551 if(HeaderInternal->GetNumberOfScalarComponents()==3)
553 PixelReadConverter->BuildRGBImage();
555 ValEntry* spp = CopyValEntry(0x0028,0x0002);
559 ValEntry* planConfig = CopyValEntry(0x0028,0x0006);
560 planConfig->SetValue("0 ");
561 planConfig->SetLength(2);
563 ValEntry* photInt = CopyValEntry(0x0028,0x0004);
564 photInt->SetValue("RGB ");
565 photInt->SetLength(4);
567 BinEntry* pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
568 pixel->SetValue(GDCM_BINLOADED);
569 if(PixelWriteConverter->GetUserData())
571 pixel->SetBinArea(PixelWriteConverter->GetUserData(),false);
572 pixel->SetLength(PixelWriteConverter->GetUserDataSize());
574 else if(PixelReadConverter->GetRGB())
576 pixel->SetBinArea(PixelReadConverter->GetRGB(),false);
577 pixel->SetLength(PixelReadConverter->GetRGBSize());
579 else // Decompressed data
581 pixel->SetBinArea(PixelReadConverter->GetDecompressed(),false);
582 pixel->SetLength(PixelReadConverter->GetDecompressedSize());
586 Archive->Push(planConfig);
587 Archive->Push(photInt);
588 Archive->Push(pixel);
591 Archive->Push(0x0028,0x1101);
592 Archive->Push(0x0028,0x1102);
593 Archive->Push(0x0028,0x1103);
594 Archive->Push(0x0028,0x1201);
595 Archive->Push(0x0028,0x1202);
596 Archive->Push(0x0028,0x1203);
599 // Thus, we have a RGB image and the bits allocated = 24 and
600 // samples per pixels = 1 (in the read file)
601 if(HeaderInternal->GetBitsAllocated()==24)
603 ValEntry* bitsAlloc = CopyValEntry(0x0028,0x0100);
604 bitsAlloc->SetValue("8 ");
605 bitsAlloc->SetLength(2);
607 ValEntry* bitsStored = CopyValEntry(0x0028,0x0101);
608 bitsStored->SetValue("8 ");
609 bitsStored->SetLength(2);
611 ValEntry* highBit = CopyValEntry(0x0028,0x0102);
612 highBit->SetValue("7 ");
613 highBit->SetLength(2);
615 Archive->Push(bitsAlloc);
616 Archive->Push(bitsStored);
617 Archive->Push(highBit);
622 SetWriteToDecompressed();
626 void File::RestoreWrite()
628 Archive->Restore(0x0028,0x0002);
629 Archive->Restore(0x0028,0x0004);
630 Archive->Restore(0x0028,0x0006);
631 Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
633 // For old ACR-NEMA (24 bits problem)
634 Archive->Restore(0x0028,0x0100);
635 Archive->Restore(0x0028,0x0101);
636 Archive->Restore(0x0028,0x0102);
639 Archive->Restore(0x0028,0x1101);
640 Archive->Restore(0x0028,0x1102);
641 Archive->Restore(0x0028,0x1103);
642 Archive->Restore(0x0028,0x1201);
643 Archive->Restore(0x0028,0x1202);
644 Archive->Restore(0x0028,0x1203);
647 void File::SetWriteFileTypeToACR()
649 Archive->Push(0x0002,0x0010);
652 void File::SetWriteFileTypeToExplicitVR()
654 std::string ts = Util::DicomString(
655 Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
657 ValEntry* tss = CopyValEntry(0x0002,0x0010);
659 tss->SetLength(ts.length());
664 void File::SetWriteFileTypeToImplicitVR()
666 std::string ts = Util::DicomString(
667 Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
669 ValEntry* tss = CopyValEntry(0x0002,0x0010);
671 tss->SetLength(ts.length());
674 void File::RestoreWriteFileType()
676 Archive->Restore(0x0002,0x0010);
679 void File::SetWriteToLibido()
681 ValEntry *oldRow = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0010));
682 ValEntry *oldCol = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0028, 0x0011));
684 if( oldRow && oldCol )
686 std::string rows, columns;
688 ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
689 ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
691 newRow->Copy(oldCol);
692 newCol->Copy(oldRow);
694 newRow->SetValue(oldCol->GetValue());
695 newCol->SetValue(oldRow->GetValue());
697 Archive->Push(newRow);
698 Archive->Push(newCol);
701 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
702 libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
703 libidoCode->SetLength(10);
704 Archive->Push(libidoCode);
707 void File::SetWriteToNoLibido()
709 ValEntry *recCode = dynamic_cast<ValEntry *>(HeaderInternal->GetDocEntryByNumber(0x0008,0x0010));
712 if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
714 ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
715 libidoCode->SetValue("");
716 libidoCode->SetLength(0);
717 Archive->Push(libidoCode);
722 void File::RestoreWriteOfLibido()
724 Archive->Restore(0x0028,0x0010);
725 Archive->Restore(0x0028,0x0011);
726 Archive->Restore(0x0008,0x0010);
729 ValEntry* File::CopyValEntry(uint16_t group,uint16_t element)
731 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
736 newE = new ValEntry(oldE->GetDictEntry());
741 newE = GetHeader()->NewValEntryByNumber(group,element);
747 BinEntry* File::CopyBinEntry(uint16_t group,uint16_t element)
749 DocEntry* oldE = HeaderInternal->GetDocEntryByNumber(group, element);
754 newE = new BinEntry(oldE->GetDictEntry());
759 newE = GetHeader()->NewBinEntryByNumber(group,element);
765 //-----------------------------------------------------------------------------
768 //-----------------------------------------------------------------------------
769 } // end namespace gdcm