1 /*=========================================================================
4 Module: $RCSfile: gdcmFileHelper.cxx,v $
7 Date: $Date: 2006/07/04 07:58:51 $
8 Version: $Revision: 1.106 $
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"
29 #include "gdcmDocEntry.h"
31 #include "gdcmPixelReadConvert.h"
32 #include "gdcmPixelWriteConvert.h"
33 #include "gdcmDocEntryArchive.h"
34 #include "gdcmDictSet.h"
35 #include "gdcmOrientation.h"
37 #if defined(__BORLANDC__)
38 #include <mem.h> // for memset
44 // ----------------------------- WARNING -------------------------
46 These lines will be moved to the document-to-be 'User's Guide'
48 // To read an image, user needs a gdcm::File
49 gdcm::File *f = new gdcm::File(fileName);
51 // user may also decide he doesn't want to load some parts of the header
52 gdcm::File *f = new gdcm::File();
53 f->SetFileName(fileName);
54 f->SetLoadMode(LD_NOSEQ); // or
55 f->SetLoadMode(LD_NOSHADOW); // or
56 f->SetLoadMode(LD_NOSEQ | LD_NOSHADOW); // or
57 f->SetLoadMode(LD_NOSHADOWSEQ);
60 // user can now check some values
61 std::string v = f->GetEntryValue(groupNb,ElementNb);
63 // to get the pixels, user needs a gdcm::FileHelper
64 gdcm::FileHelper *fh = new gdcm::FileHelper(f);
65 // user may ask not to convert Palette to RGB
66 uint8_t *pixels = fh->GetImageDataRaw();
67 int imageLength = fh->GetImageDataRawSize();
68 // He can now use the pixels, create a new image, ...
69 uint8_t *userPixels = ...
71 To re-write the image, user re-uses the gdcm::FileHelper
73 fh->SetImageData( userPixels, userPixelsLength);
74 fh->SetTypeToRaw(); // Even if it was possible to convert Palette to RGB
77 fh->SetWriteTypeToDcmExpl(); // he wants Explicit Value Representation
78 // Little Endian is the default
79 // no other value is allowed
80 (-->SetWriteType(ExplicitVR);)
81 -->WriteType = ExplicitVR;
82 fh->Write(newFileName); // overwrites the file, if any
85 fh->WriteDcmExplVR(newFileName);
88 // ----------------------------- WARNING -------------------------
90 These lines will be moved to the document-to-be 'Developer's Guide'
92 WriteMode : WMODE_RAW / WMODE_RGB
93 WriteType : ImplicitVR, ExplicitVR, ACR, ACR_LIBIDO
95 fh1->Write(newFileName);
96 SetWriteFileTypeToImplicitVR() / SetWriteFileTypeToExplicitVR();
97 (modifies TransferSyntax)
98 SetWriteToRaw(); / SetWriteToRGB();
99 (modifies, when necessary : photochromatic interpretation,
100 samples per pixel, Planar configuration,
101 bits allocated, bits stored, high bit -ACR 24 bits-
102 Pixels element VR, pushes out the LUT )
103 CheckWriteIntegrity();
104 (checks user given pixels length)
105 FileInternal->Write(fileName,WriteType)
106 fp = opens file(fileName);
107 ComputeGroup0002Length( );
109 RemoveEntry(palettes, etc)
110 Document::WriteContent(fp, writetype);
112 (moves back to the File all the archived elements)
113 RestoreWriteFileType();
114 (pushes back group 0002, with TransferSyntax)
122 typedef std::map<uint16_t, int> GroupHT; // Hash Table
123 //-------------------------------------------------------------------------
124 // Constructor / Destructor
126 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
127 * file (gdcm::File only deals with the ... header)
128 * Opens (in read only and when possible) an existing file and checks
129 * for DICOM compliance. Returns NULL on failure.
130 * It will be up to the user to load the pixels into memory
131 * ( GetImageDataSize() + GetImageData() methods)
132 * \note the in-memory representation of all available tags found in
133 * the DICOM header is post-poned to first header information access.
134 * This avoid a double parsing of public part of the header when
135 * one sets an a posteriori shadow dictionary (efficiency can be
136 * seen as a side effect).
138 FileHelper::FileHelper( )
140 FileInternal = File::New( );
145 * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
146 * file (File only deals with the ... header)
147 * Opens (in read only and when possible) an existing file and checks
148 * for DICOM compliance. Returns NULL on failure.
149 * It will be up to the user to load the pixels into memory
150 * ( GetImageDataSize() + GetImageData() methods)
151 * \note the in-memory representation of all available tags found in
152 * the DICOM header is post-poned to first header information access.
153 * This avoid a double parsing of public part of the header when
154 * user sets an a posteriori shadow dictionary (efficiency can be
155 * seen as a side effect).
156 * @param header already built Header
158 FileHelper::FileHelper(File *header)
160 gdcmAssertMacro(header);
162 FileInternal = header;
163 FileInternal->Register();
165 if ( FileInternal->IsReadable() )
167 PixelReadConverter->GrabInformationsFromFile( FileInternal, this );
172 * \brief canonical destructor
173 * \note If the header (gdcm::File) was created by the FileHelper constructor,
174 * it is destroyed by the FileHelper
176 FileHelper::~FileHelper()
178 if ( PixelReadConverter )
180 delete PixelReadConverter;
182 if ( PixelWriteConverter )
184 delete PixelWriteConverter;
191 FileInternal->Unregister();
194 //-----------------------------------------------------------------------------
198 * \brief Sets the LoadMode of the internal gdcm::File as a boolean string.
199 * NO_SEQ, NO_SHADOW, NO_SHADOWSEQ ... (nothing more, right now)
200 * WARNING : before using NO_SHADOW, be sure *all* your files
201 * contain accurate values in the 0x0000 element (if any)
202 * of *each* Shadow Group. The parser will fail if the size is wrong !
203 * @param loadMode Load mode to be used
205 void FileHelper::SetLoadMode(int loadMode)
207 GetFile()->SetLoadMode( loadMode );
210 * \brief Sets the LoadMode of the internal gdcm::File
211 * @param fileName name of the file to be open
213 void FileHelper::SetFileName(std::string const &fileName)
215 FileInternal->SetFileName( fileName );
220 * @return false if file cannot be open or no swap info was found,
221 * or no tag was found.
223 bool FileHelper::Load()
225 if ( !FileInternal->Load() )
228 PixelReadConverter->GrabInformationsFromFile( FileInternal, this );
233 * \brief Accesses an existing DataEntry through it's (group, element)
234 * and modifies it's content with the given value.
235 * @param content new value (string) to substitute with
236 * @param group group number of the Dicom Element to modify
237 * @param elem element number of the Dicom Element to modify
238 * \return false if DataEntry not found
240 bool FileHelper::SetEntryString(std::string const &content,
241 uint16_t group, uint16_t elem)
243 return FileInternal->SetEntryString(content, group, elem);
248 * \brief Accesses an existing DataEntry through it's (group, element)
249 * and modifies it's content with the given value.
250 * @param content new value (void* -> uint8_t*) to substitute with
251 * @param lgth new value length
252 * @param group group number of the Dicom Element to modify
253 * @param elem element number of the Dicom Element to modify
254 * \return false if DataEntry not found
256 bool FileHelper::SetEntryBinArea(uint8_t *content, int lgth,
257 uint16_t group, uint16_t elem)
259 return FileInternal->SetEntryBinArea(content, lgth, group, elem);
263 * \brief Modifies the value of a given DataEntry when it exists.
264 * Creates it with the given value when unexistant.
265 * @param content (string) value to be set
266 * @param group Group number of the Entry
267 * @param elem Element number of the Entry
268 * \return pointer to the modified/created DataEntry (NULL when creation
271 DataEntry *FileHelper::InsertEntryString(std::string const &content,
272 uint16_t group, uint16_t elem,
275 return FileInternal->InsertEntryString(content, group, elem, vr);
279 * \brief Modifies the value of a given DataEntry when it exists.
280 * Creates it with the given value when unexistant.
281 * A copy of the binArea is made to be kept in the Document.
282 * @param binArea (binary)value to be set
283 * @param lgth new value length
284 * @param group Group number of the Entry
285 * @param elem Element number of the Entry
286 * @param vr Value Represenation of the DataElement to be inserted
287 * \return pointer to the modified/created DataEntry (NULL when creation
290 DataEntry *FileHelper::InsertEntryBinArea(uint8_t *binArea, int lgth,
291 uint16_t group, uint16_t elem,
294 return FileInternal->InsertEntryBinArea(binArea, lgth, group, elem, vr);
298 * \brief Adds an empty SeqEntry
299 * (remove any existing entry with same group,elem)
300 * @param group Group number of the Entry
301 * @param elem Element number of the Entry
302 * \return pointer to the created SeqEntry (NULL when creation
305 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
307 return FileInternal->InsertSeqEntry(group, elem);
311 * \brief Get the size of the image data
312 * If the image can be RGB (with a lut or by default), the size
313 * corresponds to the RGB image
314 * (use GetImageDataRawSize if you want to be sure to get *only*
315 * the size of the pixels)
316 * @return The image size
318 size_t FileHelper::GetImageDataSize()
320 if ( PixelWriteConverter->GetUserData() )
322 return PixelWriteConverter->GetUserDataSize();
324 return PixelReadConverter->GetRGBSize();
328 * \brief Get the size of the image data.
329 * If the image could be converted to RGB using a LUT,
330 * this transformation is not taken into account by GetImageDataRawSize
331 * (use GetImageDataSize if you wish)
332 * @return The raw image size
334 size_t FileHelper::GetImageDataRawSize()
336 if ( PixelWriteConverter->GetUserData() )
338 return PixelWriteConverter->GetUserDataSize();
340 return PixelReadConverter->GetRawSize();
344 * \brief brings pixels into memory :
345 * - Allocates necessary memory,
346 * - Reads the pixels from disk (uncompress if necessary),
347 * - Transforms YBR pixels, if any, into RGB pixels,
348 * - Transforms 3 planes R, G, B, if any, into a single RGB Plane
349 * - Transforms single Grey plane + 3 Palettes into a RGB Plane
350 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
351 * @return Pointer to newly allocated pixel data.
352 * (uint8_t is just for prototyping. feel free to cast)
353 * NULL if alloc fails
355 uint8_t *FileHelper::GetImageData()
357 if ( PixelWriteConverter->GetUserData() )
359 return PixelWriteConverter->GetUserData();
364 // If the decompression failed nothing can be done.
368 if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
370 return PixelReadConverter->GetRGB();
374 // When no LUT or LUT conversion fails, return the Raw
375 return PixelReadConverter->GetRaw();
380 * \brief brings pixels into memory :
381 * - Allocates necessary memory,
382 * - Transforms YBR pixels (if any) into RGB pixels
383 * - Transforms 3 planes R, G, B (if any) into a single RGB Plane
384 * - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
385 * - DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
386 * @return Pointer to newly allocated pixel data.
387 * (uint8_t is just for prototyping. feel free to cast)
388 * NULL if alloc fails
390 uint8_t *FileHelper::GetImageDataRaw ()
395 //#ifndef GDCM_LEGACY_REMOVE
397 * \brief Useless function, since PixelReadConverter forces us
398 * copy the Pixels anyway.
399 * Reads the pixels from disk (uncompress if necessary),
400 * Transforms YBR pixels, if any, into RGB pixels
401 * Transforms 3 planes R, G, B, if any, into a single RGB Plane
402 * Transforms single Grey plane + 3 Palettes into a RGB Plane
403 * Copies at most MaxSize bytes of pixel data to caller allocated
405 * \warning This function allows people that want to build a volume
406 * from an image stack *not to* have, first to get the image pixels,
407 * and then move them to the volume area.
408 * It's absolutely useless for any VTK user since vtk chooses
409 * to invert the lines of an image, that is the last line comes first
410 * (for some axis related reasons?). Hence he will have
411 * to load the image line by line, starting from the end.
412 * VTK users have to call GetImageData
414 * @param destination Address (in caller's memory space) at which the
415 * pixel data should be copied
416 * @param maxSize Maximum number of bytes to be copied. When MaxSize
417 * is not sufficient to hold the pixel data the copy is not
418 * executed (i.e. no partial copy).
419 * @return On success, the number of bytes actually copied. Zero on
420 * failure e.g. MaxSize is lower than necessary.
423 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
427 // If the decompression failed nothing can be done.
431 if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
433 if ( PixelReadConverter->GetRGBSize() > maxSize )
435 gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
439 (void*)PixelReadConverter->GetRGB(),
440 PixelReadConverter->GetRGBSize() );
441 return PixelReadConverter->GetRGBSize();
444 // Either no LUT conversion necessary or LUT conversion failed
445 if ( PixelReadConverter->GetRawSize() > maxSize )
447 gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
451 (void *)PixelReadConverter->GetRaw(),
452 PixelReadConverter->GetRawSize() );
453 return PixelReadConverter->GetRawSize();
459 * \brief Points the internal pointer to the callers inData
460 * image representation, BUT WITHOUT COPYING THE DATA.
461 * 'image' Pixels are presented as C-like 2D arrays : line per line.
462 * 'volume'Pixels are presented as C-like 3D arrays : plane per plane
463 * \warning Since the pixels are not copied, it is the caller's responsability
464 * not to deallocate its data before gdcm uses them (e.g. with
465 * the Write() method )
466 * @param inData user supplied pixel area (uint8_t* is just for the compiler.
467 * user is allowed to pass any kind of pixelsn since the size is
469 * @param expectedSize total image size, *in Bytes*
471 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
473 SetUserData(inData, expectedSize);
477 * \brief Set the image data defined by the user
478 * \warning When writting the file, this data are get as default data to write
479 * @param inData user supplied pixel area (uint8_t* is just for the compiler.
480 * user is allowed to pass any kind of pixels since the size is
482 * @param expectedSize total image size, *in Bytes*
484 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
486 PixelWriteConverter->SetUserData(inData, expectedSize);
490 * \brief Get the image data defined by the user
491 * \warning When writting the file, this data are get as default data to write
493 uint8_t *FileHelper::GetUserData()
495 return PixelWriteConverter->GetUserData();
499 * \brief Get the image data size defined by the user
500 * \warning When writting the file, this data are get as default data to write
502 size_t FileHelper::GetUserDataSize()
504 return PixelWriteConverter->GetUserDataSize();
508 * \brief Get the image data from the file.
509 * If a LUT is found, the data are expanded to be RGB
511 uint8_t *FileHelper::GetRGBData()
513 return PixelReadConverter->GetRGB();
517 * \brief Get the image data size from the file.
518 * If a LUT is found, the data are expanded to be RGB
520 size_t FileHelper::GetRGBDataSize()
522 return PixelReadConverter->GetRGBSize();
526 * \brief Get the image data from the file.
527 * Even when a LUT is found, the data are not expanded to RGB!
529 uint8_t *FileHelper::GetRawData()
531 return PixelReadConverter->GetRaw();
535 * \brief Get the image data size from the file.
536 * Even when a LUT is found, the data are not expanded to RGB!
538 size_t FileHelper::GetRawDataSize()
540 return PixelReadConverter->GetRawSize();
544 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
546 uint8_t* FileHelper::GetLutRGBA()
548 if ( PixelReadConverter->GetLutRGBA() ==0 )
549 PixelReadConverter->BuildLUTRGBA();
550 return PixelReadConverter->GetLutRGBA();
554 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Number
556 int FileHelper::GetLutItemNumber()
558 return PixelReadConverter->GetLutItemNumber();
562 * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Size
564 int FileHelper::GetLutItemSize()
566 return PixelReadConverter->GetLutItemSize();
570 * \brief Writes on disk A SINGLE Dicom file
571 * NO test is performed on processor "Endiannity".
572 * It's up to the user to call his Reader properly
573 * @param fileName name of the file to be created
574 * (any already existing file is over written)
575 * @return false if write fails
577 bool FileHelper::WriteRawData(std::string const &fileName)
579 std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
582 gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
586 if ( PixelWriteConverter->GetUserData() )
588 fp1.write( (char *)PixelWriteConverter->GetUserData(),
589 PixelWriteConverter->GetUserDataSize() );
591 else if ( PixelReadConverter->GetRGB() )
593 fp1.write( (char *)PixelReadConverter->GetRGB(),
594 PixelReadConverter->GetRGBSize());
596 else if ( PixelReadConverter->GetRaw() )
598 fp1.write( (char *)PixelReadConverter->GetRaw(),
599 PixelReadConverter->GetRawSize());
603 gdcmErrorMacro( "Nothing written." );
612 * \brief Writes on disk A SINGLE Dicom file,
613 * using the Implicit Value Representation convention
614 * NO test is performed on processor "Endianity".
615 * @param fileName name of the file to be created
616 * (any already existing file is overwritten)
617 * @return false if write fails
620 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
622 SetWriteTypeToDcmImplVR();
623 return Write(fileName);
627 * \brief Writes on disk A SINGLE Dicom file,
628 * using the Explicit Value Representation convention
629 * NO test is performed on processor "Endiannity".
630 * @param fileName name of the file to be created
631 * (any already existing file is overwritten)
632 * @return false if write fails
635 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
637 SetWriteTypeToDcmExplVR();
638 return Write(fileName);
642 * \brief Writes on disk A SINGLE Dicom file,
643 * using the ACR-NEMA convention
644 * NO test is performed on processor "Endiannity".
645 * (a l'attention des logiciels cliniques
646 * qui ne prennent en entrée QUE des images ACR ...
647 * \warning if a DICOM_V3 header is supplied,
648 * groups < 0x0008 and shadow groups are ignored
649 * \warning 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::WriteAcr (std::string const &fileName)
658 return Write(fileName);
662 * \brief Writes on disk A SINGLE Dicom file,
663 * @param fileName name of the file to be created
664 * (any already existing file is overwritten)
665 * @return false if write fails
667 bool FileHelper::Write(std::string const &fileName)
670 CheckMandatoryElements(); //called once, here !
677 SetWriteFileTypeToImplicitVR();
680 case Unknown: // should never happen; ExplicitVR is the default value
683 // User should ask gdcm to write an image in Explicit VR mode
684 // only when he is sure *all* the VR of *all* the DataElements is known.
685 // i.e : when there are *only* Public Groups
686 // or *all* the Shadow Groups are fully described in the relevant Shadow
688 // Let's just *dream* about it; *never* trust a user !
689 // We turn to Implicit VR if at least the VR of one element is unknown.
692 e = FileInternal->GetFirstEntry();
695 if (e->GetVR() == " ")
697 SetWriteTypeToDcmImplVR();
698 SetWriteFileTypeToImplicitVR();
702 e = FileInternal->GetNextEntry();
707 SetWriteFileTypeToExplicitVR();
711 SetWriteFileTypeToExplicitVR(); // to see JPRx
715 // NOTHING is done here just for LibIDO.
716 // Just to avoid further trouble if user creates a file ex-nihilo,
717 // wants to write it as an ACR-NEMA file,
718 // and forgets to create any Entry belonging to group 0008
720 // We add Recognition Code (RET)
721 if ( ! FileInternal->GetDataEntry(0x0008, 0x0010) )
722 FileInternal->InsertEntryString("ACR-NEMA V1.0 ",
723 0x0008, 0x0010, "LO");
724 SetWriteFileTypeToACR();
725 // SetWriteFileTypeToImplicitVR(); // ACR IS implicit VR !
728 /// \todo FIXME : JPEG may be either ExplicitVR or ImplicitVR
730 SetWriteFileTypeToJPEG();
734 // --------------------------------------------------------------
735 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
737 // if recognition code tells us we dealt with a LibIDO image
738 // we reproduce on disk the switch between lineNumber and columnNumber
739 // just before writting ...
740 /// \todo the best trick would be *change* the recognition code
741 /// but pb expected if user deals with, e.g. COMPLEX images
743 if ( WriteType == ACR_LIBIDO )
749 SetWriteToNoLibido();
751 // ----------------- End of Special Patch ----------------
756 SetWriteToRaw(); // modifies and pushes to the archive, when necessary
759 SetWriteToRGB(); // modifies and pushes to the archive, when necessary
763 bool check = CheckWriteIntegrity(); // verifies length
764 if (WriteType == JPEG ) check = true;
767 check = FileInternal->Write(fileName,WriteType);
771 // RestoreWriteFileType();
772 // RestoreWriteMandatory();
775 // --------------------------------------------------------------
776 // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
778 // ...and we restore the header to be Dicom Compliant again
779 // just after writting
780 RestoreWriteOfLibido();
781 // ----------------- End of Special Patch ----------------
786 //-----------------------------------------------------------------------------
789 * \brief Checks the write integrity
791 * The tests made are :
792 * - verify the size of the image to write with the possible write
793 * when the user set an image data
794 * @return true if check is successfull
796 bool FileHelper::CheckWriteIntegrity()
798 if ( PixelWriteConverter->GetUserData() )
800 int numberBitsAllocated = FileInternal->GetBitsAllocated();
801 if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
803 gdcmWarningMacro( "numberBitsAllocated changed from "
804 << numberBitsAllocated << " to 16 "
805 << " for consistency purpose" );
806 numberBitsAllocated = 16;
809 size_t decSize = FileInternal->GetXSize()
810 * FileInternal->GetYSize()
811 * FileInternal->GetZSize()
812 * FileInternal->GetTSize()
813 * FileInternal->GetSamplesPerPixel()
814 * ( numberBitsAllocated / 8 );
815 size_t rgbSize = decSize;
816 if ( FileInternal->HasLUT() )
817 rgbSize = decSize * 3;
822 if ( decSize!=PixelWriteConverter->GetUserDataSize() )
824 gdcmWarningMacro( "Data size (Raw) is incorrect. Should be "
825 << decSize << " / Found :"
826 << PixelWriteConverter->GetUserDataSize() );
831 if ( rgbSize!=PixelWriteConverter->GetUserDataSize() )
833 gdcmWarningMacro( "Data size (RGB) is incorrect. Should be "
834 << decSize << " / Found "
835 << PixelWriteConverter->GetUserDataSize() );
846 * \brief Updates the File to write RAW data (as opposed to RGB data)
847 * (modifies, when necessary, photochromatic interpretation,
848 * bits allocated, Pixels element VR)
850 void FileHelper::SetWriteToRaw()
852 if ( FileInternal->GetNumberOfScalarComponents() == 3
853 && !FileInternal->HasLUT() )
859 DataEntry *photInt = CopyDataEntry(0x0028,0x0004,"CS");
860 if (FileInternal->HasLUT() )
862 photInt->SetString("PALETTE COLOR ");
866 photInt->SetString("MONOCHROME2 ");
869 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
870 PixelReadConverter->GetRawSize());
872 std::string vr = "OB";
873 if ( FileInternal->GetBitsAllocated()>8 )
875 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
877 // For non RAW data. Mainly JPEG
878 if( WriteType == JPEG )
883 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
884 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
885 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
886 pixel->SetLength(PixelWriteConverter->GetDataSize());
888 Archive->Push(photInt);
889 Archive->Push(pixel);
897 * \brief Updates the File to write RGB data (as opposed to RAW data)
898 * (modifies, when necessary, photochromatic interpretation,
899 * samples per pixel, Planar configuration,
900 * bits allocated, bits stored, high bit -ACR 24 bits-
901 * Pixels element VR, pushes out the LUT, )
903 void FileHelper::SetWriteToRGB()
905 if ( FileInternal->GetNumberOfScalarComponents()==3 )
907 PixelReadConverter->BuildRGBImage();
909 DataEntry *spp = CopyDataEntry(0x0028,0x0002,"US");
910 spp->SetString("3 ");
912 DataEntry *planConfig = CopyDataEntry(0x0028,0x0006,"US");
913 planConfig->SetString("0 ");
915 DataEntry *photInt = CopyDataEntry(0x0028,0x0004,"CS");
916 photInt->SetString("RGB ");
918 if ( PixelReadConverter->GetRGB() )
920 PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
921 PixelReadConverter->GetRGBSize());
925 PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
926 PixelReadConverter->GetRawSize());
929 std::string vr = "OB";
930 if ( FileInternal->GetBitsAllocated()>8 )
932 if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files
935 CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
936 pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
937 pixel->SetBinArea(PixelWriteConverter->GetData(),false);
938 pixel->SetLength(PixelWriteConverter->GetDataSize());
941 Archive->Push(planConfig);
942 Archive->Push(photInt);
943 Archive->Push(pixel);
946 planConfig->Delete();
951 Archive->Push(0x0028,0x1101);
952 Archive->Push(0x0028,0x1102);
953 Archive->Push(0x0028,0x1103);
954 Archive->Push(0x0028,0x1201);
955 Archive->Push(0x0028,0x1202);
956 Archive->Push(0x0028,0x1203);
958 // push out Palette Color Lookup Table UID, if any
959 Archive->Push(0x0028,0x1199);
961 // For old '24 Bits' ACR-NEMA
962 // Thus, we have a RGB image and the bits allocated = 24 and
963 // samples per pixels = 1 (in the read file)
964 if ( FileInternal->GetBitsAllocated()==24 )
966 DataEntry *bitsAlloc = CopyDataEntry(0x0028,0x0100,"US");
967 bitsAlloc->SetString("8 ");
969 DataEntry *bitsStored = CopyDataEntry(0x0028,0x0101,"US");
970 bitsStored->SetString("8 ");
972 DataEntry *highBit = CopyDataEntry(0x0028,0x0102,"US");
973 highBit->SetString("7 ");
975 Archive->Push(bitsAlloc);
976 Archive->Push(bitsStored);
977 Archive->Push(highBit);
980 bitsStored->Delete();
991 * \brief Restore the File write mode
993 void FileHelper::RestoreWrite()
996 Archive->Restore(0x0028,0x0002);
997 Archive->Restore(0x0028,0x0004);
999 Archive->Restore(0x0028,0x0006);
1000 Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
1002 // For old ACR-NEMA (24 bits problem)
1003 Archive->Restore(0x0028,0x0100);
1004 Archive->Restore(0x0028,0x0101);
1005 Archive->Restore(0x0028,0x0102);
1008 Archive->Restore(0x0028,0x1101);
1009 Archive->Restore(0x0028,0x1102);
1010 Archive->Restore(0x0028,0x1103);
1011 Archive->Restore(0x0028,0x1201);
1012 Archive->Restore(0x0028,0x1202);
1013 Archive->Restore(0x0028,0x1203);
1015 // For the Palette Color Lookup Table UID
1016 Archive->Restore(0x0028,0x1203);
1018 // group 0002 may be pushed out for ACR-NEMA writting purposes
1019 Archive->Restore(0x0002,0x0000);
1020 Archive->Restore(0x0002,0x0001);
1021 Archive->Restore(0x0002,0x0002);
1022 Archive->Restore(0x0002,0x0003);
1023 Archive->Restore(0x0002,0x0010);
1024 Archive->Restore(0x0002,0x0012);
1025 Archive->Restore(0x0002,0x0013);
1026 Archive->Restore(0x0002,0x0016);
1027 Archive->Restore(0x0002,0x0100);
1028 Archive->Restore(0x0002,0x0102);
1033 * \brief Pushes out the whole group 0002
1034 * FIXME : better, set a flag to tell the writer not to write it ...
1035 * FIXME : method should probably have an other name !
1036 * SetWriteFileTypeToACR is NOT opposed to
1037 * SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
1039 void FileHelper::SetWriteFileTypeToACR()
1041 Archive->Push(0x0002,0x0000);
1042 Archive->Push(0x0002,0x0001);
1043 Archive->Push(0x0002,0x0002);
1044 Archive->Push(0x0002,0x0003);
1045 Archive->Push(0x0002,0x0010);
1046 Archive->Push(0x0002,0x0012);
1047 Archive->Push(0x0002,0x0013);
1048 Archive->Push(0x0002,0x0016);
1049 Archive->Push(0x0002,0x0100);
1050 Archive->Push(0x0002,0x0102);
1054 * \brief Sets in the File the TransferSyntax to 'JPEG'
1056 void FileHelper::SetWriteFileTypeToJPEG()
1058 std::string ts = Util::DicomString(
1059 Global::GetTS()->GetSpecialTransferSyntax(TS::JPEGBaselineProcess1) );
1061 DataEntry *tss = CopyDataEntry(0x0002,0x0010,"UI");
1069 * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"
1071 void FileHelper::SetWriteFileTypeToExplicitVR()
1073 std::string ts = Util::DicomString(
1074 Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
1076 DataEntry *tss = CopyDataEntry(0x0002,0x0010,"UI");
1083 * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"
1085 void FileHelper::SetWriteFileTypeToImplicitVR()
1087 std::string ts = Util::DicomString(
1088 Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
1090 DataEntry *tss = CopyDataEntry(0x0002,0x0010,"UI");
1098 * \brief Restore in the File the initial group 0002
1100 void FileHelper::RestoreWriteFileType()
1105 * \brief Set the Write not to Libido format
1107 void FileHelper::SetWriteToLibido()
1109 DataEntry *oldRow = FileInternal->GetDataEntry(0x0028, 0x0010);
1110 DataEntry *oldCol = FileInternal->GetDataEntry(0x0028, 0x0011);
1112 if ( oldRow && oldCol )
1114 std::string rows, columns;
1116 //DataEntry *newRow=DataEntry::New(oldRow->GetDictEntry());
1117 //DataEntry *newCol=DataEntry::New(oldCol->GetDictEntry());
1119 DataEntry *newRow=DataEntry::New(0x0028, 0x0010, "US");
1120 DataEntry *newCol=DataEntry::New(0x0028, 0x0011, "US");
1122 newRow->Copy(oldCol);
1123 newCol->Copy(oldRow);
1125 newRow->SetString(oldCol->GetString());
1126 newCol->SetString(oldRow->GetString());
1128 Archive->Push(newRow);
1129 Archive->Push(newCol);
1135 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010,"LO");
1136 libidoCode->SetString("ACRNEMA_LIBIDO_1.1");
1137 Archive->Push(libidoCode);
1138 libidoCode->Delete();
1142 * \brief Set the Write not to No Libido format
1144 void FileHelper::SetWriteToNoLibido()
1146 DataEntry *recCode = FileInternal->GetDataEntry(0x0008,0x0010);
1149 if ( recCode->GetString() == "ACRNEMA_LIBIDO_1.1" )
1151 DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010,"LO");
1152 libidoCode->SetString("");
1153 Archive->Push(libidoCode);
1154 libidoCode->Delete();
1160 * \brief Restore the Write format
1162 void FileHelper::RestoreWriteOfLibido()
1164 Archive->Restore(0x0028,0x0010);
1165 Archive->Restore(0x0028,0x0011);
1166 Archive->Restore(0x0008,0x0010);
1168 // Restore 'LibIDO-special' entries, if any
1169 Archive->Restore(0x0028,0x0015);
1170 Archive->Restore(0x0028,0x0016);
1171 Archive->Restore(0x0028,0x0017);
1172 Archive->Restore(0x0028,0x00199);
1176 * \brief Duplicates a DataEntry or creates it.
1177 * @param group Group number of the Entry
1178 * @param elem Element number of the Entry
1179 * @param vr Value Representation of the Entry
1180 * \return pointer to the new Bin Entry (NULL when creation failed).
1182 DataEntry *FileHelper::CopyDataEntry(uint16_t group, uint16_t elem,
1185 DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1188 if ( oldE && vr != GDCM_VRUNKNOWN )
1189 if ( oldE->GetVR() != vr )
1194 //newE = DataEntry::New(oldE->GetDictEntry());
1195 newE = DataEntry::New(group, elem, vr);
1200 newE = GetFile()->NewDataEntry(group, elem, vr);
1207 * \brief This method is called automatically, just before writting
1208 * in order to produce a 'True Dicom V3' image.
1210 * We cannot know *how* the user made the File :
1211 * (reading an old ACR-NEMA file or a not very clean DICOM file ...)
1212 * Just before writting :
1213 * - we check the Entries
1214 * - we create the mandatory entries if they are missing
1215 * - we modify the values if necessary
1216 * - we push the sensitive entries to the Archive
1217 * The writing process will restore the entries as they where before
1218 * entering FileHelper::CheckMandatoryElements, so the user will always
1219 * see the entries just as they were before he decided to write.
1222 * - Entries whose type is 1 are mandatory, with a mandatory value
1223 * - Entries whose type is 1c are mandatory-inside-a-Sequence,
1224 * with a mandatory value
1225 * - Entries whose type is 2 are mandatory, with an optional value
1226 * - Entries whose type is 2c are mandatory-inside-a-Sequence,
1227 * with an optional value
1228 * - Entries whose type is 3 are optional
1231 * - warn the user if we had to add some entries :
1232 * even if a mandatory entry is missing, we add it, with a default value
1233 * (we don't want to give up the writting process if user forgot to
1234 * specify Lena's Patient ID, for instance ...)
1235 * - read the whole PS 3.3 Part of DICOM (890 pages)
1236 * and write a *full* checker (probably one method per Modality ...)
1237 * Any contribution is welcome.
1238 * - write a user callable full checker, to allow post reading
1239 * and/or pre writting image consistency check.
1242 /* -------------------------------------------------------------------------------------
1243 To be moved to User's guide / WIKI ?
1245 We have to deal with 4 *very* different cases :
1246 -1) user created ex nihilo his own image and wants to write it as a Dicom image.
1248 -2) user modified the pixels of an existing image.
1250 -3) user created a new image, using a set of existing images (eg MIP, MPR, cartography image)
1252 -4) user modified/added some tags *without processing* the pixels (anonymization..
1253 UNMODIFIED_PIXELS_IMAGE
1254 -Probabely some more to be added
1256 gdcm::FileHelper::CheckMandatoryElements() deals automatically with these cases.
1259 0008 0012 Instance Creation Date
1260 0008 0013 Instance Creation Time
1261 0008 0018 SOP Instance UID
1262 are *always* created with the current values; user has *no* possible intervention on
1265 'Serie Instance UID'(0x0020,0x000e)
1266 'Study Instance UID'(0x0020,0x000d) are kept as is if already exist,
1267 created if it doesn't.
1268 The user is allowed to create his own Series/Studies,
1269 keeping the same 'Serie Instance UID' / 'Study Instance UID' for various images
1271 The user shouldn't add any image to a 'Manufacturer Serie'
1272 but there is no way no to allow him to do that
1274 None of the 'shadow elements' are droped out.
1278 'Conversion Type (0x0008,0x0064) is forced to 'SYN' (Synthetic Image).
1281 'Media Storage SOP Class UID' (0x0002,0x0002)
1282 'SOP Class UID' (0x0008,0x0016) are set to
1283 [Secondary Capture Image Storage]
1284 'Image Type' (0x0008,0x0008) is forced to "DERIVED\PRIMARY"
1285 Conversion Type (0x0008,0x0064) is forced to 'SYN' (Synthetic Image)
1288 If 'SOP Class UID' exists in the native image ('true DICOM' image)
1289 we create the 'Source Image Sequence' SeqEntry (0x0008, 0x2112)
1290 --> 'Referenced SOP Class UID' (0x0008, 0x1150)
1291 whose value is the original 'SOP Class UID'
1292 --> 'Referenced SOP Instance UID' (0x0008, 0x1155)
1293 whose value is the original 'SOP Class UID'
1295 3) TODO : find a trick to allow user to pass to the writter the list of the Dicom images
1296 or the Series, (or the Study ?) he used to created his image
1297 (MIP, MPR, cartography image, ...)
1298 These info should be stored (?)
1299 0008 1110 SQ 1 Referenced Study Sequence
1300 0008 1115 SQ 1 Referenced Series Sequence
1301 0008 1140 SQ 1 Referenced Image Sequence
1303 4) When user *knows* he didn't modified the pixels, we keep some informations unchanged :
1304 'Media Storage SOP Class UID' (0x0002,0x0002)
1305 'SOP Class UID' (0x0008,0x0016)
1306 'Image Type' (0x0008,0x0008)
1307 'Conversion Type' (0x0008,0x0064)
1310 Bellow follows the full description (hope so !) of the consistency checks performed
1311 by gdcm::FileHelper::CheckMandatoryElements()
1314 -->'Media Storage SOP Class UID' (0x0002,0x0002)
1315 -->'SOP Class UID' (0x0008,0x0016) are defaulted to
1316 [Secondary Capture Image Storage]
1317 --> 'Image Type' (0x0008,0x0008)
1318 is forced to "DERIVED\PRIMARY"
1319 (The written image is no longer an 'ORIGINAL' one)
1320 Except if user knows he didn't modify the image (e.g. : he just anonymized the file)
1322 --> Conversion Type (0x0008,0x0064)
1323 is defaulted to 'SYN' (Synthetic Image)
1324 when *he* knows he created his own image ex nihilo
1326 --> 'Modality' (0x0008,0x0060)
1327 is defaulted to "OT" (other) if missing.
1328 (a fully user created image belongs to *no* modality)
1330 --> 'Media Storage SOP Instance UID' (0x0002,0x0003)
1331 --> 'Implementation Class UID' (0x0002,0x0012)
1332 are automatically generated; no user intervention possible
1334 --> 'Serie Instance UID'(0x0020,0x000e)
1335 --> 'Study Instance UID'(0x0020,0x000d) are kept as is if already exist
1336 created if it doesn't.
1337 The user is allowed to create his own Series/Studies,
1338 keeping the same 'Serie Instance UID' / 'Study Instance UID'
1341 The user shouldn't add any image to a 'Manufacturer Serie'
1342 but there is no way no to allowed him to do that
1344 --> If 'SOP Class UID' exists in the native image ('true DICOM' image)
1345 we create the 'Source Image Sequence' SeqEntry (0x0008, 0x2112)
1347 --> 'Referenced SOP Class UID' (0x0008, 0x1150)
1348 whose value is the original 'SOP Class UID'
1349 --> 'Referenced SOP Instance UID' (0x0008, 0x1155)
1350 whose value is the original 'SOP Class UID'
1352 --> Bits Stored, Bits Allocated, Hight Bit Position are checked for consistency
1353 --> Pixel Spacing (0x0028,0x0030) is defaulted to "1.0\1.0"
1354 --> Samples Per Pixel (0x0028,0x0002) is defaulted to 1 (grayscale)
1356 --> Imager Pixel Spacing (0x0018,0x1164) : defaulted to Pixel Spacing value
1358 --> Instance Creation Date, Instance Creation Time are forced to current Date and Time
1360 --> Study Date, Study Time are defaulted to current Date and Time
1361 (they remain unchanged if they exist)
1363 --> Patient Orientation : (0x0020,0x0020), if not present, is deduced from
1364 Image Orientation (Patient) : (0020|0037) or from
1365 Image Orientation (RET) : (0020 0035)
1367 --> Study ID, Series Number, Instance Number, Patient Orientation (Type 2)
1368 are created, with empty value if there are missing.
1370 --> Manufacturer, Institution Name, Patient's Name, (Type 2)
1371 are defaulted with a 'gdcm' value.
1373 --> Patient ID, Patient's Birth Date, Patient's Sex, (Type 2)
1374 --> Referring Physician's Name (Type 2)
1375 are created, with empty value if there are missing.
1377 -------------------------------------------------------------------------------------*/
1379 void FileHelper::CheckMandatoryElements()
1381 std::string sop = Util::CreateUniqueUID();
1383 // --------------------- For Meta Elements ---------------------
1384 // just to remember : 'official' 0002 group
1385 if ( WriteType != ACR && WriteType != ACR_LIBIDO )
1387 // Group 000002 (Meta Elements) already pushed out
1389 //0002 0000 UL 1 Meta Group Length
1390 //0002 0001 OB 1 File Meta Information Version
1391 //0002 0002 UI 1 Media Stored SOP Class UID
1392 //0002 0003 UI 1 Media Stored SOP Instance UID
1393 //0002 0010 UI 1 Transfer Syntax UID
1394 //0002 0012 UI 1 Implementation Class UID
1395 //0002 0013 SH 1 Implementation Version Name
1396 //0002 0016 AE 1 Source Application Entity Title
1397 //0002 0100 UI 1 Private Information Creator
1398 //0002 0102 OB 1 Private Information
1400 // Create them if not found
1401 // Always modify the value
1402 // Push the entries to the archive.
1403 CopyMandatoryEntry(0x0002,0x0000,"0","UL");
1405 DataEntry *e_0002_0001 = CopyDataEntry(0x0002,0x0001, "OB");
1406 e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1408 e_0002_0001->SetLength(2);
1409 Archive->Push(e_0002_0001);
1410 e_0002_0001->Delete();
1412 if ( ContentType == FILTERED_IMAGE || ContentType == UNMODIFIED_PIXELS_IMAGE)
1414 // we keep the original 'Media Storage SOP Class UID', we default it if missing
1415 CheckMandatoryEntry(0x0002,0x0002,"1.2.840.10008.5.1.4.1.1.7","UI");
1419 // It's *not* an image comming straight from a source. We force
1420 // 'Media Storage SOP Class UID' --> [Secondary Capture Image Storage]
1421 CopyMandatoryEntry(0x0002,0x0002,"1.2.840.10008.5.1.4.1.1.7","UI");
1424 // 'Media Storage SOP Instance UID'
1425 CopyMandatoryEntry(0x0002,0x0003,sop,"UI");
1427 // 'Implementation Class UID'
1428 // FIXME : in all examples we have, 0x0002,0x0012 is not so long :
1429 // seems to be Root UID + 4 digits (?)
1430 CopyMandatoryEntry(0x0002,0x0012,Util::CreateUniqueUID(),"UI");
1432 // 'Implementation Version Name'
1433 std::string version = "GDCM ";
1434 version += Util::GetVersion();
1435 CopyMandatoryEntry(0x0002,0x0013,version,"SH");
1438 // --------------------- For DataSet ---------------------
1440 if ( ContentType != USER_OWN_IMAGE) // when it's not a user made image
1443 gdcmDebugMacro( "USER_OWN_IMAGE (1)");
1444 // If 'SOP Class UID' exists ('true DICOM' image)
1445 // we create the 'Source Image Sequence' SeqEntry
1446 // to hold informations about the Source Image
1448 DataEntry *e_0008_0016 = FileInternal->GetDataEntry(0x0008, 0x0016);
1451 // Create 'Source Image Sequence' SeqEntry
1452 // SeqEntry *sis = SeqEntry::New (
1453 // Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1454 SeqEntry *sis = SeqEntry::New (0x0008, 0x2112);
1455 SQItem *sqi = SQItem::New(1);
1456 // (we assume 'SOP Instance UID' exists too)
1457 // create 'Referenced SOP Class UID'
1458 // DataEntry *e_0008_1150 = DataEntry::New(
1459 // Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1460 DataEntry *e_0008_1150 = DataEntry::New(0x0008, 0x1150, "UI");
1461 e_0008_1150->SetString( e_0008_0016->GetString());
1462 sqi->AddEntry(e_0008_1150);
1463 e_0008_1150->Delete();
1465 // create 'Referenced SOP Instance UID'
1466 DataEntry *e_0008_0018 = FileInternal->GetDataEntry(0x0008, 0x0018);
1467 // DataEntry *e_0008_1155 = DataEntry::New(
1468 // Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1469 DataEntry *e_0008_1155 = DataEntry::New(0x0008, 0x1155, "UI");
1470 e_0008_1155->SetString( e_0008_0018->GetString());
1471 sqi->AddEntry(e_0008_1155);
1472 e_0008_1155->Delete();
1474 sis->AddSQItem(sqi,1);
1477 // temporarily replaces any previous 'Source Image Sequence'
1481 // FIXME : is 'Image Type' *really* depending on the presence of 'SOP Class UID'?
1482 if ( ContentType == FILTERED_IMAGE)
1483 // the user *knows* he just modified the pixels
1484 // the image is no longer an 'Original' one
1485 CopyMandatoryEntry(0x0008,0x0008,"DERIVED\\PRIMARY","CS");
1489 if ( ContentType == FILTERED_IMAGE || ContentType == UNMODIFIED_PIXELS_IMAGE)
1491 // we keep the original 'Media Storage SOP Class UID', we default it if missing (it should be present !)
1492 CheckMandatoryEntry(0x0008,0x0016,"1.2.840.10008.5.1.4.1.1.7","UI");
1496 // It's *not* an image comming straight from a source. We force
1497 // 'Media Storage SOP Class UID' --> [Secondary Capture Image Storage]
1498 CopyMandatoryEntry(0x0008,0x0016,"1.2.840.10008.5.1.4.1.1.7", "UI");
1501 Archive->Push(0x0028,0x005); // [Image Dimensions (RET)
1502 // Push out 'LibIDO-special' entries, if any
1503 Archive->Push(0x0028,0x0015);
1504 Archive->Push(0x0028,0x0016);
1505 Archive->Push(0x0028,0x0017);
1506 Archive->Push(0x0028,0x0198); // very old versions
1507 Archive->Push(0x0028,0x0199);
1509 // Replace deprecated 0028 0012 US Planes
1510 // by new 0028 0008 IS Number of Frames
1512 ///\todo : find if there is a rule!
1513 DataEntry *e_0028_0012 = FileInternal->GetDataEntry(0x0028, 0x0012);
1516 CopyMandatoryEntry(0x0028, 0x0008,e_0028_0012->GetString(),"IS");
1517 Archive->Push(0x0028,0x0012);
1520 // Deal with the pb of (Bits Stored = 12)
1521 // - we're gonna write the image as Bits Stored = 16
1522 if ( FileInternal->GetEntryString(0x0028,0x0100) == "12")
1524 CopyMandatoryEntry(0x0028,0x0100,"16","US");
1527 // Check if user wasn't drunk ;-)
1529 std::ostringstream s;
1530 // check 'Bits Allocated' vs decent values
1531 int nbBitsAllocated = FileInternal->GetBitsAllocated();
1532 if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1534 CopyMandatoryEntry(0x0028,0x0100,"16","US");
1535 gdcmWarningMacro("(0028,0100) changed from "
1536 << nbBitsAllocated << " to 16 for consistency purpose");
1537 nbBitsAllocated = 16;
1539 // check 'Bits Stored' vs 'Bits Allocated'
1540 int nbBitsStored = FileInternal->GetBitsStored();
1541 if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1544 s << nbBitsAllocated;
1545 CopyMandatoryEntry(0x0028,0x0101,s.str(),"US");
1546 gdcmWarningMacro("(0028,0101) changed from "
1547 << nbBitsStored << " to " << nbBitsAllocated
1548 << " for consistency purpose" );
1549 nbBitsStored = nbBitsAllocated;
1551 // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1552 int highBitPosition = FileInternal->GetHighBitPosition();
1553 if ( highBitPosition == 0 ||
1554 highBitPosition > nbBitsAllocated-1 ||
1555 highBitPosition < nbBitsStored-1 )
1558 s << nbBitsStored - 1;
1559 CopyMandatoryEntry(0x0028,0x0102,s.str(),"US");
1560 gdcmWarningMacro("(0028,0102) changed from "
1561 << highBitPosition << " to " << nbBitsAllocated-1
1562 << " for consistency purpose");
1565 std::string pixelSpacing = FileInternal->GetEntryString(0x0028,0x0030);
1566 if ( pixelSpacing == GDCM_UNFOUND )
1568 pixelSpacing = "1.0\\1.0";
1569 // if missing, Pixel Spacing forced to "1.0\1.0"
1570 CopyMandatoryEntry(0x0028,0x0030,pixelSpacing,"DS");
1573 // 'Imager Pixel Spacing' : defaulted to 'Pixel Spacing'
1574 // --> This one is the *legal* one !
1575 if ( ContentType != USER_OWN_IMAGE)
1576 // we write it only when we are *sure* the image comes from
1577 // an imager (see also 0008,0x0064)
1578 CheckMandatoryEntry(0x0018,0x1164,pixelSpacing,"DS");
1583 ///Exact meaning of RETired fields
1585 // See page 73 of ACR-NEMA_300-1988.pdf !
1587 // 0020,0020 : Patient Orientation :
1588 Patient direction of the first row and
1589 column of the images. The first entry id the direction of the raws, given by the
1590 direction of the last pixel in the first row from the first pixel in tha row.
1591 the second entry is the direction of the columns, given by the direction of the
1592 last pixel in the first column from the first pixel in that column.
1593 L : Left, F : Feet, A : Anterior, P : Posterior.
1594 Up to 3 letters can be used in combination to indicate oblique planes.
1596 //0020,0030 Image Position (RET)
1597 x,y,z coordinates im mm of the first pixel in the image
1599 // 0020,0035 Image Orientation (RET)
1600 Direction cosines of the R axis of the image system with respect to the
1601 equipment coordinate axes x,y,z, followed by direction cosines of the C axis of
1602 the image system with respect to the same axes
1604 //0020,0050 Location
1605 An image location reference, standard for the modality (such as CT bed
1606 position), used to indicate position. Calculation of position for other purposes
1607 is only from (0020,0030) and (0020,0035)
1611 // if imagePositionPatient not found, default it with imagePositionRet, if any
1612 // if imageOrientationPatient not found, default it with imageOrientationRet, if any
1614 std::string imagePositionRet = FileInternal->GetEntryString(0x0020,0x0030);
1615 std::string imageOrientationRet = FileInternal->GetEntryString(0x0020,0x0035);
1616 std::string imagePositionPatient = FileInternal->GetEntryString(0x0020,0x0032);
1617 std::string imageOrientationPatient = FileInternal->GetEntryString(0x0020,0x0037);
1619 if( imagePositionPatient == GDCM_UNFOUND && imageOrientationPatient == GDCM_UNFOUND
1620 && imagePositionRet != GDCM_UNFOUND && imageOrientationRet != GDCM_UNFOUND)
1622 CopyMandatoryEntry(0x0020, 0x0032,imagePositionRet,"DS");
1623 Archive->Push(0x0020,0x0030);
1624 CopyMandatoryEntry(0x0020, 0x0037,imageOrientationRet,"DS");
1625 Archive->Push(0x0020,0x0035);
1629 // Samples Per Pixel (type 1) : default to grayscale
1630 CheckMandatoryEntry(0x0028,0x0002,"1","US");
1632 // --- Check UID-related Entries ---
1634 // At the end, not to overwrite the original ones,
1635 // needed by 'Referenced SOP Instance UID', 'Referenced SOP Class UID'
1636 // 'SOP Instance UID'
1637 CopyMandatoryEntry(0x0008,0x0018,sop,"UI");
1639 if ( ContentType == USER_OWN_IMAGE)
1641 gdcmDebugMacro( "USER_OWN_IMAGE (2)");
1643 // Other possible values are :
1644 // See PS 3.3, Page 408
1646 // DV = Digitized Video
1647 // DI = Digital Interface
1648 // DF = Digitized Film
1649 // WSD = Workstation
1650 // SD = Scanned Document
1651 // SI = Scanned Image
1653 // SYN = Synthetic Image
1655 CheckMandatoryEntry(0x0008,0x0064,"SYN","CS"); // Why not?
1658 if ( ContentType == CREATED_IMAGE)
1660 /// \todo : find a trick to pass the Media Storage SOP Instance UID of the images used to create the current image
1665 // ---- The user will never have to take any action on the following ----
1667 // new value for 'SOP Instance UID'
1668 //SetMandatoryEntry(0x0008,0x0018,Util::CreateUniqueUID());
1670 // Instance Creation Date
1671 const std::string &date = Util::GetCurrentDate();
1672 CopyMandatoryEntry(0x0008,0x0012,date,"DA");
1674 // Instance Creation Time
1675 const std::string &time = Util::GetCurrentTime();
1676 CopyMandatoryEntry(0x0008,0x0013,time,"TM");
1679 CheckMandatoryEntry(0x0008,0x0020,date,"DA");
1681 CheckMandatoryEntry(0x0008,0x0030,time,"TM");
1684 //CopyMandatoryEntry(0x0008,0x0050,"");
1685 CheckMandatoryEntry(0x0008,0x0050,"","SH");
1688 // ----- Add Mandatory Entries if missing ---
1689 // Entries whose type is 1 are mandatory, with a mandatory value
1690 // Entries whose type is 1c are mandatory-inside-a-Sequence,
1691 // with a mandatory value
1692 // Entries whose type is 2 are mandatory, with an optional value
1693 // Entries whose type is 2c are mandatory-inside-a-Sequence,
1694 // with an optional value
1695 // Entries whose type is 3 are optional
1697 // 'Study Instance UID'
1698 // Keep the value if exists
1699 // The user is allowed to create his own Study,
1700 // keeping the same 'Study Instance UID' for various images
1701 // The user may add images to a 'Manufacturer Study',
1702 // adding new Series to an already existing Study
1703 CheckMandatoryEntry(0x0020,0x000d,Util::CreateUniqueUID(),"UI");
1705 // 'Serie Instance UID'
1706 // Keep the value if exists
1707 // The user is allowed to create his own Series,
1708 // keeping the same 'Serie Instance UID' for various images
1709 // The user shouldn't add any image to a 'Manufacturer Serie'
1710 // but there is no way no to prevent him for doing that
1711 CheckMandatoryEntry(0x0020,0x000e,Util::CreateUniqueUID(),"UI");
1714 CheckMandatoryEntry(0x0020,0x0010,"","SH");
1717 CheckMandatoryEntry(0x0020,0x0011,"","IS");
1720 CheckMandatoryEntry(0x0020,0x0013,"","IS");
1722 // Patient Orientation
1723 // Can be computed from (0020|0037) : Image Orientation (Patient)
1724 gdcm::Orientation *o = gdcm::Orientation::New();
1725 std::string ori = o->GetOrientation ( FileInternal );
1727 if (ori != "\\" && ori != GDCM_UNFOUND)
1728 CheckMandatoryEntry(0x0020,0x0020,ori,"CS");
1730 CheckMandatoryEntry(0x0020,0x0020,"","CS");
1732 // Default Patient Position to HFS
1733 CheckMandatoryEntry(0x0018,0x5100,"HFS","CS");
1735 // Modality : if missing we set it to 'OTher'
1736 CheckMandatoryEntry(0x0008,0x0060,"OT","CS");
1738 // Manufacturer : if missing we set it to 'GDCM Factory'
1739 CheckMandatoryEntry(0x0008,0x0070,"GDCM Factory","LO");
1741 // Institution Name : if missing we set it to 'GDCM Hospital'
1742 CheckMandatoryEntry(0x0008,0x0080,"GDCM Hospital","LO");
1744 // Patient's Name : if missing, we set it to 'GDCM^Patient'
1745 CheckMandatoryEntry(0x0010,0x0010,"GDCM^Patient","PN");
1747 // Patient ID : some clinical softwares *demand* it although it's a 'type 2' entry.
1748 CheckMandatoryEntry(0x0010,0x0020,"gdcm ID","LO");
1750 // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1751 CheckMandatoryEntry(0x0010,0x0030,"","DA");
1753 // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1754 CheckMandatoryEntry(0x0010,0x0040,"","CS");
1756 // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1757 CheckMandatoryEntry(0x0008,0x0090,"","PN");
1760 // Deal with element 0x0000 (group length) of each group.
1761 // First stage : get all the different Groups
1764 DocEntry *d = FileInternal->GetFirstEntry();
1767 grHT[d->GetGroup()] = 0;
1768 d=FileInternal->GetNextEntry();
1770 // Second stage : add the missing ones (if any)
1771 for (GroupHT::iterator it = grHT.begin(); it != grHT.end(); ++it)
1773 CheckMandatoryEntry(it->first, 0x0000, "0");
1775 // Third stage : update all 'zero level' groups length
1780 void FileHelper::CheckMandatoryEntry(uint16_t group,uint16_t elem,std::string value,const VRKey &vr )
1782 DataEntry *entry = FileInternal->GetDataEntry(group,elem);
1785 //entry = DataEntry::New(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1786 entry = DataEntry::New(group,elem,vr);
1787 entry->SetString(value);
1788 Archive->Push(entry);
1793 /// \todo : what is it used for ? (FileHelper::SetMandatoryEntry)
1794 void FileHelper::SetMandatoryEntry(uint16_t group,uint16_t elem,std::string value,const VRKey &vr)
1796 //DataEntry *entry = DataEntry::New(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1797 DataEntry *entry = DataEntry::New(group,elem,vr);
1798 entry->SetString(value);
1799 Archive->Push(entry);
1803 void FileHelper::CopyMandatoryEntry(uint16_t group,uint16_t elem,std::string value,const VRKey &vr)
1805 DataEntry *entry = CopyDataEntry(group,elem,vr);
1806 entry->SetString(value);
1807 Archive->Push(entry);
1812 * \brief Restore in the File the initial group 0002
1814 void FileHelper::RestoreWriteMandatory()
1816 // group 0002 may be pushed out for ACR-NEMA writting purposes
1817 Archive->Restore(0x0002,0x0000);
1818 Archive->Restore(0x0002,0x0001);
1819 Archive->Restore(0x0002,0x0002);
1820 Archive->Restore(0x0002,0x0003);
1821 Archive->Restore(0x0002,0x0010);
1822 Archive->Restore(0x0002,0x0012);
1823 Archive->Restore(0x0002,0x0013);
1824 Archive->Restore(0x0002,0x0016);
1825 Archive->Restore(0x0002,0x0100);
1826 Archive->Restore(0x0002,0x0102);
1828 // FIXME : Check if none is missing !
1830 Archive->Restore(0x0008,0x0012);
1831 Archive->Restore(0x0008,0x0013);
1832 Archive->Restore(0x0008,0x0016);
1833 Archive->Restore(0x0008,0x0018);
1834 Archive->Restore(0x0008,0x0060);
1835 Archive->Restore(0x0008,0x0070);
1836 Archive->Restore(0x0008,0x0080);
1837 Archive->Restore(0x0008,0x0090);
1838 Archive->Restore(0x0008,0x2112);
1840 Archive->Restore(0x0010,0x0010);
1841 Archive->Restore(0x0010,0x0030);
1842 Archive->Restore(0x0010,0x0040);
1844 Archive->Restore(0x0020,0x000d);
1845 Archive->Restore(0x0020,0x000e);
1850 * \brief CallStartMethod
1852 void FileHelper::CallStartMethod()
1856 CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1860 * \brief CallProgressMethod
1862 void FileHelper::CallProgressMethod()
1864 CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1868 * \brief CallEndMethod
1870 void FileHelper::CallEndMethod()
1873 CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1876 //-----------------------------------------------------------------------------
1879 * \brief Factorization for various forms of constructors.
1881 void FileHelper::Initialize()
1884 ContentType = USER_OWN_IMAGE;
1886 WriteMode = WMODE_RAW;
1887 WriteType = ExplicitVR;
1889 PixelReadConverter = new PixelReadConvert;
1890 PixelWriteConverter = new PixelWriteConvert;
1891 Archive = new DocEntryArchive( FileInternal );
1895 * \brief Reads/[decompresses] the pixels,
1896 * *without* making RGB from Palette Colors
1897 * @return the pixels area, whatever its type
1898 * (uint8_t is just for prototyping : feel free to Cast it)
1900 uint8_t *FileHelper::GetRaw()
1902 PixelReadConverter->SetUserFunction( UserFunction );
1904 uint8_t *raw = PixelReadConverter->GetRaw();
1907 // The Raw image migth not be loaded yet:
1908 std::ifstream *fp = FileInternal->OpenFile();
1909 PixelReadConverter->ReadAndDecompressPixelData( fp );
1911 FileInternal->CloseFile();
1913 raw = PixelReadConverter->GetRaw();
1916 gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1923 //-----------------------------------------------------------------------------
1925 * \brief Prints the common part of DataEntry, SeqEntry
1926 * @param os ostream we want to print in
1927 * @param indent (unused)
1929 void FileHelper::Print(std::ostream &os, std::string const &)
1931 FileInternal->SetPrintLevel(PrintLevel);
1932 FileInternal->Print(os);
1934 if ( FileInternal->IsReadable() )
1936 PixelReadConverter->SetPrintLevel(PrintLevel);
1937 PixelReadConverter->Print(os);
1941 //-----------------------------------------------------------------------------
1942 } // end namespace gdcm
1945 /* Probabely something to be added to use Rescale Slope/Intercept
1946 Have a look ,at ITK code !
1948 // Internal function to rescale pixel according to Rescale Slope/Intercept
1949 template<class TBuffer, class TSource>
1950 void RescaleFunction(TBuffer* buffer, TSource *source,
1951 double slope, double intercept, size_t size)
1953 size /= sizeof(TSource);
1955 if (slope != 1.0 && intercept != 0.0)
1957 // Duff's device. Instead of this code:
1959 // for(unsigned int i=0; i<size; i++)
1961 // buffer[i] = (TBuffer)(source[i]*slope + intercept);
1964 // use Duff's device which exploits "fall through"
1965 register size_t n = (size + 7) / 8;
1968 case 0: do { *buffer++ = (TBuffer)((*source++)*slope + intercept);
1969 case 7: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1970 case 6: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1971 case 5: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1972 case 4: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1973 case 3: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1974 case 2: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1975 case 1: *buffer++ = (TBuffer)((*source++)*slope + intercept);
1979 else if (slope == 1.0 && intercept != 0.0)
1981 // Duff's device. Instead of this code:
1983 // for(unsigned int i=0; i<size; i++)
1985 // buffer[i] = (TBuffer)(source[i] + intercept);
1988 // use Duff's device which exploits "fall through"
1989 register size_t n = (size + 7) / 8;
1992 case 0: do { *buffer++ = (TBuffer)(*source++ + intercept);
1993 case 7: *buffer++ = (TBuffer)(*source++ + intercept);
1994 case 6: *buffer++ = (TBuffer)(*source++ + intercept);
1995 case 5: *buffer++ = (TBuffer)(*source++ + intercept);
1996 case 4: *buffer++ = (TBuffer)(*source++ + intercept);
1997 case 3: *buffer++ = (TBuffer)(*source++ + intercept);
1998 case 2: *buffer++ = (TBuffer)(*source++ + intercept);
1999 case 1: *buffer++ = (TBuffer)(*source++ + intercept);
2003 else if (slope != 1.0 && intercept == 0.0)
2005 // Duff's device. Instead of this code:
2007 // for(unsigned int i=0; i<size; i++)
2009 // buffer[i] = (TBuffer)(source[i]*slope);
2012 // use Duff's device which exploits "fall through"
2013 register size_t n = (size + 7) / 8;
2016 case 0: do { *buffer++ = (TBuffer)((*source++)*slope);
2017 case 7: *buffer++ = (TBuffer)((*source++)*slope);
2018 case 6: *buffer++ = (TBuffer)((*source++)*slope);
2019 case 5: *buffer++ = (TBuffer)((*source++)*slope);
2020 case 4: *buffer++ = (TBuffer)((*source++)*slope);
2021 case 3: *buffer++ = (TBuffer)((*source++)*slope);
2022 case 2: *buffer++ = (TBuffer)((*source++)*slope);
2023 case 1: *buffer++ = (TBuffer)((*source++)*slope);
2029 // Duff's device. Instead of this code:
2031 // for(unsigned int i=0; i<size; i++)
2033 // buffer[i] = (TBuffer)(source[i]);
2036 // use Duff's device which exploits "fall through"
2037 register size_t n = (size + 7) / 8;
2040 case 0: do { *buffer++ = (TBuffer)(*source++);
2041 case 7: *buffer++ = (TBuffer)(*source++);
2042 case 6: *buffer++ = (TBuffer)(*source++);
2043 case 5: *buffer++ = (TBuffer)(*source++);
2044 case 4: *buffer++ = (TBuffer)(*source++);
2045 case 3: *buffer++ = (TBuffer)(*source++);
2046 case 2: *buffer++ = (TBuffer)(*source++);
2047 case 1: *buffer++ = (TBuffer)(*source++);
2056 template<class TSource>
2057 void RescaleFunction(ImageIOBase::IOComponentType bufferType,
2058 void* buffer, TSource *source,
2059 double slope, double intercept, size_t size)
2063 case ImageIOBase::UCHAR:
2064 RescaleFunction( (unsigned char *)buffer, source, slope, intercept, size);
2066 case ImageIOBase::CHAR:
2067 RescaleFunction( (char *)buffer, source, slope, intercept, size);
2069 case ImageIOBase::USHORT:
2070 RescaleFunction( (unsigned short *)buffer, source, slope, intercept,size);
2072 case ImageIOBase::SHORT:
2073 RescaleFunction( (short *)buffer, source, slope, intercept, size);
2075 case ImageIOBase::UINT:
2076 RescaleFunction( (unsigned int *)buffer, source, slope, intercept, size);
2078 case ImageIOBase::INT:
2079 RescaleFunction( (int *)buffer, source, slope, intercept, size);
2081 case ImageIOBase::FLOAT:
2082 RescaleFunction( (float *)buffer, source, slope, intercept, size);
2084 case ImageIOBase::DOUBLE:
2085 RescaleFunction( (double *)buffer, source, slope, intercept, size);
2088 ::itk::OStringStream message;
2089 message << "itk::ERROR: GDCMImageIO: Unknown component type : " << bufferType;
2090 ::itk::ExceptionObject e(__FILE__, __LINE__, message.str().c_str(),ITK_LOCATION);