]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
1a4cf5c2a224b4e5020ce23d0412046c90bc0b22
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/21 17:45:41 $
7   Version:   $Revision: 1.18 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmFileHelper.h"
20 #include "gdcmGlobal.h"
21 #include "gdcmTS.h"
22 #include "gdcmDocument.h"
23 #include "gdcmDebug.h"
24 #include "gdcmUtil.h"
25 #include "gdcmBinEntry.h"
26 #include "gdcmValEntry.h"
27 #include "gdcmSeqEntry.h"
28 #include "gdcmSQItem.h"
29 #include "gdcmContentEntry.h"
30 #include "gdcmFile.h"
31 #include "gdcmPixelReadConvert.h"
32 #include "gdcmPixelWriteConvert.h"
33 #include "gdcmDocEntryArchive.h"
34 #include "gdcmDictSet.h"
35
36 #include <fstream>
37
38
39 namespace gdcm 
40 {
41 //-------------------------------------------------------------------------
42 // Constructor / Destructor
43 /**
44  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
45  *        file (gdcm::File only deals with the ... header)
46  *        Opens (in read only and when possible) an existing file and checks
47  *        for DICOM compliance. Returns NULL on failure.
48  *        It will be up to the user to load the pixels into memory
49  * \note  the in-memory representation of all available tags found in
50  *        the DICOM header is post-poned to first header information access.
51  *        This avoid a double parsing of public part of the header when
52  *        one sets an a posteriori shadow dictionary (efficiency can be
53  *        seen as a side effect).   
54  */
55 FileHelper::FileHelper( )
56 {
57    FileInternal = new File( );
58    SelfHeader = true;
59    Initialize();
60 }
61
62 /**
63  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
64  *        file (File only deals with the ... header)
65  *        Opens (in read only and when possible) an existing file and checks
66  *        for DICOM compliance. Returns NULL on failure.
67  *        It will be up to the user to load the pixels into memory
68  * \note  the in-memory representation of all available tags found in
69  *        the DICOM header is post-poned to first header information access.
70  *        This avoid a double parsing of public part of the header when
71  *        user sets an a posteriori shadow dictionary (efficiency can be
72  *        seen as a side effect).   
73  * @param header already built Header
74  */
75 FileHelper::FileHelper(File *header)
76 {
77    FileInternal = header;
78    SelfHeader = false;
79    Initialize();
80 }
81
82 /**
83  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
84  *        file (gdcm::File only deals with the ... header)
85  *        Opens (in read only and when possible) an existing file and checks
86  *        for DICOM compliance. Returns NULL on failure.
87  *        It will be up to the user to load the pixels into memory
88  * \note  the in-memory representation of all available tags found in
89  *        the DICOM header is post-poned to first header information access.
90  *        This avoid a double parsing of public part of the header when
91  *        one sets an a posteriori shadow dictionary (efficiency can be
92  *        seen as a side effect).   
93  * @param filename file to be opened for parsing
94  */
95 FileHelper::FileHelper(std::string const &filename )
96 {
97    FileInternal = new File( filename );
98    SelfHeader = true;
99    Initialize();
100 }
101
102 /**
103  * \brief canonical destructor
104  * \note  If the header (gdcm::File) was created by the FileHelper constructor,
105  *        it is destroyed by the FileHelper
106  */
107 FileHelper::~FileHelper()
108
109    if( PixelReadConverter )
110    {
111       delete PixelReadConverter;
112    }
113    if( PixelWriteConverter )
114    {
115       delete PixelWriteConverter;
116    }
117    if( Archive )
118    {
119       delete Archive;
120    }
121
122    if( SelfHeader )
123    {
124       delete FileInternal;
125    }
126    FileInternal = 0;
127 }
128
129 //-----------------------------------------------------------------------------
130 // Public
131 /**
132  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
133  *          through it's (group, element) and modifies it's content with
134  *          the given value.
135  * @param   content new value (string) to substitute with
136  * @param   group  group number of the Dicom Element to modify
137  * @param   elem element number of the Dicom Element to modify
138  * \return  false if DocEntry not found
139  */
140 bool FileHelper::SetValEntry(std::string const &content,
141                              uint16_t group, uint16_t elem)
142
143    return FileInternal->SetValEntry(content, group, elem);
144 }
145
146
147 /**
148  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
149  *          through it's (group, element) and modifies it's content with
150  *          the given value.
151  * @param   content new value (void*  -> uint8_t*) to substitute with
152  * @param   lgth new value length
153  * @param   group  group number of the Dicom Element to modify
154  * @param   elem element number of the Dicom Element to modify
155  * \return  false if DocEntry not found
156  */
157 bool FileHelper::SetBinEntry(uint8_t *content, int lgth,
158                              uint16_t group, uint16_t elem)
159 {
160    return FileInternal->SetBinEntry(content, lgth, group, elem);
161 }
162
163 /**
164  * \brief   Modifies the value of a given DocEntry (Dicom entry)
165  *          when it exists. Creates it with the given value when unexistant.
166  * @param   content (string)value to be set
167  * @param   group   Group number of the Entry 
168  * @param   elem  Element number of the Entry
169  * \return  pointer to the modified/created Dicom entry (NULL when creation
170  *          failed).
171  */ 
172 ValEntry *FileHelper::InsertValEntry(std::string const &content,
173                                      uint16_t group, uint16_t elem)
174 {
175    return FileInternal->InsertValEntry(content,group,elem);
176 }
177
178 /**
179  * \brief   Modifies the value of a given DocEntry (Dicom entry)
180  *          when it exists. Creates it with the given value when unexistant.
181  *          A copy of the binArea is made to be kept in the Document.
182  * @param   binArea (binary)value to be set
183  * @param   lgth new value length
184  * @param   group   Group number of the Entry 
185  * @param   elem  Element number of the Entry
186  * \return  pointer to the modified/created Dicom entry (NULL when creation
187  *          failed).
188  */
189 BinEntry *FileHelper::InsertBinEntry(uint8_t *binArea, int lgth,
190                                      uint16_t group, uint16_t elem)
191 {
192    return FileInternal->InsertBinEntry(binArea, lgth, group, elem);
193 }
194
195 /**
196  * \brief   Modifies the value of a given DocEntry (Dicom entry)
197  *          when it exists. Creates it, empty (?!) when unexistant.
198  * @param   group   Group number of the Entry 
199  * @param   elem  Element number of the Entry
200  * \return  pointer to the modified/created Dicom entry (NULL when creation
201  *          failed).
202  */
203 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
204 {
205    return FileInternal->InsertSeqEntry(group, elem);
206 }
207
208 /**
209  * \brief   Get the size of the image data
210  *          If the image can be RGB (with a lut or by default), the size 
211  *          corresponds to the RGB image
212  *         (use GetImageDataRawSize if you want to be sure to get *only*
213  *          the size of the pixels)
214  * @return  The image size
215  */
216 size_t FileHelper::GetImageDataSize()
217 {
218    if ( PixelWriteConverter->GetUserData() )
219    {
220       return PixelWriteConverter->GetUserDataSize();
221    }
222
223    return PixelReadConverter->GetRGBSize();
224 }
225
226 /**
227  * \brief   Get the size of the image data
228  *          If the image could be converted to RGB using a LUT, 
229  *          this transformation is not taken into account by GetImageDataRawSize
230  *          (use GetImageDataSize if you wish)
231  * @return  The raw image size
232  */
233 size_t FileHelper::GetImageDataRawSize()
234 {
235    if ( PixelWriteConverter->GetUserData() )
236    {
237       return PixelWriteConverter->GetUserDataSize();
238    }
239
240    return PixelReadConverter->GetRawSize();
241 }
242
243 /**
244  * \brief   - Allocates necessary memory,
245  *          - Reads the pixels from disk (uncompress if necessary),
246  *          - Transforms YBR pixels, if any, into RGB pixels,
247  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
248  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
249  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
250  * @return  Pointer to newly allocated pixel data.
251  *          NULL if alloc fails 
252  */
253 uint8_t *FileHelper::GetImageData()
254 {
255    if ( PixelWriteConverter->GetUserData() )
256    {
257       return PixelWriteConverter->GetUserData();
258    }
259
260    if ( ! GetRaw() )
261    {
262       // If the decompression failed nothing can be done.
263       return 0;
264    }
265
266    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
267    {
268       return PixelReadConverter->GetRGB();
269    }
270    else
271    {
272       // When no LUT or LUT conversion fails, return the Raw
273       return PixelReadConverter->GetRaw();
274    }
275 }
276
277 /**
278  * \brief   Allocates necessary memory, 
279  *          Transforms YBR pixels (if any) into RGB pixels
280  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
281  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
282  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
283  * @return  Pointer to newly allocated pixel data.
284  *          NULL if alloc fails 
285  */
286 uint8_t *FileHelper::GetImageDataRaw ()
287 {
288    return GetRaw();
289 }
290
291 /**
292  * \brief
293  *          Read the pixels from disk (uncompress if necessary),
294  *          Transforms YBR pixels, if any, into RGB pixels
295  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
296  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
297  *          Copies at most MaxSize bytes of pixel data to caller allocated
298  *          memory space.
299  * \warning This function allows people that want to build a volume
300  *          from an image stack *not to* have, first to get the image pixels, 
301  *          and then move them to the volume area.
302  *          It's absolutely useless for any VTK user since vtk chooses 
303  *          to invert the lines of an image, that is the last line comes first
304  *          (for some axis related reasons?). Hence he will have 
305  *          to load the image line by line, starting from the end.
306  *          VTK users have to call GetImageData
307  *     
308  * @param   destination Address (in caller's memory space) at which the
309  *          pixel data should be copied
310  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
311  *          is not sufficient to hold the pixel data the copy is not
312  *          executed (i.e. no partial copy).
313  * @return  On success, the number of bytes actually copied. Zero on
314  *          failure e.g. MaxSize is lower than necessary.
315  */
316 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
317 {
318    if ( ! GetRaw() )
319    {
320       // If the decompression failed nothing can be done.
321       return 0;
322    }
323
324    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
325    {
326       if ( PixelReadConverter->GetRGBSize() > maxSize )
327       {
328          gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
329          return 0;
330       }
331       memcpy( destination,
332               (void*)PixelReadConverter->GetRGB(),
333               PixelReadConverter->GetRGBSize() );
334       return PixelReadConverter->GetRGBSize();
335    }
336
337    // Either no LUT conversion necessary or LUT conversion failed
338    if ( PixelReadConverter->GetRawSize() > maxSize )
339    {
340       gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
341       return 0;
342    }
343    memcpy( destination,
344            (void*)PixelReadConverter->GetRaw(),
345            PixelReadConverter->GetRawSize() );
346    return PixelReadConverter->GetRawSize();
347 }
348
349 /**
350  * \brief   Points the internal pointer to the callers inData
351  *          image representation, BUT WITHOUT COPYING THE DATA.
352  *          'image' Pixels are presented as C-like 2D arrays : line per line.
353  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
354  * \warning Since the pixels are not copied, it is the caller's responsability
355  *          not to deallocate its data before gdcm uses them (e.g. with
356  *          the Write() method )
357  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
358  *               user is allowed to pass any kind of pixelsn since the size is
359  *               given in bytes) 
360  * @param expectedSize total image size, *in Bytes*
361  */
362 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
363 {
364    SetUserData(inData, expectedSize);
365 }
366
367 /**
368  * \brief   Set the image data defined by the user
369  * \warning When writting the file, this data are get as default data to write
370  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
371  *               user is allowed to pass any kind of pixels since the size is
372  *               given in bytes) 
373  * @param expectedSize total image size, *in Bytes* 
374  */
375 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
376 {
377    PixelWriteConverter->SetUserData(inData, expectedSize);
378 }
379
380 /**
381  * \brief   Get the image data defined by the user
382  * \warning When writting the file, this data are get as default data to write
383  */
384 uint8_t *FileHelper::GetUserData()
385 {
386    return PixelWriteConverter->GetUserData();
387 }
388
389 /**
390  * \brief   Get the image data size defined by the user
391  * \warning When writting the file, this data are get as default data to write
392  */
393 size_t FileHelper::GetUserDataSize()
394 {
395    return PixelWriteConverter->GetUserDataSize();
396 }
397
398 /**
399  * \brief   Get the image data from the file.
400  *          If a LUT is found, the data are expanded to be RGB
401  */
402 uint8_t *FileHelper::GetRGBData()
403 {
404    return PixelReadConverter->GetRGB();
405 }
406
407 /**
408  * \brief   Get the image data size from the file.
409  *          If a LUT is found, the data are expanded to be RGB
410  */
411 size_t FileHelper::GetRGBDataSize()
412 {
413    return PixelReadConverter->GetRGBSize();
414 }
415
416 /**
417  * \brief   Get the image data from the file.
418  *          Even when a LUT is found, the data are not expanded to RGB!
419  */
420 uint8_t *FileHelper::GetRawData()
421 {
422    return PixelReadConverter->GetRaw();
423 }
424
425 /**
426  * \brief   Get the image data size from the file.
427  *          Even when a LUT is found, the data are not expanded to RGB!
428  */
429 size_t FileHelper::GetRawDataSize()
430 {
431    return PixelReadConverter->GetRawSize();
432 }
433
434 /**
435  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
436  */
437 uint8_t* FileHelper::GetLutRGBA()
438 {
439    return PixelReadConverter->GetLutRGBA();
440 }
441
442 /**
443  * \brief Writes on disk A SINGLE Dicom file
444  *        NO test is performed on  processor "Endiannity".
445  *        It's up to the user to call his Reader properly
446  * @param fileName name of the file to be created
447  *                 (any already existing file is over written)
448  * @return false if write fails
449  */
450 bool FileHelper::WriteRawData(std::string const &fileName)
451 {
452   std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
453    if (!fp1)
454    {
455       gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
456       return false;
457    }
458
459    if( PixelWriteConverter->GetUserData() )
460    {
461       fp1.write( (char*)PixelWriteConverter->GetUserData(), 
462                  PixelWriteConverter->GetUserDataSize() );
463    }
464    else if ( PixelReadConverter->GetRGB() )
465    {
466       fp1.write( (char*)PixelReadConverter->GetRGB(), 
467                  PixelReadConverter->GetRGBSize());
468    }
469    else if ( PixelReadConverter->GetRaw() )
470    {
471       fp1.write( (char*)PixelReadConverter->GetRaw(), 
472                  PixelReadConverter->GetRawSize());
473    }
474    else
475    {
476       gdcmErrorMacro( "Nothing written." );
477    }
478
479    fp1.close();
480
481    return true;
482 }
483
484 /**
485  * \brief Writes on disk A SINGLE Dicom file, 
486  *        using the Implicit Value Representation convention
487  *        NO test is performed on  processor "Endiannity".
488  * @param fileName name of the file to be created
489  *                 (any already existing file is overwritten)
490  * @return false if write fails
491  */
492
493 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
494 {
495    SetWriteTypeToDcmImplVR();
496    return Write(fileName);
497 }
498
499 /**
500 * \brief Writes on disk A SINGLE Dicom file, 
501  *        using the Explicit Value Representation convention
502  *        NO test is performed on  processor "Endiannity". 
503  * @param fileName name of the file to be created
504  *                 (any already existing file is overwritten)
505  * @return false if write fails
506  */
507
508 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
509 {
510    SetWriteTypeToDcmExplVR();
511    return Write(fileName);
512 }
513
514 /**
515  * \brief Writes on disk A SINGLE Dicom file, 
516  *        using the ACR-NEMA convention
517  *        NO test is performed on  processor "Endiannity".
518  *        (a l'attention des logiciels cliniques 
519  *        qui ne prennent en entrée QUE des images ACR ...
520  * \warning if a DICOM_V3 header is supplied,
521  *         groups < 0x0008 and shadow groups are ignored
522  * \warning NO TEST is performed on processor "Endiannity".
523  * @param fileName name of the file to be created
524  *                 (any already existing file is overwritten)
525  * @return false if write fails
526  */
527
528 bool FileHelper::WriteAcr (std::string const &fileName)
529 {
530    SetWriteTypeToAcr();
531    return Write(fileName);
532 }
533
534 /**
535  * \brief Writes on disk A SINGLE Dicom file, 
536  * @param fileName name of the file to be created
537  *                 (any already existing file is overwritten)
538  * @return false if write fails
539  */
540 bool FileHelper::Write(std::string const &fileName)
541 {
542    switch(WriteType)
543    {
544       case ImplicitVR:
545          SetWriteFileTypeToImplicitVR();
546          CheckMandatoryElements();
547          break;
548       case ExplicitVR:
549          SetWriteFileTypeToExplicitVR();
550          CheckMandatoryElements();
551          break;
552       case ACR:
553       case ACR_LIBIDO:
554          SetWriteFileTypeToACR();
555          break;
556       default:
557          SetWriteFileTypeToExplicitVR();
558          CheckMandatoryElements();
559    }
560
561    // --------------------------------------------------------------
562    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
563    //
564    // if recognition code tells us we dealt with a LibIDO image
565    // we reproduce on disk the switch between lineNumber and columnNumber
566    // just before writting ...
567    /// \todo the best trick would be *change* the recognition code
568    ///       but pb expected if user deals with, e.g. COMPLEX images
569    if( WriteType == ACR_LIBIDO )
570    {
571       SetWriteToLibido();
572    }
573    else
574    {
575       SetWriteToNoLibido();
576    }
577    // ----------------- End of Special Patch ----------------
578   
579    switch(WriteMode)
580    {
581       case WMODE_RAW :
582          SetWriteToRaw(); // modifies and pushes to the archive, when necessary
583          break;
584       case WMODE_RGB :
585          SetWriteToRGB(); // modifies and pushes to the archive, when necessary
586          break;
587    }
588
589    bool check = CheckWriteIntegrity(); // verifies length
590    if(check)
591    {
592       check = FileInternal->Write(fileName,WriteType);
593    }
594
595    RestoreWrite();
596    RestoreWriteFileType();
597
598    // --------------------------------------------------------------
599    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
600    // 
601    // ...and we restore the header to be Dicom Compliant again 
602    // just after writting
603    RestoreWriteOfLibido();
604    // ----------------- End of Special Patch ----------------
605
606    return check;
607 }
608
609 //-----------------------------------------------------------------------------
610 // Protected
611 /**
612  * \brief Checks the write integrity
613  *
614  * The tests made are :
615  *  - verify the size of the image to write with the possible write
616  *    when the user set an image data
617  * @return true if check is successfull
618  */
619 bool FileHelper::CheckWriteIntegrity()
620 {
621    if(PixelWriteConverter->GetUserData())
622    {
623       int numberBitsAllocated = FileInternal->GetBitsAllocated();
624       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
625       {
626          numberBitsAllocated = 16;
627       }
628
629       size_t decSize = FileInternal->GetXSize()
630                     * FileInternal->GetYSize() 
631                     * FileInternal->GetZSize()
632                     * ( numberBitsAllocated / 8 )
633                     * FileInternal->GetSamplesPerPixel();
634       size_t rgbSize = decSize;
635       if( FileInternal->HasLUT() )
636          rgbSize = decSize * 3;
637
638       switch(WriteMode)
639       {
640          case WMODE_RAW :
641             if( decSize!=PixelWriteConverter->GetUserDataSize() )
642             {
643                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
644                            << decSize << " / Found :" 
645                            << PixelWriteConverter->GetUserDataSize() );
646                return false;
647             }
648             break;
649          case WMODE_RGB :
650             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
651             {
652                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
653                           << decSize << " / Found " 
654                           << PixelWriteConverter->GetUserDataSize() );
655                return false;
656             }
657             break;
658       }
659    }
660    
661    return true;
662 }
663
664 /**
665  * \brief Updates the File to write RAW data (as opposed to RGB data)
666  *       (modifies, when necessary, photochromatic interpretation, 
667  *       bits allocated, Pixels element VR)
668  */ 
669 void FileHelper::SetWriteToRaw()
670 {
671    if( FileInternal->GetNumberOfScalarComponents() == 3 
672     && !FileInternal->HasLUT())
673    {
674       SetWriteToRGB();
675    } 
676    else
677    {
678       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
679       if(FileInternal->HasLUT())
680       {
681          photInt->SetValue("PALETTE COLOR ");
682       }
683       else
684       {
685          photInt->SetValue("MONOCHROME2 ");
686       }
687
688       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
689                                        PixelReadConverter->GetRawSize());
690
691       std::string vr = "OB";
692       if( FileInternal->GetBitsAllocated()>8 )
693          vr = "OW";
694       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
695          vr = "OB";
696       BinEntry *pixel = 
697          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
698       pixel->SetValue(GDCM_BINLOADED);
699       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
700       pixel->SetLength(PixelWriteConverter->GetDataSize());
701
702       Archive->Push(photInt);
703       Archive->Push(pixel);
704    }
705 }
706
707 /**
708  * \brief Updates the File to write RGB data (as opposed to RAW data)
709  *       (modifies, when necessary, photochromatic interpretation, 
710  *       samples per pixel, Planar configuration, 
711  *       bits allocated, bits stored, high bit -ACR 24 bits-
712  *       Pixels element VR, pushes out the LUT, )
713  */ 
714 void FileHelper::SetWriteToRGB()
715 {
716    if(FileInternal->GetNumberOfScalarComponents()==3)
717    {
718       PixelReadConverter->BuildRGBImage();
719       
720       ValEntry *spp = CopyValEntry(0x0028,0x0002);
721       spp->SetValue("3 ");
722
723       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
724       planConfig->SetValue("0 ");
725
726       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
727       photInt->SetValue("RGB ");
728
729       if(PixelReadConverter->GetRGB())
730       {
731          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
732                                           PixelReadConverter->GetRGBSize());
733       }
734       else // Raw data
735       {
736          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
737                                           PixelReadConverter->GetRawSize());
738       }
739
740       std::string vr = "OB";
741       if( FileInternal->GetBitsAllocated()>8 )
742          vr = "OW";
743       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
744          vr = "OB";
745       BinEntry *pixel = 
746          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
747       pixel->SetValue(GDCM_BINLOADED);
748       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
749       pixel->SetLength(PixelWriteConverter->GetDataSize());
750
751       Archive->Push(spp);
752       Archive->Push(planConfig);
753       Archive->Push(photInt);
754       Archive->Push(pixel);
755
756       // Remove any LUT
757       Archive->Push(0x0028,0x1101);
758       Archive->Push(0x0028,0x1102);
759       Archive->Push(0x0028,0x1103);
760       Archive->Push(0x0028,0x1201);
761       Archive->Push(0x0028,0x1202);
762       Archive->Push(0x0028,0x1203);
763
764       // For old '24 Bits' ACR-NEMA
765       // Thus, we have a RGB image and the bits allocated = 24 and 
766       // samples per pixels = 1 (in the read file)
767       if(FileInternal->GetBitsAllocated()==24) 
768       {
769          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
770          bitsAlloc->SetValue("8 ");
771
772          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
773          bitsStored->SetValue("8 ");
774
775          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
776          highBit->SetValue("7 ");
777
778          Archive->Push(bitsAlloc);
779          Archive->Push(bitsStored);
780          Archive->Push(highBit);
781       }
782    }
783    else
784    {
785       SetWriteToRaw();
786    }
787 }
788
789 /**
790  * \brief Restore the File write mode  
791  */ 
792 void FileHelper::RestoreWrite()
793 {
794    Archive->Restore(0x0028,0x0002);
795    Archive->Restore(0x0028,0x0004);
796    Archive->Restore(0x0028,0x0006);
797    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
798
799    // For old ACR-NEMA (24 bits problem)
800    Archive->Restore(0x0028,0x0100);
801    Archive->Restore(0x0028,0x0101);
802    Archive->Restore(0x0028,0x0102);
803
804    // For the LUT
805    Archive->Restore(0x0028,0x1101);
806    Archive->Restore(0x0028,0x1102);
807    Archive->Restore(0x0028,0x1103);
808    Archive->Restore(0x0028,0x1201);
809    Archive->Restore(0x0028,0x1202);
810    Archive->Restore(0x0028,0x1203);
811
812    // group 0002 may be pushed out for ACR-NEMA writting purposes 
813    Archive->Restore(0x0002,0x0000);
814    Archive->Restore(0x0002,0x0001);
815    Archive->Restore(0x0002,0x0002);
816    Archive->Restore(0x0002,0x0003);
817    Archive->Restore(0x0002,0x0010);
818    Archive->Restore(0x0002,0x0012);
819    Archive->Restore(0x0002,0x0013);
820    Archive->Restore(0x0002,0x0016);
821    Archive->Restore(0x0002,0x0100);
822    Archive->Restore(0x0002,0x0102);
823 }
824
825 /**
826  * \brief Pushes out the whole group 0002
827  *        FIXME : better, set a flag to tell the writer not to write it ...
828  *        FIXME : method should probably have an other name !
829  *                SetWriteFileTypeToACR is NOT opposed to 
830  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
831  */ 
832 void FileHelper::SetWriteFileTypeToACR()
833 {
834    Archive->Push(0x0002,0x0000);
835    Archive->Push(0x0002,0x0001);
836    Archive->Push(0x0002,0x0002);
837    Archive->Push(0x0002,0x0003);
838    Archive->Push(0x0002,0x0010);// Only TransferSyntax was pushed out !
839    Archive->Push(0x0002,0x0012);
840    Archive->Push(0x0002,0x0013);
841    Archive->Push(0x0002,0x0016);
842    Archive->Push(0x0002,0x0100);
843    Archive->Push(0x0002,0x0102);
844 }
845
846 /**
847  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
848  */ 
849 void FileHelper::SetWriteFileTypeToExplicitVR()
850 {
851    std::string ts = Util::DicomString( 
852       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
853
854    ValEntry *tss = CopyValEntry(0x0002,0x0010);
855    tss->SetValue(ts);
856
857    Archive->Push(tss);
858 }
859
860 /**
861  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
862  */ 
863 void FileHelper::SetWriteFileTypeToImplicitVR()
864 {
865    std::string ts = Util::DicomString(
866       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
867
868    ValEntry *tss = CopyValEntry(0x0002,0x0010);
869    tss->SetValue(ts);
870
871    Archive->Push(tss);
872 }
873
874
875 /**
876  * \brief Restore in the File the initial group 0002
877  */ 
878 void FileHelper::RestoreWriteFileType()
879 {
880    // group 0002 may be pushed out for ACR-NEMA writting purposes 
881    Archive->Restore(0x0002,0x0000);
882    Archive->Restore(0x0002,0x0001);
883    Archive->Restore(0x0002,0x0002);
884    Archive->Restore(0x0002,0x0003);
885    Archive->Restore(0x0002,0x0010);//only TransferSyntax was pushed out/restored
886    Archive->Restore(0x0002,0x0012);
887    Archive->Restore(0x0002,0x0013);
888    Archive->Restore(0x0002,0x0016);
889    Archive->Restore(0x0002,0x0100);
890    Archive->Restore(0x0002,0x0102);
891 }
892
893 /**
894  * \brief Set the Write not to Libido format
895  */ 
896 void FileHelper::SetWriteToLibido()
897 {
898    ValEntry *oldRow = dynamic_cast<ValEntry *>
899                 (FileInternal->GetDocEntry(0x0028, 0x0010));
900    ValEntry *oldCol = dynamic_cast<ValEntry *>
901                 (FileInternal->GetDocEntry(0x0028, 0x0011));
902    
903    if( oldRow && oldCol )
904    {
905       std::string rows, columns; 
906
907       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
908       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
909
910       newRow->Copy(oldCol);
911       newCol->Copy(oldRow);
912
913       newRow->SetValue(oldCol->GetValue());
914       newCol->SetValue(oldRow->GetValue());
915
916       Archive->Push(newRow);
917       Archive->Push(newCol);
918    }
919
920    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
921    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
922    Archive->Push(libidoCode);
923 }
924
925 /**
926  * \brief Set the Write not to No Libido format
927  */ 
928 void FileHelper::SetWriteToNoLibido()
929 {
930    ValEntry *recCode = dynamic_cast<ValEntry *>
931                 (FileInternal->GetDocEntry(0x0008,0x0010));
932    if( recCode )
933    {
934       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
935       {
936          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
937          libidoCode->SetValue("");
938          Archive->Push(libidoCode);
939       }
940    }
941 }
942
943 /**
944  * \brief Restore the Write format
945  */ 
946 void FileHelper::RestoreWriteOfLibido()
947 {
948    Archive->Restore(0x0028,0x0010);
949    Archive->Restore(0x0028,0x0011);
950    Archive->Restore(0x0008,0x0010);
951 }
952
953 /**
954  * \brief Duplicates a ValEntry or creates it.
955  * @param   group   Group number of the Entry 
956  * @param   elem  Element number of the Entry
957  * \return  pointer to the new Val Entry (NULL when creation failed).          
958  */ 
959 ValEntry *FileHelper::CopyValEntry(uint16_t group, uint16_t elem)
960 {
961    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
962    ValEntry *newE;
963
964    if( oldE )
965    {
966       newE = new ValEntry(oldE->GetDictEntry());
967       newE->Copy(oldE);
968    }
969    else
970    {
971       newE = GetFile()->NewValEntry(group, elem);
972    }
973
974    return newE;
975 }
976
977 /**
978  * \brief   Duplicates a BinEntry or creates it.
979  * @param   group   Group number of the Entry 
980  * @param   elem  Element number of the Entry
981  * @param   vr  Value Representation of the Entry
982  *          FIXME : what is it used for?
983  * \return  pointer to the new Bin Entry (NULL when creation failed).
984  */ 
985 BinEntry *FileHelper::CopyBinEntry(uint16_t group, uint16_t elem,
986                                    const std::string &vr)
987 {
988    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
989    BinEntry *newE;
990
991    if( oldE )
992       if( oldE->GetVR()!=vr )
993          oldE = NULL;
994
995    if( oldE )
996    {
997       newE = new BinEntry(oldE->GetDictEntry());
998       newE->Copy(oldE);
999    }
1000    else
1001    {
1002       newE = GetFile()->NewBinEntry(group, elem, vr);
1003    }
1004
1005    return newE;
1006 }
1007
1008 /**
1009  * \brief   Checks the Mandatory Elements
1010  *          adds the mandatory Entries if not found
1011  *          (when user asks to write as a DICOM file, an ACR-NEMA file
1012  *           he read before)
1013  */ 
1014 void FileHelper::CheckMandatoryElements()
1015 {
1016    // just to remember : 'official' 0002 group
1017
1018    //0002 0000 UL 1 Meta Group Length
1019    //0002 0001 OB 1 File Meta Information Version
1020    //0002 0002 UI 1 Media Stored SOP Class UID
1021    //0002 0003 UI 1 Media Stored SOP Instance UID
1022    //0002 0010 UI 1 Transfer Syntax UID
1023    //0002 0012 UI 1 Implementation Class UID
1024    //0002 0013 SH 1 Implementation Version Name
1025    //0002 0016 AE 1 Source Application Entity Title
1026    //0002 0100 UI 1 Private Information Creator
1027    //0002 0102 OB 1 Private Information
1028
1029    // Create them if not found
1030    ValEntry *e_0002_0000 = CopyValEntry(0x0002,0x0000);
1031       e_0002_0000->SetValue("0"); // for the moment
1032       Archive->Push(e_0002_0000);
1033   
1034    BinEntry *e_0002_0001 = CopyBinEntry(0x0002,0x0001, "OB");
1035       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1036                                false);
1037       e_0002_0001->SetLength(2);
1038
1039    ValEntry *e_0002_0002 = CopyValEntry(0x0002,0x0002);
1040       // [Secondary Capture Image Storage]
1041       e_0002_0002->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1042       Archive->Push(e_0002_0002);
1043  
1044    // 'Media Stored SOP Instance UID'   
1045    ValEntry *e_0002_0003 = CopyValEntry(0x0002,0x0003);
1046       e_0002_0003->SetValue(Util::CreateUniqueUID());
1047       Archive->Push(e_0002_0003); 
1048
1049    ValEntry *e_0002_0010 = CopyValEntry(0x0002,0x0010);
1050       //[Explicit VR - Little Endian] 
1051       e_0002_0010->SetValue("1.2.840.10008.1.2.1"); 
1052       Archive->Push(e_0002_0010);
1053  
1054    // 'Implementation Class UID'
1055    ValEntry *e_0002_0012 = CopyValEntry(0x0002,0x0012);
1056       e_0002_0012->SetValue(Util::CreateUniqueUID());
1057       Archive->Push(e_0002_0012); 
1058
1059    // 'Implementation Version Name'
1060    ValEntry *e_0002_0013 = CopyValEntry(0x0002,0x0013);
1061       e_0002_0013->SetValue("GDCM 1.0");
1062       Archive->Push(e_0002_0013);
1063
1064    //'Source Application Entity Title' Not Mandatory
1065    //ValEntry *e_0002_0016 = CopyValEntry(0x0002,0x0016);
1066    //   e_0002_0016->SetValue("1.2.840.10008.5.1.4.1.1.7");
1067    //   Archive->Push(e_0002_0016);
1068
1069    // Push out 'LibIDO-special' entries, if any
1070    Archive->Push(0x0028,0x0015);
1071    Archive->Push(0x0028,0x0016);
1072    Archive->Push(0x0028,0x0017);
1073    Archive->Push(0x0028,0x00199);
1074
1075    // --- Check UID-related Entries ---
1076
1077    // If 'SOP Class UID' exists ('true DICOM' image)
1078
1079    ValEntry *e_0008_0016 = FileInternal->GetValEntry(0x0008, 0x0016);
1080    if ( e_0008_0016 != 0 )
1081    {
1082       // Create 'Source Image Sequence' SeqEntry
1083       SeqEntry *s = new SeqEntry (
1084       Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1085       SQItem *sqi = new SQItem(1);
1086       // (we assume 'SOP Instance UID' exists too) 
1087       // create 'Referenced SOP Class UID'
1088       ValEntry *e_0008_1150 = new ValEntry(
1089       Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1090       e_0008_1150->SetValue( e_0008_0016->GetValue());
1091       sqi->AddEntry(e_0008_1150);
1092       
1093       // create 'Referenced SOP Instance UID'
1094       ValEntry *e_0008_0018 = FileInternal->GetValEntry(0x0008, 0x0018);
1095       ValEntry *e_0008_1155 = new ValEntry(
1096             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1097       e_0008_1155->SetValue( e_0008_0018->GetValue());
1098       sqi->AddEntry(e_0008_1155);
1099
1100       s->AddSQItem(sqi,1); 
1101       // temporarily replaces any previous 'Source Image Sequence' 
1102       Archive->Push(s);
1103  
1104       // 'Image Type'
1105       ValEntry *e_0008_0008 = CopyValEntry(0x0008,0x0008);
1106       e_0008_0008->SetValue("DERIVED\\PRIMARY");
1107       Archive->Push(e_0008_0008);
1108    } 
1109    else
1110    {
1111    // SOP Class UID
1112       ValEntry *e_0008_0016  =  new ValEntry( 
1113             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0016) );
1114       // [Secondary Capture Image Storage]
1115       e_0008_0016 ->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1116       Archive->Push(e_0008_0016); 
1117    }
1118
1119    // new value for 'SOP Instance UID'
1120    ValEntry *e_0008_0018 = new ValEntry(
1121     Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0018) );
1122    e_0008_0018->SetValue( Util::CreateUniqueUID() );
1123    Archive->Push(e_0008_0018);
1124
1125    // Instance Creation Date
1126    ValEntry *e0008_0012 = CopyValEntry(0x0008,0x0012);
1127    std::string date = Util::GetCurrentDate();
1128    e0008_0012->SetValue(date.c_str());
1129    Archive->Push(e0008_0012);
1130  
1131    // Instance Creation Time
1132    ValEntry *e0008_0013 = CopyValEntry(0x0008,0x0013);
1133    std::string time = Util::GetCurrentTime();
1134    e0008_0013->SetValue(time.c_str());
1135    Archive->Push(e0008_0013);
1136
1137    // new value for 'Serie Instance UID'
1138    // TODO prevoir booleen pour figer la valeur d'un appel a l'autre
1139    //                           calculer nouvelle valeur a chaque fois
1140
1141    ValEntry *e_0020_000e = new ValEntry(
1142             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000e) );
1143    e_0020_000e->SetValue( Util::CreateUniqueUID() );
1144    Archive->Push(e_0020_000e);
1145
1146    // new value for 'Study Instance UID'
1147    // TODO prevoir flag pour figer la valeurd'un appel a l'autre
1148    //                        calculer nouvelle valeur a chaque fois
1149    //                        reutiliser mla valeur image origine
1150
1151    ValEntry *e_0020_000d = new ValEntry(
1152             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000d) );
1153    e_0020_000d->SetValue( Util::CreateUniqueUID() );
1154    Archive->Push(e_0020_000d);
1155
1156 // ----- Add Mandatory Entries if missing ---
1157
1158 // Entries whose type is 1 are mandatory, with a mandatory value
1159 // Entries whose type is 1c are ?
1160 // Entries whose type is 2 are mandatory, with a optional value
1161 // Entries whose type is 2c are ?
1162 // Entries whose type is 3 are optional
1163    ValEntry *e;
1164
1165    // Modality
1166    e = FileInternal->GetValEntry(0x0008, 0x0060);
1167    if ( !e )
1168    {
1169       e = InsertValEntry("OT",           0x0008, 0x0060);
1170       Archive->Push(e);
1171    } 
1172    // Manufacturer
1173    e = FileInternal->GetValEntry(0x0008, 0x0070);
1174    if ( !e )
1175    {
1176       e = InsertValEntry("GDCM Factory", 0x0008, 0x0070);
1177       Archive->Push(e);
1178    }
1179    // Institution Name
1180    e = FileInternal->GetValEntry(0x0008, 0x0070);
1181    if ( !e )
1182    {
1183       e = InsertValEntry("GDCM Hospital",0x0008, 0x0080);
1184       Archive->Push(e);
1185    }
1186    // Institution Adress
1187    e = FileInternal->GetValEntry(0x0008, 0x0081);
1188    if ( !e )
1189    {
1190       e = InsertValEntry("@ GDCM",       0x0008, 0x0081);
1191       Archive->Push(e);
1192    }
1193    // Patient's Name
1194    e = FileInternal->GetValEntry(0x0010, 0x0010);
1195    if ( !e )
1196    {
1197       e = InsertValEntry("GDCM^patient", 0x0010, 0x0010);
1198       Archive->Push(e);
1199    }
1200    // Patient's ID
1201    e = FileInternal->GetValEntry(0x0010, 0x0020);
1202    if ( !e )
1203    {
1204       e = InsertValEntry("GDCM_patient_ID",0x0010, 0x0020);
1205       Archive->Push(e);
1206    }
1207
1208    // Patient's Birth Date
1209    e = FileInternal->GetValEntry(0x0010, 0x0030);
1210    if ( !e )
1211    {
1212       e = InsertValEntry("",0x0010, 0x0030);
1213       Archive->Push(e);
1214    }
1215
1216    // Patient's Sex
1217    e = FileInternal->GetValEntry(0x0010, 0x0040);
1218    if ( !e )
1219    {
1220       e = InsertValEntry("",0x0010, 0x0040);
1221       Archive->Push(e);
1222    }
1223
1224    // Referring Physician's Name
1225    e = FileInternal->GetValEntry(0x0008, 0x0090);
1226    if ( !e )
1227    {
1228       e = InsertValEntry("",0x0008, 0x0090);
1229       Archive->Push(e);
1230    }
1231
1232
1233  
1234 //-----------------------------------------------------------------------------
1235 // Private
1236 /**
1237  * \brief Factorization for various forms of constructors.
1238  */
1239 void FileHelper::Initialize()
1240 {
1241    WriteMode = WMODE_RAW;
1242    WriteType = ExplicitVR;
1243
1244    PixelReadConverter = new PixelReadConvert;
1245    PixelWriteConverter = new PixelWriteConvert;
1246    Archive = new DocEntryArchive( FileInternal );
1247
1248    if ( FileInternal->IsReadable() )
1249    {
1250       PixelReadConverter->GrabInformationsFromFile( FileInternal );
1251    }
1252 }
1253
1254 /**
1255  * \brief   
1256  */ 
1257 uint8_t *FileHelper::GetRaw()
1258 {
1259    uint8_t *raw = PixelReadConverter->GetRaw();
1260    if ( ! raw )
1261    {
1262       // The Raw image migth not be loaded yet:
1263       std::ifstream *fp = FileInternal->OpenFile();
1264       PixelReadConverter->ReadAndDecompressPixelData( fp );
1265       if(fp) 
1266          FileInternal->CloseFile();
1267
1268       raw = PixelReadConverter->GetRaw();
1269       if ( ! raw )
1270       {
1271          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1272          return 0;
1273       }
1274    }
1275
1276    return raw;
1277 }
1278
1279 //-----------------------------------------------------------------------------
1280 // Print
1281 void FileHelper::Print(std::ostream &os, std::string const &)
1282 {
1283    FileInternal->SetPrintLevel(PrintLevel);
1284    FileInternal->Print(os);
1285
1286    PixelReadConverter->SetPrintLevel(PrintLevel);
1287    PixelReadConverter->Print(os);
1288 }
1289
1290 //-----------------------------------------------------------------------------
1291 } // end namespace gdcm