1 /*=========================================================================
4 Module: $RCSfile: gdcmFileHelper.cxx,v $
7 Date: $Date: 2005/10/21 12:06:06 $
8 Version: $Revision: 1.67 $
10 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
11 l'Image). All rights reserved. See Doc/License.txt or
12 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
14 This software is distributed WITHOUT ANY WARRANTY; without even
15 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16 PURPOSE. See the above copyright notices for more information.
18 =========================================================================*/
20 #include "gdcmFileHelper.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmDocument.h"
24 #include "gdcmDebug.h"
26 #include "gdcmSeqEntry.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
30 #include "gdcmPixelReadConvert.h"
31 #include "gdcmPixelWriteConvert.h"
32 #include "gdcmDocEntryArchive.h"
33 #include "gdcmDictSet.h"
38 // ----------------------------- WARNING -------------------------
40 These lines will be moved to the document-to-be 'User's Guide'
42 // To read an image, user needs a gdcm::File
43 gdcm::File *f = new gdcm::File(fileName);
45 // user may also decide he doesn't want to load some parts of the header
46 gdcm::File *f = new gdcm::File();
47 f->SetFileName(fileName);
48 f->SetLoadMode(LD_NOSEQ); // or
49 f->SetLoadMode(LD_NOSHADOW); // or
50 f->SetLoadMode(LD_NOSEQ | LD_NOSHADOW); // or
51 f->SetLoadMode(LD_NOSHADOWSEQ);
54 // user can now check some values
55 std::string v = f->GetEntryValue(groupNb,ElementNb);
57 // to get the pixels, user needs a gdcm::FileHelper
58 gdcm::FileHelper *fh = new gdcm::FileHelper(f);
59 // user may ask not to convert Palette to RGB
60 uint8_t *pixels = fh->GetImageDataRaw();
61 int imageLength = fh->GetImageDataRawSize();
62 // He can now use the pixels, create a new image, ...
63 uint8_t *userPixels = ...
65 To re-write the image, user re-uses the gdcm::FileHelper
67 fh->SetImageData( userPixels, userPixelsLength);
68 fh->SetTypeToRaw(); // Even if it was possible to convert Palette to RGB
71 fh->SetWriteTypeToDcmExpl(); // he wants Explicit Value Representation
72 // Little Endian is the default
73 // no other value is allowed
74 (-->SetWriteType(ExplicitVR);)
75 -->WriteType = ExplicitVR;
76 fh->Write(newFileName); // overwrites the file, if any
79 fh->WriteDcmExplVR(newFileName);
82 // ----------------------------- WARNING -------------------------
84 These lines will be moved to the document-to-be 'Developer's Guide'
86 WriteMode : WMODE_RAW / WMODE_RGB
87 WriteType : ImplicitVR, ExplicitVR, ACR, ACR_LIBIDO
89 fh1->Write(newFileName);
90 SetWriteFileTypeToImplicitVR() / SetWriteFileTypeToExplicitVR();
91 (modifies TransferSyntax)
92 SetWriteToRaw(); / SetWriteToRGB();
93 (modifies, when necessary : photochromatic interpretation,
94 samples per pixel, Planar configuration,
95 bits allocated, bits stored, high bit -ACR 24 bits-
96 Pixels element VR, pushes out the LUT )
97 CheckWriteIntegrity();
98 (checks user given pixels length)
99 FileInternal->Write(fileName,WriteType)
100 fp = opens file(fileName);
101 ComputeGroup0002Length( );
103 RemoveEntryNoDestroy(palettes, etc)
104 Document::WriteContent(fp, writetype);
106 (moves back to the File all the archived elements)
107 RestoreWriteFileType();
108 (pushes back group 0002, with TransferSyntax)
116 //-------------------------------------------------------------------------
117 // Constructor / Destructor
119 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
120 * file (gdcm::File only deals with the ... header)
121 * Opens (in read only and when possible) an existing file and checks
122 * for DICOM compliance. Returns NULL on failure.
123 * It will be up to the user to load the pixels into memory
124 * ( GetImageDataSize() + GetImageData() methods)
125 * \note the in-memory representation of all available tags found in
126 * the DICOM header is post-poned to first header information access.
127 * This avoid a double parsing of public part of the header when
128 * one sets an a posteriori shadow dictionary (efficiency can be
129 * seen as a side effect).
131 FileHelper::FileHelper( )
133 FileInternal = new File( );
139 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
140 * file (File only deals with the ... header)
141 * Opens (in read only and when possible) an existing file and checks
142 * for DICOM compliance. Returns NULL on failure.
143 * It will be up to the user to load the pixels into memory
144 * ( GetImageDataSize() + GetImageData() methods)
145 * \note the in-memory representation of all available tags found in
146 * the DICOM header is post-poned to first header information access.
147 * This avoid a double parsing of public part of the header when
148 * user sets an a posteriori shadow dictionary (efficiency can be
149 * seen as a side effect).
150 * @param header already built Header
152 FileHelper::FileHelper(File *header)
154 FileInternal = header;
157 if ( FileInternal->IsReadable() )
159 PixelReadConverter->GrabInformationsFromFile( FileInternal );
163 #ifndef GDCM_LEGACY_REMOVE
165 * \brief DEPRECATED : use SetFilename() + SetLoadMode() + Load() methods
166 * Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
167 * file (gdcm::File only deals with the ... header)
168 * Opens (in read only and when possible) an existing file and checks
169 * for DICOM compliance. Returns NULL on failure.
170 * It will be up to the user to load the pixels into memory
171 * \note the in-memory representation of all available tags found in
172 * the DICOM header is post-poned to first header information access.
173 * This avoid a double parsing of public part of the header when
174 * one sets an a posteriori shadow dictionary (efficiency can be
175 * seen as a side effect).
176 * @param filename file to be opened for parsing
177 * @deprecated use SetFilename() + Load() methods
179 FileHelper::FileHelper(std::string const &filename )
181 FileInternal = new File( );
182 FileInternal->SetFileName( filename );
183 FileInternal->Load();
186 if ( FileInternal->IsReadable() )
188 PixelReadConverter->GrabInformationsFromFile( FileInternal );
194 * \brief canonical destructor
195 * \note If the header (gdcm::File) was created by the FileHelper constructor,
196 * it is destroyed by the FileHelper
198 FileHelper::~FileHelper()
200 if ( PixelReadConverter )
202 delete PixelReadConverter;
204 if ( PixelWriteConverter )
206 delete PixelWriteConverter;
220 //-----------------------------------------------------------------------------
224 * \brief Sets the LoadMode of the internal gdcm::File as a boolean string.
225 * NO_SEQ, NO_SHADOW, NO_SHADOWSEQ
226 *... (nothing more, right now)
227 * WARNING : before using NO_SHADOW, be sure *all* your files
228 * contain accurate values in the 0x0000 element (if any)
229 * of *each* Shadow Group. The parser will fail if the size is wrong !
230 * @param loadMode Load mode to be used
232 void FileHelper::SetLoadMode(int loadMode)
234 GetFile()->SetLoadMode( loadMode );
237 * \brief Sets the LoadMode of the internal gdcm::File
238 * @param fileName name of the file to be open
240 void FileHelper::SetFileName(std::string const &fileName)
242 FileInternal->SetFileName( fileName );
247 * @return false if file cannot be open or no swap info was found,
248 * or no tag was found.
250 bool FileHelper::Load()
252 if ( !FileInternal->Load() )
255 PixelReadConverter->GrabInformationsFromFile( FileInternal );
260 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
261 * through it's (group, element) and modifies it's content with
263 * @param content new value (string) to substitute with
264 * @param group group number of the Dicom Element to modify
265 * @param elem element number of the Dicom Element to modify
266 * \return false if DocEntry not found
268 bool FileHelper::SetEntryString(std::string const &content,
269 uint16_t group, uint16_t elem)
271 return FileInternal->SetEntryString(content, group, elem);
276 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
277 * through it's (group, element) and modifies it's content with
279 * @param content new value (void* -> uint8_t*) to substitute with
280 * @param lgth new value length
281 * @param group group number of the Dicom Element to modify
282 * @param elem element number of the Dicom Element to modify
283 * \return false if DocEntry not found
285 bool FileHelper::SetEntryBinArea(uint8_t *content, int lgth,
286 uint16_t group, uint16_t elem)
288 return FileInternal->SetEntryBinArea(content, lgth, group, elem);
292 * \brief Modifies the value of a given DocEntry (Dicom entry)
293 * when it exists. Creates it with the given value when unexistant.
294 * @param content (string)value to be set
295 * @param group Group number of the Entry
296 * @param elem Element number of the Entry
297 * \return pointer to the modified/created Dicom entry (NULL when creation
300 DataEntry *FileHelper::InsertEntryString(std::string const &content,
301 uint16_t group, uint16_t elem)
303 return FileInternal->InsertEntryString(content, group, elem);
307 * \brief Modifies the value of a given DocEntry (Dicom entry)
308 * when it exists. Creates it with the given value when unexistant.
309 * A copy of the binArea is made to be kept in the Document.
310 * @param binArea (binary)value to be set
311 * @param lgth new value length
312 * @param group Group number of the Entry
313 * @param elem Element number of the Entry
314 * \return pointer to the modified/created Dicom entry (NULL when creation
317 DataEntry *FileHelper::InsertEntryBinArea(uint8_t *binArea, int lgth,
318 uint16_t group, uint16_t elem)
320 return FileInternal->InsertEntryBinArea(binArea, lgth, group, elem);
324 * \brief Modifies the value of a given DocEntry (Dicom entry)
325 * when it exists. Creates it, empty (?!) when unexistant.
326 * @param group Group number of the Entry
327 * @param elem Element number of the Entry
328 * \return pointer to the modified/created Dicom entry (NULL when creation
331 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
333 return FileInternal->InsertSeqEntry(group, elem);
337 * \brief Get the size of the image data
338 * If the image can be RGB (with a lut or by default), the size
339 * corresponds to the RGB image
340 * (use GetImageDataRawSize if you want to be sure to get *only*
341 * the size of the pixels)
342 * @return The image size
344 size_t FileHelper::GetImageDataSize()
346 if ( PixelWriteConverter->GetUserData() )
348 return PixelWriteConverter->GetUserDataSize();
350 return PixelReadConverter->GetRGBSize();
354 * \brief Get the size of the image data
355 * If the image could be converted to RGB using a LUT,
356 * this transformation is not taken into account by GetImageDataRawSize
357 * (use GetImageDataSize if you wish)
358 * @return The raw image size
360 size_t FileHelper::GetImageDataRawSize()
362 if ( PixelWriteConverter->GetUserData() )
364 return PixelWriteConverter->GetUserDataSize();
366 return PixelReadConverter->GetRawSize();
370 * \brief - Allocates necessary memory,
371 * - Reads the pixels from disk (uncompress if necessary),
372 * - Transforms YBR pixels, if any, into RGB pixels,
373 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
374 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
375 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
376 * @return Pointer to newly allocated pixel data.
377 * NULL if alloc fails
379 uint8_t *FileHelper::GetImageData()
381 if ( PixelWriteConverter->GetUserData() )
383 return PixelWriteConverter->GetUserData();
388 // If the decompression failed nothing can be done.
392 if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
394 return PixelReadConverter->GetRGB();
398 // When no LUT or LUT conversion fails, return the Raw
399 return PixelReadConverter->GetRaw();
404 * \brief Allocates necessary memory,
405 * Transforms YBR pixels (if any) into RGB pixels
406 * Transforms 3 planes R, G, B (if any) into a single RGB Plane
407 * Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
408 * DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
409 * @return Pointer to newly allocated pixel data.
410 * NULL if alloc fails
412 uint8_t *FileHelper::GetImageDataRaw ()
417 #ifndef GDCM_LEGACY_REMOVE
419 * \brief Useless function, since PixelReadConverter forces us
420 * copy the Pixels anyway.
421 * Reads the pixels from disk (uncompress if necessary),
422 * Transforms YBR pixels, if any, into RGB pixels
423 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
424 * Transforms single Grey plane + 3 Palettes into a RGB Plane
425 * Copies at most MaxSize bytes of pixel data to caller allocated
427 * \warning This function allows people that want to build a volume
428 * from an image stack *not to* have, first to get the image pixels,
429 * and then move them to the volume area.
430 * It's absolutely useless for any VTK user since vtk chooses
431 * to invert the lines of an image, that is the last line comes first
432 * (for some axis related reasons?). Hence he will have
433 * to load the image line by line, starting from the end.
434 * VTK users have to call GetImageData
436 * @param destination Address (in caller's memory space) at which the
437 * pixel data should be copied
438 * @param maxSize Maximum number of bytes to be copied. When MaxSize
439 * is not sufficient to hold the pixel data the copy is not
440 * executed (i.e. no partial copy).
441 * @return On success, the number of bytes actually copied. Zero on
442 * failure e.g. MaxSize is lower than necessary.
444 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
448 // If the decompression failed nothing can be done.
452 if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
454 if ( PixelReadConverter->GetRGBSize() > maxSize )
456 gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
460 (void*)PixelReadConverter->GetRGB(),
461 PixelReadConverter->GetRGBSize() );
462 return PixelReadConverter->GetRGBSize();
465 // Either no LUT conversion necessary or LUT conversion failed
466 if ( PixelReadConverter->GetRawSize() > maxSize )
468 gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
472 (void *)PixelReadConverter->GetRaw(),
473 PixelReadConverter->GetRawSize() );
474 return PixelReadConverter->GetRawSize();
479 * \brief Points the internal pointer to the callers inData
480 * image representation, BUT WITHOUT COPYING THE DATA.
481 * 'image' Pixels are presented as C-like 2D arrays : line per line.
482 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
483 * \warning Since the pixels are not copied, it is the caller's responsability
484 * not to deallocate its data before gdcm uses them (e.g. with
485 * the Write() method )
486 * @param inData user supplied pixel area (uint8_t* is just for the compiler.
487 * user is allowed to pass any kind of pixelsn since the size is
489 * @param expectedSize total image size, *in Bytes*
491 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
493 SetUserData(inData, expectedSize);
497 * \brief Set the image data defined by the user
498 * \warning When writting the file, this data are get as default data to write
499 * @param inData user supplied pixel area (uint8_t* is just for the compiler.
500 * user is allowed to pass any kind of pixels since the size is
502 * @param expectedSize total image size, *in Bytes*
504 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
506 PixelWriteConverter->SetUserData(inData, expectedSize);
510 * \brief Get the image data defined by the user
511 * \warning When writting the file, this data are get as default data to write
513 uint8_t *FileHelper::GetUserData()
515 return PixelWriteConverter->GetUserData();
519 * \brief Get the image data size defined by the user
520 * \warning When writting the file, this data are get as default data to write
522 size_t FileHelper::GetUserDataSize()
524 return PixelWriteConverter->GetUserDataSize();
528 * \brief Get the image data from the file.
529 * If a LUT is found, the data are expanded to be RGB
531 uint8_t *FileHelper::GetRGBData()
533 return PixelReadConverter->GetRGB();
537 * \brief Get the image data size from the file.
538 * If a LUT is found, the data are expanded to be RGB
540 size_t FileHelper::GetRGBDataSize()
542 return PixelReadConverter->GetRGBSize();
546 * \brief Get the image data from the file.
547 * Even when a LUT is found, the data are not expanded to RGB!
549 uint8_t *FileHelper::GetRawData()
551 return PixelReadConverter->GetRaw();
555 * \brief Get the image data size from the file.
556 * Even when a LUT is found, the data are not expanded to RGB!
558 size_t FileHelper::GetRawDataSize()
560 return PixelReadConverter->GetRawSize();
564 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
566 uint8_t* FileHelper::GetLutRGBA()
568 if ( PixelReadConverter->GetLutRGBA() ==0 )
569 PixelReadConverter->BuildLUTRGBA();
570 return PixelReadConverter->GetLutRGBA();
574 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Number
576 int FileHelper::GetLutItemNumber()
578 return PixelReadConverter->GetLutItemNumber();
582 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Size
584 int FileHelper::GetLutItemSize()
586 return PixelReadConverter->GetLutItemSize();
590 * \brief Writes on disk A SINGLE Dicom file
591 * NO test is performed on processor "Endiannity".
592 * It's up to the user to call his Reader properly
593 * @param fileName name of the file to be created
594 * (any already existing file is over written)
595 * @return false if write fails
597 bool FileHelper::WriteRawData(std::string const &fileName)
599 std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
602 gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
606 if ( PixelWriteConverter->GetUserData() )
608 fp1.write( (char *)PixelWriteConverter->GetUserData(),
609 PixelWriteConverter->GetUserDataSize() );
611 else if ( PixelReadConverter->GetRGB() )
613 fp1.write( (char *)PixelReadConverter->GetRGB(),
614 PixelReadConverter->GetRGBSize());
616 else if ( PixelReadConverter->GetRaw() )
618 fp1.write( (char *)PixelReadConverter->GetRaw(),
619 PixelReadConverter->GetRawSize());
623 gdcmErrorMacro( "Nothing written." );
632 * \brief Writes on disk A SINGLE Dicom file,
633 * using the Implicit Value Representation convention
634 * NO test is performed on processor "Endianity".
635 * @param fileName name of the file to be created
636 * (any already existing file is overwritten)
637 * @return false if write fails
640 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
642 SetWriteTypeToDcmImplVR();
643 return Write(fileName);
647 * \brief Writes on disk A SINGLE Dicom file,
648 * using the Explicit Value Representation convention
649 * NO test is performed on processor "Endiannity".
650 * @param fileName name of the file to be created
651 * (any already existing file is overwritten)
652 * @return false if write fails
655 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
657 SetWriteTypeToDcmExplVR();
658 return Write(fileName);
662 * \brief Writes on disk A SINGLE Dicom file,
663 * using the ACR-NEMA convention
664 * NO test is performed on processor "Endiannity".
665 * (a l'attention des logiciels cliniques
666 * qui ne prennent en entrée QUE des images ACR ...
667 * \warning if a DICOM_V3 header is supplied,
668 * groups < 0x0008 and shadow groups are ignored
669 * \warning NO TEST is performed on processor "Endiannity".
670 * @param fileName name of the file to be created
671 * (any already existing file is overwritten)
672 * @return false if write fails
675 bool FileHelper::WriteAcr (std::string const &fileName)
678 return Write(fileName);
682 * \brief Writes on disk A SINGLE Dicom file,
683 * @param fileName name of the file to be created
684 * (any already existing file is overwritten)
685 * @return false if write fails
687 bool FileHelper::Write(std::string const &fileName)
692 SetWriteFileTypeToImplicitVR();
694 case Unknown: // should never happen; ExplicitVR is the default value
696 SetWriteFileTypeToExplicitVR();
700 // NOTHING is done here just for LibIDO.
701 // Just to avoid further trouble if user creates a file ex-nihilo,
702 // wants to write it as an ACR-NEMA file,
703 // and forgets to create any Entry belonging to group 0008
705 // We add Recognition Code (RET)
706 if ( ! FileInternal->GetDataEntry(0x0008, 0x0010) )
707 FileInternal->InsertEntryString("ACR-NEMA V1.0 ", 0x0008, 0x0010);
708 SetWriteFileTypeToACR();
709 // SetWriteFileTypeToImplicitVR(); // ACR IS implicit VR !
712 SetWriteFileTypeToJPEG();
713 std::cerr << "Writting as JPEG" << std::endl;
716 CheckMandatoryElements();
718 // --------------------------------------------------------------
719 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
721 // if recognition code tells us we dealt with a LibIDO image
722 // we reproduce on disk the switch between lineNumber and columnNumber
723 // just before writting ...
724 /// \todo the best trick would be *change* the recognition code
725 /// but pb expected if user deals with, e.g. COMPLEX images
727 if ( WriteType == ACR_LIBIDO )
733 SetWriteToNoLibido();
735 // ----------------- End of Special Patch ----------------
740 SetWriteToRaw(); // modifies and pushes to the archive, when necessary
743 SetWriteToRGB(); // modifies and pushes to the archive, when necessary
747 bool check = CheckWriteIntegrity(); // verifies length
748 if (WriteType == JPEG ) check = true;
751 check = FileInternal->Write(fileName,WriteType);
755 RestoreWriteFileType();
756 RestoreWriteMandatory();
758 // --------------------------------------------------------------
759 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
761 // ...and we restore the header to be Dicom Compliant again
762 // just after writting
763 RestoreWriteOfLibido();
764 // ----------------- End of Special Patch ----------------
769 //-----------------------------------------------------------------------------
772 * \brief Checks the write integrity
774 * The tests made are :
775 * - verify the size of the image to write with the possible write
776 * when the user set an image data
777 * @return true if check is successfull
779 bool FileHelper::CheckWriteIntegrity()
781 if ( PixelWriteConverter->GetUserData() )
783 int numberBitsAllocated = FileInternal->GetBitsAllocated();
784 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
786 gdcmWarningMacro( "numberBitsAllocated changed from "
787 << numberBitsAllocated << " to 16 "
788 << " for consistency purpose" );
789 numberBitsAllocated = 16;
792 size_t decSize = FileInternal->GetXSize()
793 * FileInternal->GetYSize()
794 * FileInternal->GetZSize()
795 * FileInternal->GetSamplesPerPixel()
796 * ( numberBitsAllocated / 8 );
797 size_t rgbSize = decSize;
798 if ( FileInternal->HasLUT() )
799 rgbSize = decSize * 3;
804 if ( decSize!=PixelWriteConverter->GetUserDataSize() )
806 gdcmWarningMacro( "Data size (Raw) is incorrect. Should be "
807 << decSize << " / Found :"
808 << PixelWriteConverter->GetUserDataSize() );
813 if ( rgbSize!=PixelWriteConverter->GetUserDataSize() )
815 gdcmWarningMacro( "Data size (RGB) is incorrect. Should be "
816 << decSize << " / Found "
817 << PixelWriteConverter->GetUserDataSize() );
828 * \brief Updates the File to write RAW data (as opposed to RGB data)
829 * (modifies, when necessary, photochromatic interpretation,
830 * bits allocated, Pixels element VR)
832 void FileHelper::SetWriteToRaw()
834 if ( FileInternal->GetNumberOfScalarComponents() == 3
835 && !FileInternal->HasLUT() )
841 DataEntry *photInt = CopyDataEntry(0x0028,0x0004);
842 if (FileInternal->HasLUT() )
844 photInt->SetString("PALETTE COLOR ");
848 photInt->SetString("MONOCHROME2 ");
851 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
852 PixelReadConverter->GetRawSize());
854 std::string vr = "OB";
855 if ( FileInternal->GetBitsAllocated()>8 )
857 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
860 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
861 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
862 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
863 pixel->SetLength(PixelWriteConverter->GetDataSize());
865 Archive->Push(photInt);
866 Archive->Push(pixel);
871 * \brief Updates the File to write RGB data (as opposed to RAW data)
872 * (modifies, when necessary, photochromatic interpretation,
873 * samples per pixel, Planar configuration,
874 * bits allocated, bits stored, high bit -ACR 24 bits-
875 * Pixels element VR, pushes out the LUT, )
877 void FileHelper::SetWriteToRGB()
879 if ( FileInternal->GetNumberOfScalarComponents()==3 )
881 PixelReadConverter->BuildRGBImage();
883 DataEntry *spp = CopyDataEntry(0x0028,0x0002);
884 spp->SetString("3 ");
886 DataEntry *planConfig = CopyDataEntry(0x0028,0x0006);
887 planConfig->SetString("0 ");
889 DataEntry *photInt = CopyDataEntry(0x0028,0x0004);
890 photInt->SetString("RGB ");
892 if ( PixelReadConverter->GetRGB() )
894 PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
895 PixelReadConverter->GetRGBSize());
899 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
900 PixelReadConverter->GetRawSize());
903 std::string vr = "OB";
904 if ( FileInternal->GetBitsAllocated()>8 )
906 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
909 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
910 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
911 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
912 pixel->SetLength(PixelWriteConverter->GetDataSize());
915 Archive->Push(planConfig);
916 Archive->Push(photInt);
917 Archive->Push(pixel);
920 Archive->Push(0x0028,0x1101);
921 Archive->Push(0x0028,0x1102);
922 Archive->Push(0x0028,0x1103);
923 Archive->Push(0x0028,0x1201);
924 Archive->Push(0x0028,0x1202);
925 Archive->Push(0x0028,0x1203);
927 // push out Palette Color Lookup Table UID, if any
928 Archive->Push(0x0028,0x1199);
930 // For old '24 Bits' ACR-NEMA
931 // Thus, we have a RGB image and the bits allocated = 24 and
932 // samples per pixels = 1 (in the read file)
933 if ( FileInternal->GetBitsAllocated()==24 )
935 DataEntry *bitsAlloc = CopyDataEntry(0x0028,0x0100);
936 bitsAlloc->SetString("8 ");
938 DataEntry *bitsStored = CopyDataEntry(0x0028,0x0101);
939 bitsStored->SetString("8 ");
941 DataEntry *highBit = CopyDataEntry(0x0028,0x0102);
942 highBit->SetString("7 ");
944 Archive->Push(bitsAlloc);
945 Archive->Push(bitsStored);
946 Archive->Push(highBit);
956 * \brief Restore the File write mode
958 void FileHelper::RestoreWrite()
960 Archive->Restore(0x0028,0x0002);
961 Archive->Restore(0x0028,0x0004);
962 Archive->Restore(0x0028,0x0006);
963 Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
965 // For old ACR-NEMA (24 bits problem)
966 Archive->Restore(0x0028,0x0100);
967 Archive->Restore(0x0028,0x0101);
968 Archive->Restore(0x0028,0x0102);
971 Archive->Restore(0x0028,0x1101);
972 Archive->Restore(0x0028,0x1102);
973 Archive->Restore(0x0028,0x1103);
974 Archive->Restore(0x0028,0x1201);
975 Archive->Restore(0x0028,0x1202);
976 Archive->Restore(0x0028,0x1203);
978 // For the Palette Color Lookup Table UID
979 Archive->Restore(0x0028,0x1203);
982 // group 0002 may be pushed out for ACR-NEMA writting purposes
983 Archive->Restore(0x0002,0x0000);
984 Archive->Restore(0x0002,0x0001);
985 Archive->Restore(0x0002,0x0002);
986 Archive->Restore(0x0002,0x0003);
987 Archive->Restore(0x0002,0x0010);
988 Archive->Restore(0x0002,0x0012);
989 Archive->Restore(0x0002,0x0013);
990 Archive->Restore(0x0002,0x0016);
991 Archive->Restore(0x0002,0x0100);
992 Archive->Restore(0x0002,0x0102);
996 * \brief Pushes out the whole group 0002
997 * FIXME : better, set a flag to tell the writer not to write it ...
998 * FIXME : method should probably have an other name !
999 * SetWriteFileTypeToACR is NOT opposed to
1000 * SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
1002 void FileHelper::SetWriteFileTypeToACR()
1004 Archive->Push(0x0002,0x0000);
1005 Archive->Push(0x0002,0x0001);
1006 Archive->Push(0x0002,0x0002);
1007 Archive->Push(0x0002,0x0003);
1008 Archive->Push(0x0002,0x0010);
1009 Archive->Push(0x0002,0x0012);
1010 Archive->Push(0x0002,0x0013);
1011 Archive->Push(0x0002,0x0016);
1012 Archive->Push(0x0002,0x0100);
1013 Archive->Push(0x0002,0x0102);
1017 * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"
1019 void FileHelper::SetWriteFileTypeToJPEG()
1021 std::string ts = Util::DicomString(
1022 Global::GetTS()->GetSpecialTransferSyntax(TS::JPEGBaselineProcess1) );
1024 DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1030 void FileHelper::SetWriteFileTypeToExplicitVR()
1032 std::string ts = Util::DicomString(
1033 Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
1035 DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1042 * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"
1044 void FileHelper::SetWriteFileTypeToImplicitVR()
1046 std::string ts = Util::DicomString(
1047 Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
1049 DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1057 * \brief Restore in the File the initial group 0002
1059 void FileHelper::RestoreWriteFileType()
1064 * \brief Set the Write not to Libido format
1066 void FileHelper::SetWriteToLibido()
1068 DataEntry *oldRow = FileInternal->GetDataEntry(0x0028, 0x0010);
1069 DataEntry *oldCol = FileInternal->GetDataEntry(0x0028, 0x0011);
1071 if ( oldRow && oldCol )
1073 std::string rows, columns;
1075 DataEntry *newRow=new DataEntry(oldRow->GetDictEntry());
1076 DataEntry *newCol=new DataEntry(oldCol->GetDictEntry());
1078 newRow->Copy(oldCol);
1079 newCol->Copy(oldRow);
1081 newRow->SetString(oldCol->GetString());
1082 newCol->SetString(oldRow->GetString());
1084 Archive->Push(newRow);
1085 Archive->Push(newCol);
1088 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1089 libidoCode->SetString("ACRNEMA_LIBIDO_1.1");
1090 Archive->Push(libidoCode);
1094 * \brief Set the Write not to No Libido format
1096 void FileHelper::SetWriteToNoLibido()
1098 DataEntry *recCode = FileInternal->GetDataEntry(0x0008,0x0010);
1101 if ( recCode->GetString() == "ACRNEMA_LIBIDO_1.1" )
1103 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1104 libidoCode->SetString("");
1105 Archive->Push(libidoCode);
1111 * \brief Restore the Write format
1113 void FileHelper::RestoreWriteOfLibido()
1115 Archive->Restore(0x0028,0x0010);
1116 Archive->Restore(0x0028,0x0011);
1117 Archive->Restore(0x0008,0x0010);
1119 // Restore 'LibIDO-special' entries, if any
1120 Archive->Restore(0x0028,0x0015);
1121 Archive->Restore(0x0028,0x0016);
1122 Archive->Restore(0x0028,0x0017);
1123 Archive->Restore(0x0028,0x00199);
1127 * \brief Duplicates a DataEntry or creates it.
1128 * @param group Group number of the Entry
1129 * @param elem Element number of the Entry
1130 * @param vr Value Representation of the Entry
1131 * FIXME : what is it used for?
1132 * \return pointer to the new Bin Entry (NULL when creation failed).
1134 DataEntry *FileHelper::CopyDataEntry(uint16_t group, uint16_t elem,
1137 DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1140 if ( oldE && vr != GDCM_VRUNKNOWN )
1141 if ( oldE->GetVR() != vr )
1146 newE = new DataEntry(oldE->GetDictEntry());
1151 newE = GetFile()->NewDataEntry(group, elem, vr);
1158 * \brief This method is called automatically, just before writting
1159 * in order to produce a 'True Dicom V3' image
1160 * We cannot know *how* the user made the File (reading an old ACR-NEMA
1161 * file or a not very clean DICOM file ...)
1163 * Just before writting :
1164 * - we check the Entries
1165 * - we create the mandatory entries if they are missing
1166 * - we modify the values if necessary
1167 * - we push the sensitive entries to the Archive
1168 * The writing process will restore the entries as they where before
1169 * entering FileHelper::CheckMandatoryElements, so the user will always
1170 * see the entries just as he left them.
1172 * \todo : - warn the user if we had to add some entries :
1173 * even if a mandatory entry is missing, we add it, with a default value
1174 * (we don't want to give up the writting process if user forgot to
1175 * specify Lena's Patient ID, for instance ...)
1176 * - read the whole PS 3.3 Part of DICOM (890 pages)
1177 * and write a *full* checker (probably one method per Modality ...)
1178 * Any contribution is welcome.
1179 * - write a user callable full checker, to allow post reading
1180 * and/or pre writting image consistency check.
1183 void FileHelper::CheckMandatoryElements()
1185 std::string sop = Util::CreateUniqueUID();
1187 // just to remember : 'official' 0002 group
1188 if ( WriteType != ACR && WriteType != ACR_LIBIDO )
1190 // Group 000002 (Meta Elements) already pushed out
1192 //0002 0000 UL 1 Meta Group Length
1193 //0002 0001 OB 1 File Meta Information Version
1194 //0002 0002 UI 1 Media Stored SOP Class UID
1195 //0002 0003 UI 1 Media Stored SOP Instance UID
1196 //0002 0010 UI 1 Transfer Syntax UID
1197 //0002 0012 UI 1 Implementation Class UID
1198 //0002 0013 SH 1 Implementation Version Name
1199 //0002 0016 AE 1 Source Application Entity Title
1200 //0002 0100 UI 1 Private Information Creator
1201 //0002 0102 OB 1 Private Information
1203 // Create them if not found
1204 // Always modify the value
1205 // Push the entries to the archive.
1206 CopyMandatoryEntry(0x0002,0x0000,"0");
1208 DataEntry *e_0002_0001 = CopyDataEntry(0x0002,0x0001, "OB");
1209 e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1211 e_0002_0001->SetLength(2);
1212 Archive->Push(e_0002_0001);
1214 // Potentialy post-processed image --> [Secondary Capture Image Storage]
1215 // 'Media Storage SOP Class UID'
1216 CopyMandatoryEntry(0x0002,0x0002,"1.2.840.10008.5.1.4.1.1.7");
1218 // 'Media Storage SOP Instance UID'
1219 CopyMandatoryEntry(0x0002,0x0003,sop);
1221 // 'Implementation Class UID'
1222 CopyMandatoryEntry(0x0002,0x0012,Util::CreateUniqueUID());
1224 // 'Implementation Version Name'
1225 std::string version = "GDCM ";
1226 version += Util::GetVersion();
1227 CopyMandatoryEntry(0x0002,0x0013,version);
1230 // Push out 'LibIDO-special' entries, if any
1231 Archive->Push(0x0028,0x0015);
1232 Archive->Push(0x0028,0x0016);
1233 Archive->Push(0x0028,0x0017);
1234 Archive->Push(0x0028,0x00199);
1236 // Deal with the pb of (Bits Stored = 12)
1237 // - we're gonna write the image as Bits Stored = 16
1238 if ( FileInternal->GetEntryString(0x0028,0x0100) == "12")
1240 CopyMandatoryEntry(0x0028,0x0100,"16");
1243 // Check if user wasn't drunk ;-)
1245 std::ostringstream s;
1246 // check 'Bits Allocated' vs decent values
1247 int nbBitsAllocated = FileInternal->GetBitsAllocated();
1248 if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1250 CopyMandatoryEntry(0x0028,0x0100,"16");
1251 gdcmWarningMacro("(0028,0100) changed from "
1252 << nbBitsAllocated << " to 16 for consistency purpose");
1253 nbBitsAllocated = 16;
1255 // check 'Bits Stored' vs 'Bits Allocated'
1256 int nbBitsStored = FileInternal->GetBitsStored();
1257 if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1260 s << nbBitsAllocated;
1261 CopyMandatoryEntry(0x0028,0x0101,s.str());
1262 gdcmWarningMacro("(0028,0101) changed from "
1263 << nbBitsStored << " to " << nbBitsAllocated
1264 << " for consistency purpose" );
1265 nbBitsStored = nbBitsAllocated;
1267 // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1268 int highBitPosition = FileInternal->GetHighBitPosition();
1269 if ( highBitPosition == 0 ||
1270 highBitPosition > nbBitsAllocated-1 ||
1271 highBitPosition < nbBitsStored-1 )
1274 s << nbBitsStored - 1;
1275 CopyMandatoryEntry(0x0028,0x0102,s.str());
1276 gdcmWarningMacro("(0028,0102) changed from "
1277 << highBitPosition << " to " << nbBitsAllocated-1
1278 << " for consistency purpose");
1280 // --- Check UID-related Entries ---
1282 // If 'SOP Class UID' exists ('true DICOM' image)
1283 // we create the 'Source Image Sequence' SeqEntry
1284 // to hold informations about the Source Image
1286 DataEntry *e_0008_0016 = FileInternal->GetDataEntry(0x0008, 0x0016);
1289 // Create 'Source Image Sequence' SeqEntry
1290 SeqEntry *sis = new SeqEntry (
1291 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1292 SQItem *sqi = new SQItem(1);
1293 // (we assume 'SOP Instance UID' exists too)
1294 // create 'Referenced SOP Class UID'
1295 DataEntry *e_0008_1150 = new DataEntry(
1296 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1297 e_0008_1150->SetString( e_0008_0016->GetString());
1298 sqi->AddEntry(e_0008_1150);
1300 // create 'Referenced SOP Instance UID'
1301 DataEntry *e_0008_0018 = FileInternal->GetDataEntry(0x0008, 0x0018);
1302 DataEntry *e_0008_1155 = new DataEntry(
1303 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1304 e_0008_1155->SetString( e_0008_0018->GetString());
1305 sqi->AddEntry(e_0008_1155);
1307 sis->AddSQItem(sqi,1);
1308 // temporarily replaces any previous 'Source Image Sequence'
1311 // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1312 CopyMandatoryEntry(0x0008,0x0008,"DERIVED\\PRIMARY");
1315 // At the end, not to overwrite the original ones,
1316 // needed by 'Referenced SOP Instance UID', 'Referenced SOP Class UID'
1317 // 'SOP Instance UID'
1318 CopyMandatoryEntry(0x0008,0x0018,sop);
1320 // whether a 'SOP Class UID' already exists or not in the original image
1321 // the gdcm written image *is* a [Secondary Capture Image Storage] !
1322 // 'SOP Class UID' : [Secondary Capture Image Storage]
1323 CopyMandatoryEntry(0x0008,0x0016,"1.2.840.10008.5.1.4.1.1.7");
1325 // ---- The user will never have to take any action on the following ----.
1326 // new value for 'SOP Instance UID'
1327 //SetMandatoryEntry(0x0008,0x0018,Util::CreateUniqueUID());
1329 // Instance Creation Date
1330 CopyMandatoryEntry(0x0008,0x0012,Util::GetCurrentDate().c_str());
1332 // Instance Creation Time
1333 CopyMandatoryEntry(0x0008,0x0013,Util::GetCurrentTime().c_str());
1335 // ----- Add Mandatory Entries if missing ---
1336 // Entries whose type is 1 are mandatory, with a mandatory value
1337 // Entries whose type is 1c are mandatory-inside-a-Sequence
1338 // Entries whose type is 2 are mandatory, with a optional value
1339 // Entries whose type is 2c are mandatory-inside-a-Sequence
1340 // Entries whose type is 3 are optional
1342 // 'Study Instance UID'
1343 // Keep the value if exists
1344 // The user is allowed to create his own Study,
1345 // keeping the same 'Study Instance UID' for various images
1346 // The user may add images to a 'Manufacturer Study',
1347 // adding new series to an already existing Study
1348 CheckMandatoryEntry(0x0020,0x000d,Util::CreateUniqueUID());
1350 // 'Serie Instance UID'
1351 // Keep the value if exists
1352 // The user is allowed to create his own Series,
1353 // keeping the same 'Serie Instance UID' for various images
1354 // The user shouldn't add any image to a 'Manufacturer Serie'
1355 // but there is no way no to allowed him to do that
1356 CheckMandatoryEntry(0x0020,0x000e,Util::CreateUniqueUID());
1358 // Modality : if missing we set it to 'OTher'
1359 CheckMandatoryEntry(0x0008,0x0060,"OT");
1361 // Manufacturer : if missing we set it to 'GDCM Factory'
1362 CheckMandatoryEntry(0x0008,0x0070,"GDCM Factory");
1364 // Institution Name : if missing we set it to 'GDCM Hospital'
1365 CheckMandatoryEntry(0x0008,0x0080,"GDCM Hospital");
1367 // Patient's Name : if missing, we set it to 'GDCM^Patient'
1368 CheckMandatoryEntry(0x0010,0x0010,"GDCM^Patient");
1370 // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1371 CheckMandatoryEntry(0x0010,0x0030,"");
1373 // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1374 CheckMandatoryEntry(0x0010,0x0040,"");
1376 // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1377 CheckMandatoryEntry(0x0008,0x0090,"");
1379 // Pixel Spacing : defaulted to 1.0\1.0
1380 CheckMandatoryEntry(0x0028,0x0030,"1.0\\1.0");
1382 // Remove some inconstencies (probably some more will be added)
1384 // if (0028 0008)Number of Frames exists
1385 // Push out (0020 0052),Frame of Reference UID
1386 // (only meaningfull within a Serie)
1387 DataEntry *e_0028_0008 = FileInternal->GetDataEntry(0x0028, 0x0008);
1390 Archive->Push(0x0020, 0X0052);
1394 void FileHelper::CheckMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1396 DataEntry *entry = FileInternal->GetDataEntry(group,elem);
1399 entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1400 entry->SetString(value);
1401 Archive->Push(entry);
1405 void FileHelper::SetMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1407 DataEntry *entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1408 entry->SetString(value);
1409 Archive->Push(entry);
1412 void FileHelper::CopyMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1414 DataEntry *entry = CopyDataEntry(group,elem);
1415 entry->SetString(value);
1416 Archive->Push(entry);
1420 * \brief Restore in the File the initial group 0002
1422 void FileHelper::RestoreWriteMandatory()
1424 // group 0002 may be pushed out for ACR-NEMA writting purposes
1425 Archive->Restore(0x0002,0x0000);
1426 Archive->Restore(0x0002,0x0001);
1427 Archive->Restore(0x0002,0x0002);
1428 Archive->Restore(0x0002,0x0003);
1429 Archive->Restore(0x0002,0x0010);
1430 Archive->Restore(0x0002,0x0012);
1431 Archive->Restore(0x0002,0x0013);
1432 Archive->Restore(0x0002,0x0016);
1433 Archive->Restore(0x0002,0x0100);
1434 Archive->Restore(0x0002,0x0102);
1436 Archive->Restore(0x0008,0x0012);
1437 Archive->Restore(0x0008,0x0013);
1438 Archive->Restore(0x0008,0x0016);
1439 Archive->Restore(0x0008,0x0018);
1440 Archive->Restore(0x0008,0x0060);
1441 Archive->Restore(0x0008,0x0070);
1442 Archive->Restore(0x0008,0x0080);
1443 Archive->Restore(0x0008,0x0090);
1444 Archive->Restore(0x0008,0x2112);
1446 Archive->Restore(0x0010,0x0010);
1447 Archive->Restore(0x0010,0x0030);
1448 Archive->Restore(0x0010,0x0040);
1450 Archive->Restore(0x0020,0x000d);
1451 Archive->Restore(0x0020,0x000e);
1455 //-----------------------------------------------------------------------------
1458 * \brief Factorization for various forms of constructors.
1460 void FileHelper::Initialize()
1464 WriteMode = WMODE_RAW;
1465 WriteType = ExplicitVR;
1467 PixelReadConverter = new PixelReadConvert;
1468 PixelWriteConverter = new PixelWriteConvert;
1469 Archive = new DocEntryArchive( FileInternal );
1473 * \brief Reads/[decompresses] the pixels,
1474 * *without* making RGB from Palette Colors
1475 * @return the pixels area, whatever its type
1476 * (uint8_t is just for prototyping : feel free to Cast it)
1478 uint8_t *FileHelper::GetRaw()
1480 PixelReadConverter->SetUserFunction( UserFunction );
1482 uint8_t *raw = PixelReadConverter->GetRaw();
1485 // The Raw image migth not be loaded yet:
1486 std::ifstream *fp = FileInternal->OpenFile();
1487 PixelReadConverter->ReadAndDecompressPixelData( fp );
1489 FileInternal->CloseFile();
1491 raw = PixelReadConverter->GetRaw();
1494 gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1501 //-----------------------------------------------------------------------------
1503 * \brief Prints the common part of DataEntry, SeqEntry
1504 * @param os ostream we want to print in
1505 * @param indent (unused)
1507 void FileHelper::Print(std::ostream &os, std::string const &)
1509 FileInternal->SetPrintLevel(PrintLevel);
1510 FileInternal->Print(os);
1512 if ( FileInternal->IsReadable() )
1514 PixelReadConverter->SetPrintLevel(PrintLevel);
1515 PixelReadConverter->Print(os);
1519 //-----------------------------------------------------------------------------
1520 } // end namespace gdcm