1 /*=========================================================================
4 Module: $RCSfile: gdcmFileHelper.cxx,v $
7 Date: $Date: 2005/10/18 12:49:55 $
8 Version: $Revision: 1.61 $
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 CheckMandatoryElements();
714 // --------------------------------------------------------------
715 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
717 // if recognition code tells us we dealt with a LibIDO image
718 // we reproduce on disk the switch between lineNumber and columnNumber
719 // just before writting ...
720 /// \todo the best trick would be *change* the recognition code
721 /// but pb expected if user deals with, e.g. COMPLEX images
723 if ( WriteType == ACR_LIBIDO )
729 SetWriteToNoLibido();
731 // ----------------- End of Special Patch ----------------
736 SetWriteToRaw(); // modifies and pushes to the archive, when necessary
739 SetWriteToRGB(); // modifies and pushes to the archive, when necessary
743 bool check = CheckWriteIntegrity(); // verifies length
746 check = FileInternal->Write(fileName,WriteType);
750 RestoreWriteFileType();
751 RestoreWriteMandatory();
753 // --------------------------------------------------------------
754 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
756 // ...and we restore the header to be Dicom Compliant again
757 // just after writting
758 RestoreWriteOfLibido();
759 // ----------------- End of Special Patch ----------------
764 //-----------------------------------------------------------------------------
767 * \brief Checks the write integrity
769 * The tests made are :
770 * - verify the size of the image to write with the possible write
771 * when the user set an image data
772 * @return true if check is successfull
774 bool FileHelper::CheckWriteIntegrity()
776 if ( PixelWriteConverter->GetUserData() )
778 int numberBitsAllocated = FileInternal->GetBitsAllocated();
779 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
781 gdcmWarningMacro( "numberBitsAllocated changed from "
782 << numberBitsAllocated << " to 16 "
783 << " for consistency purpose" );
784 numberBitsAllocated = 16;
787 size_t decSize = FileInternal->GetXSize()
788 * FileInternal->GetYSize()
789 * FileInternal->GetZSize()
790 * FileInternal->GetSamplesPerPixel()
791 * ( numberBitsAllocated / 8 );
792 size_t rgbSize = decSize;
793 if ( FileInternal->HasLUT() )
794 rgbSize = decSize * 3;
799 if ( decSize!=PixelWriteConverter->GetUserDataSize() )
801 gdcmWarningMacro( "Data size (Raw) is incorrect. Should be "
802 << decSize << " / Found :"
803 << PixelWriteConverter->GetUserDataSize() );
808 if ( rgbSize!=PixelWriteConverter->GetUserDataSize() )
810 gdcmWarningMacro( "Data size (RGB) is incorrect. Should be "
811 << decSize << " / Found "
812 << PixelWriteConverter->GetUserDataSize() );
823 * \brief Updates the File to write RAW data (as opposed to RGB data)
824 * (modifies, when necessary, photochromatic interpretation,
825 * bits allocated, Pixels element VR)
827 void FileHelper::SetWriteToRaw()
829 if ( FileInternal->GetNumberOfScalarComponents() == 3
830 && !FileInternal->HasLUT() )
836 DataEntry *photInt = CopyDataEntry(0x0028,0x0004);
837 if (FileInternal->HasLUT() )
839 photInt->SetString("PALETTE COLOR ");
843 photInt->SetString("MONOCHROME2 ");
846 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
847 PixelReadConverter->GetRawSize());
849 std::string vr = "OB";
850 if ( FileInternal->GetBitsAllocated()>8 )
852 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
855 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
856 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
857 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
858 pixel->SetLength(PixelWriteConverter->GetDataSize());
860 Archive->Push(photInt);
861 Archive->Push(pixel);
866 * \brief Updates the File to write RGB data (as opposed to RAW data)
867 * (modifies, when necessary, photochromatic interpretation,
868 * samples per pixel, Planar configuration,
869 * bits allocated, bits stored, high bit -ACR 24 bits-
870 * Pixels element VR, pushes out the LUT, )
872 void FileHelper::SetWriteToRGB()
874 if ( FileInternal->GetNumberOfScalarComponents()==3 )
876 PixelReadConverter->BuildRGBImage();
878 DataEntry *spp = CopyDataEntry(0x0028,0x0002);
879 spp->SetString("3 ");
881 DataEntry *planConfig = CopyDataEntry(0x0028,0x0006);
882 planConfig->SetString("0 ");
884 DataEntry *photInt = CopyDataEntry(0x0028,0x0004);
885 photInt->SetString("RGB ");
887 if ( PixelReadConverter->GetRGB() )
889 PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
890 PixelReadConverter->GetRGBSize());
894 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
895 PixelReadConverter->GetRawSize());
898 std::string vr = "OB";
899 if ( FileInternal->GetBitsAllocated()>8 )
901 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
904 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
905 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
906 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
907 pixel->SetLength(PixelWriteConverter->GetDataSize());
910 Archive->Push(planConfig);
911 Archive->Push(photInt);
912 Archive->Push(pixel);
915 Archive->Push(0x0028,0x1101);
916 Archive->Push(0x0028,0x1102);
917 Archive->Push(0x0028,0x1103);
918 Archive->Push(0x0028,0x1201);
919 Archive->Push(0x0028,0x1202);
920 Archive->Push(0x0028,0x1203);
922 // push out Palette Color Lookup Table UID, if any
923 Archive->Push(0x0028,0x1199);
925 // For old '24 Bits' ACR-NEMA
926 // Thus, we have a RGB image and the bits allocated = 24 and
927 // samples per pixels = 1 (in the read file)
928 if ( FileInternal->GetBitsAllocated()==24 )
930 DataEntry *bitsAlloc = CopyDataEntry(0x0028,0x0100);
931 bitsAlloc->SetString("8 ");
933 DataEntry *bitsStored = CopyDataEntry(0x0028,0x0101);
934 bitsStored->SetString("8 ");
936 DataEntry *highBit = CopyDataEntry(0x0028,0x0102);
937 highBit->SetString("7 ");
939 Archive->Push(bitsAlloc);
940 Archive->Push(bitsStored);
941 Archive->Push(highBit);
951 * \brief Restore the File write mode
953 void FileHelper::RestoreWrite()
955 Archive->Restore(0x0028,0x0002);
956 Archive->Restore(0x0028,0x0004);
957 Archive->Restore(0x0028,0x0006);
958 Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
960 // For old ACR-NEMA (24 bits problem)
961 Archive->Restore(0x0028,0x0100);
962 Archive->Restore(0x0028,0x0101);
963 Archive->Restore(0x0028,0x0102);
966 Archive->Restore(0x0028,0x1101);
967 Archive->Restore(0x0028,0x1102);
968 Archive->Restore(0x0028,0x1103);
969 Archive->Restore(0x0028,0x1201);
970 Archive->Restore(0x0028,0x1202);
971 Archive->Restore(0x0028,0x1203);
973 // For the Palette Color Lookup Table UID
974 Archive->Restore(0x0028,0x1203);
977 // group 0002 may be pushed out for ACR-NEMA writting purposes
978 Archive->Restore(0x0002,0x0000);
979 Archive->Restore(0x0002,0x0001);
980 Archive->Restore(0x0002,0x0002);
981 Archive->Restore(0x0002,0x0003);
982 Archive->Restore(0x0002,0x0010);
983 Archive->Restore(0x0002,0x0012);
984 Archive->Restore(0x0002,0x0013);
985 Archive->Restore(0x0002,0x0016);
986 Archive->Restore(0x0002,0x0100);
987 Archive->Restore(0x0002,0x0102);
991 * \brief Pushes out the whole group 0002
992 * FIXME : better, set a flag to tell the writer not to write it ...
993 * FIXME : method should probably have an other name !
994 * SetWriteFileTypeToACR is NOT opposed to
995 * SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
997 void FileHelper::SetWriteFileTypeToACR()
999 Archive->Push(0x0002,0x0000);
1000 Archive->Push(0x0002,0x0001);
1001 Archive->Push(0x0002,0x0002);
1002 Archive->Push(0x0002,0x0003);
1003 Archive->Push(0x0002,0x0010);
1004 Archive->Push(0x0002,0x0012);
1005 Archive->Push(0x0002,0x0013);
1006 Archive->Push(0x0002,0x0016);
1007 Archive->Push(0x0002,0x0100);
1008 Archive->Push(0x0002,0x0102);
1012 * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"
1014 void FileHelper::SetWriteFileTypeToExplicitVR()
1016 std::string ts = Util::DicomString(
1017 Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
1019 DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1026 * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"
1028 void FileHelper::SetWriteFileTypeToImplicitVR()
1030 std::string ts = Util::DicomString(
1031 Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
1033 DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1041 * \brief Restore in the File the initial group 0002
1043 void FileHelper::RestoreWriteFileType()
1048 * \brief Set the Write not to Libido format
1050 void FileHelper::SetWriteToLibido()
1052 DataEntry *oldRow = FileInternal->GetDataEntry(0x0028, 0x0010);
1053 DataEntry *oldCol = FileInternal->GetDataEntry(0x0028, 0x0011);
1055 if ( oldRow && oldCol )
1057 std::string rows, columns;
1059 DataEntry *newRow=new DataEntry(oldRow->GetDictEntry());
1060 DataEntry *newCol=new DataEntry(oldCol->GetDictEntry());
1062 newRow->Copy(oldCol);
1063 newCol->Copy(oldRow);
1065 newRow->SetString(oldCol->GetString());
1066 newCol->SetString(oldRow->GetString());
1068 Archive->Push(newRow);
1069 Archive->Push(newCol);
1072 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1073 libidoCode->SetString("ACRNEMA_LIBIDO_1.1");
1074 Archive->Push(libidoCode);
1078 * \brief Set the Write not to No Libido format
1080 void FileHelper::SetWriteToNoLibido()
1082 DataEntry *recCode = FileInternal->GetDataEntry(0x0008,0x0010);
1085 if ( recCode->GetString() == "ACRNEMA_LIBIDO_1.1" )
1087 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1088 libidoCode->SetString("");
1089 Archive->Push(libidoCode);
1095 * \brief Restore the Write format
1097 void FileHelper::RestoreWriteOfLibido()
1099 Archive->Restore(0x0028,0x0010);
1100 Archive->Restore(0x0028,0x0011);
1101 Archive->Restore(0x0008,0x0010);
1103 // Restore 'LibIDO-special' entries, if any
1104 Archive->Restore(0x0028,0x0015);
1105 Archive->Restore(0x0028,0x0016);
1106 Archive->Restore(0x0028,0x0017);
1107 Archive->Restore(0x0028,0x00199);
1111 * \brief Duplicates a DataEntry or creates it.
1112 * @param group Group number of the Entry
1113 * @param elem Element number of the Entry
1114 * @param vr Value Representation of the Entry
1115 * FIXME : what is it used for?
1116 * \return pointer to the new Bin Entry (NULL when creation failed).
1118 DataEntry *FileHelper::CopyDataEntry(uint16_t group, uint16_t elem,
1121 DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1124 if ( oldE && vr != GDCM_UNKNOWN )
1125 if ( oldE->GetVR()!=vr )
1130 newE = new DataEntry(oldE->GetDictEntry());
1135 newE = GetFile()->NewDataEntry(group, elem, vr);
1142 * \brief This method is called automatically, just before writting
1143 * in order to produce a 'True Dicom V3' image
1144 * We cannot know *how* the user made the File (reading an old ACR-NEMA
1145 * file or a not very clean DICOM file ...)
1147 * Just before writting :
1148 * - we check the Entries
1149 * - we create the mandatory entries if they are missing
1150 * - we modify the values if necessary
1151 * - we push the sensitive entries to the Archive
1152 * The writing process will restore the entries as they where before
1153 * entering FileHelper::CheckMandatoryElements, so the user will always
1154 * see the entries just as he left them.
1156 * \todo : - warn the user if we had to add some entries :
1157 * even if a mandatory entry is missing, we add it, with a default value
1158 * (we don't want to give up the writting process if user forgot to
1159 * specify Lena's Patient ID, for instance ...)
1160 * - read the whole PS 3.3 Part of DICOM (890 pages)
1161 * and write a *full* checker (probably one method per Modality ...)
1162 * Any contribution is welcome.
1163 * - write a user callable full checker, to allow post reading
1164 * and/or pre writting image consistency check.
1167 void FileHelper::CheckMandatoryElements()
1169 // just to remember : 'official' 0002 group
1170 if ( WriteType != ACR && WriteType != ACR_LIBIDO )
1172 // Group 000002 (Meta Elements) already pushed out
1174 //0002 0000 UL 1 Meta Group Length
1175 //0002 0001 OB 1 File Meta Information Version
1176 //0002 0002 UI 1 Media Stored SOP Class UID
1177 //0002 0003 UI 1 Media Stored SOP Instance UID
1178 //0002 0010 UI 1 Transfer Syntax UID
1179 //0002 0012 UI 1 Implementation Class UID
1180 //0002 0013 SH 1 Implementation Version Name
1181 //0002 0016 AE 1 Source Application Entity Title
1182 //0002 0100 UI 1 Private Information Creator
1183 //0002 0102 OB 1 Private Information
1185 // Create them if not found
1186 // Always modify the value
1187 // Push the entries to the archive.
1188 CopyMandatoryEntry(0x0002,0x0000,"0");
1190 DataEntry *e_0002_0001 = CopyDataEntry(0x0002,0x0001, "OB");
1191 e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1193 e_0002_0001->SetLength(2);
1194 Archive->Push(e_0002_0001);
1196 // 'Media Stored SOP Class UID'
1197 // [Secondary Capture Image Storage]
1198 CopyMandatoryEntry(0x0002,0x0002,"1.2.840.10008.5.1.4.1.1.7");
1200 // 'Media Stored SOP Instance UID'
1201 CopyMandatoryEntry(0x0002,0x0003,Util::CreateUniqueUID());
1203 // 'Implementation Class UID'
1204 CopyMandatoryEntry(0x0002,0x0012,Util::CreateUniqueUID());
1206 // 'Implementation Version Name'
1207 std::string version = "GDCM ";
1208 version += Util::GetVersion();
1209 CopyMandatoryEntry(0x0002,0x0013,version);
1212 // Push out 'LibIDO-special' entries, if any
1213 Archive->Push(0x0028,0x0015);
1214 Archive->Push(0x0028,0x0016);
1215 Archive->Push(0x0028,0x0017);
1216 Archive->Push(0x0028,0x00199);
1218 // Deal with the pb of (Bits Stored = 12)
1219 // - we're gonna write the image as Bits Stored = 16
1220 if ( FileInternal->GetEntryString(0x0028,0x0100) == "12")
1222 CopyMandatoryEntry(0x0028,0x0100,"16");
1225 // Check if user wasn't drunk ;-)
1227 std::ostringstream s;
1228 // check 'Bits Allocated' vs decent values
1229 int nbBitsAllocated = FileInternal->GetBitsAllocated();
1230 if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1232 CopyMandatoryEntry(0x0028,0x0100,"16");
1233 gdcmWarningMacro("(0028,0100) changed from "
1234 << nbBitsAllocated << " to 16 for consistency purpose");
1235 nbBitsAllocated = 16;
1237 // check 'Bits Stored' vs 'Bits Allocated'
1238 int nbBitsStored = FileInternal->GetBitsStored();
1239 if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1242 s << nbBitsAllocated;
1243 CopyMandatoryEntry(0x0028,0x0101,s.str());
1244 gdcmWarningMacro("(0028,0101) changed from "
1245 << nbBitsStored << " to " << nbBitsAllocated
1246 << " for consistency purpose" );
1247 nbBitsStored = nbBitsAllocated;
1249 // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1250 int highBitPosition = FileInternal->GetHighBitPosition();
1251 if ( highBitPosition == 0 ||
1252 highBitPosition > nbBitsAllocated-1 ||
1253 highBitPosition < nbBitsStored-1 )
1256 s << nbBitsStored - 1;
1257 CopyMandatoryEntry(0x0028,0x0102,s.str());
1258 gdcmWarningMacro("(0028,0102) changed from "
1259 << highBitPosition << " to " << nbBitsAllocated-1
1260 << " for consistency purpose");
1262 // --- Check UID-related Entries ---
1264 // If 'SOP Class UID' exists ('true DICOM' image)
1265 // we create the 'Source Image Sequence' SeqEntry
1266 // to hold informations about the Source Image
1268 DataEntry *e_0008_0016 = FileInternal->GetDataEntry(0x0008, 0x0016);
1271 // Create 'Source Image Sequence' SeqEntry
1272 SeqEntry *sis = new SeqEntry (
1273 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1274 SQItem *sqi = new SQItem(1);
1275 // (we assume 'SOP Instance UID' exists too)
1276 // create 'Referenced SOP Class UID'
1277 DataEntry *e_0008_1150 = new DataEntry(
1278 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1279 e_0008_1150->SetString( e_0008_0016->GetString());
1280 sqi->AddEntry(e_0008_1150);
1282 // create 'Referenced SOP Instance UID'
1283 DataEntry *e_0008_0018 = FileInternal->GetDataEntry(0x0008, 0x0018);
1284 DataEntry *e_0008_1155 = new DataEntry(
1285 Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1286 e_0008_1155->SetString( e_0008_0018->GetString());
1287 sqi->AddEntry(e_0008_1155);
1289 sis->AddSQItem(sqi,1);
1290 // temporarily replaces any previous 'Source Image Sequence'
1293 // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1294 CopyMandatoryEntry(0x0008,0x0008,"DERIVED\\PRIMARY");
1298 // There was no 'SOP Class UID'.
1299 // the source image was NOT a true Dicom one.
1300 // We consider the image is a 'Secondary Capture' one
1302 // [Secondary Capture Image Storage]
1303 SetMandatoryEntry(0x0008,0x0016,"1.2.840.10008.5.1.4.1.1.7");
1306 // ---- The user will never have to take any action on the following ----.
1307 // new value for 'SOP Instance UID'
1308 SetMandatoryEntry(0x0008,0x0018,Util::CreateUniqueUID());
1310 // Instance Creation Date
1311 CopyMandatoryEntry(0x0008,0x0012,Util::GetCurrentDate().c_str());
1313 // Instance Creation Time
1314 CopyMandatoryEntry(0x0008,0x0013,Util::GetCurrentTime().c_str());
1316 // ----- Add Mandatory Entries if missing ---
1317 // Entries whose type is 1 are mandatory, with a mandatory value
1318 // Entries whose type is 1c are mandatory-inside-a-Sequence
1319 // Entries whose type is 2 are mandatory, with a optional value
1320 // Entries whose type is 2c are mandatory-inside-a-Sequence
1321 // Entries whose type is 3 are optional
1323 // 'Serie Instance UID'
1324 // Keep the value if exists
1325 // The user is allowed to create his own Series,
1326 // keeping the same 'Serie Instance UID' for various images
1327 // The user shouldn't add any image to a 'Manufacturer Serie'
1328 // but there is no way no to allowed him to do that
1329 CheckMandatoryEntry(0x0020,0x000e,Util::CreateUniqueUID());
1331 // 'Study Instance UID'
1332 // Keep the value if exists
1333 // The user is allowed to create his own Study,
1334 // keeping the same 'Study Instance UID' for various images
1335 // The user may add images to a 'Manufacturer Study',
1336 // adding new series to an already existing Study
1337 CheckMandatoryEntry(0x0020,0x000d,Util::CreateUniqueUID());
1339 // Modality : if missing we set it to 'OTher'
1340 CheckMandatoryEntry(0x0008,0x0060,"OT");
1342 // Manufacturer : if missing we set it to 'GDCM Factory'
1343 CheckMandatoryEntry(0x0008,0x0070,"GDCM Factory");
1345 // Institution Name : if missing we set it to 'GDCM Hospital'
1346 CheckMandatoryEntry(0x0008,0x0080,"GDCM Hospital");
1348 // Patient's Name : if missing, we set it to 'GDCM^Patient'
1349 CheckMandatoryEntry(0x0010,0x0010,"GDCM^Patient");
1351 // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1352 CheckMandatoryEntry(0x0010,0x0030,"");
1354 // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1355 CheckMandatoryEntry(0x0010,0x0040,"");
1357 // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1358 CheckMandatoryEntry(0x0008,0x0090,"");
1360 // Pixel Spacing : defaulted to 1.0\1.0
1361 CheckMandatoryEntry(0x0028,0x0030,"1.0\\1.0");
1363 // Remove some inconstencies (probably some more will be added)
1365 // if (0028 0008)Number of Frames exists
1366 // Push out (0020 0052),Frame of Reference UID
1367 // (only meaningfull within a Serie)
1368 DataEntry *e_0028_0008 = FileInternal->GetDataEntry(0x0028, 0x0008);
1371 Archive->Push(0x0020, 0X0052);
1375 void FileHelper::CheckMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1377 DataEntry *entry = FileInternal->GetDataEntry(group,elem);
1380 entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1381 entry->SetString(value);
1382 Archive->Push(entry);
1386 void FileHelper::SetMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1388 DataEntry *entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1389 entry->SetString(value);
1390 Archive->Push(entry);
1393 void FileHelper::CopyMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1395 DataEntry *entry = CopyDataEntry(group,elem);
1396 entry->SetString(value);
1397 Archive->Push(entry);
1401 * \brief Restore in the File the initial group 0002
1403 void FileHelper::RestoreWriteMandatory()
1405 // group 0002 may be pushed out for ACR-NEMA writting purposes
1406 Archive->Restore(0x0002,0x0000);
1407 Archive->Restore(0x0002,0x0001);
1408 Archive->Restore(0x0002,0x0002);
1409 Archive->Restore(0x0002,0x0003);
1410 Archive->Restore(0x0002,0x0010);
1411 Archive->Restore(0x0002,0x0012);
1412 Archive->Restore(0x0002,0x0013);
1413 Archive->Restore(0x0002,0x0016);
1414 Archive->Restore(0x0002,0x0100);
1415 Archive->Restore(0x0002,0x0102);
1417 Archive->Restore(0x0008,0x0012);
1418 Archive->Restore(0x0008,0x0013);
1419 Archive->Restore(0x0008,0x0016);
1420 Archive->Restore(0x0008,0x0018);
1421 Archive->Restore(0x0008,0x0060);
1422 Archive->Restore(0x0008,0x0070);
1423 Archive->Restore(0x0008,0x0080);
1424 Archive->Restore(0x0008,0x0090);
1425 Archive->Restore(0x0008,0x2112);
1427 Archive->Restore(0x0010,0x0010);
1428 Archive->Restore(0x0010,0x0030);
1429 Archive->Restore(0x0010,0x0040);
1431 Archive->Restore(0x0020,0x000d);
1432 Archive->Restore(0x0020,0x000e);
1436 //-----------------------------------------------------------------------------
1439 * \brief Factorization for various forms of constructors.
1441 void FileHelper::Initialize()
1445 WriteMode = WMODE_RAW;
1446 WriteType = ExplicitVR;
1448 PixelReadConverter = new PixelReadConvert;
1449 PixelWriteConverter = new PixelWriteConvert;
1450 Archive = new DocEntryArchive( FileInternal );
1454 * \brief Reads/[decompresses] the pixels,
1455 * *without* making RGB from Palette Colors
1456 * @return the pixels area, whatever its type
1457 * (uint8_t is just for prototyping : feel free to Cast it)
1459 uint8_t *FileHelper::GetRaw()
1461 PixelReadConverter->SetUserFunction( UserFunction );
1463 uint8_t *raw = PixelReadConverter->GetRaw();
1466 // The Raw image migth not be loaded yet:
1467 std::ifstream *fp = FileInternal->OpenFile();
1468 PixelReadConverter->ReadAndDecompressPixelData( fp );
1470 FileInternal->CloseFile();
1472 raw = PixelReadConverter->GetRaw();
1475 gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1482 //-----------------------------------------------------------------------------
1484 * \brief Prints the common part of DataEntry, SeqEntry
1485 * @param os ostream we want to print in
1486 * @param indent (unused)
1488 void FileHelper::Print(std::ostream &os, std::string const &)
1490 FileInternal->SetPrintLevel(PrintLevel);
1491 FileInternal->Print(os);
1493 if ( FileInternal->IsReadable() )
1495 PixelReadConverter->SetPrintLevel(PrintLevel);
1496 PixelReadConverter->Print(os);
1500 //-----------------------------------------------------------------------------
1501 } // end namespace gdcm