]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
Default Photometric Interpretation is now MONOCHROME2 (low values=dark !)
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/11 11:22:59 $
7   Version:   $Revision: 1.16 $
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 "gdcmContentEntry.h"
28 #include "gdcmFile.h"
29 #include "gdcmPixelReadConvert.h"
30 #include "gdcmPixelWriteConvert.h"
31 #include "gdcmDocEntryArchive.h"
32
33 #include <fstream>
34
35 namespace gdcm 
36 {
37 //-------------------------------------------------------------------------
38 // Constructor / Destructor
39 /**
40  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
41  *        file (gdcm::File only deals with the ... header)
42  *        Opens (in read only and when possible) an existing file and checks
43  *        for DICOM compliance. Returns NULL on failure.
44  *        It will be up to the user to load the pixels into memory
45  * \note  the in-memory representation of all available tags found in
46  *        the DICOM header is post-poned to first header information access.
47  *        This avoid a double parsing of public part of the header when
48  *        one sets an a posteriori shadow dictionary (efficiency can be
49  *        seen as a side effect).   
50  */
51 FileHelper::FileHelper( )
52 {
53    FileInternal = new File( );
54    SelfHeader = true;
55    Initialize();
56 }
57
58 /**
59  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
60  *        file (File only deals with the ... header)
61  *        Opens (in read only and when possible) an existing file and checks
62  *        for DICOM compliance. Returns NULL on failure.
63  *        It will be up to the user to load the pixels into memory
64  * \note  the in-memory representation of all available tags found in
65  *        the DICOM header is post-poned to first header information access.
66  *        This avoid a double parsing of public part of the header when
67  *        user sets an a posteriori shadow dictionary (efficiency can be
68  *        seen as a side effect).   
69  * @param header already built Header
70  */
71 FileHelper::FileHelper(File *header)
72 {
73    FileInternal = header;
74    SelfHeader = false;
75    Initialize();
76 }
77
78 /**
79  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
80  *        file (gdcm::File only deals with the ... header)
81  *        Opens (in read only and when possible) an existing file and checks
82  *        for DICOM compliance. Returns NULL on failure.
83  *        It will be up to the user to load the pixels into memory
84  * \note  the in-memory representation of all available tags found in
85  *        the DICOM header is post-poned to first header information access.
86  *        This avoid a double parsing of public part of the header when
87  *        one sets an a posteriori shadow dictionary (efficiency can be
88  *        seen as a side effect).   
89  * @param filename file to be opened for parsing
90  */
91 FileHelper::FileHelper(std::string const &filename )
92 {
93    FileInternal = new File( filename );
94    SelfHeader = true;
95    Initialize();
96 }
97
98 /**
99  * \brief canonical destructor
100  * \note  If the header (gdcm::File) was created by the FileHelper constructor,
101  *        it is destroyed by the FileHelper
102  */
103 FileHelper::~FileHelper()
104
105    if( PixelReadConverter )
106    {
107       delete PixelReadConverter;
108    }
109    if( PixelWriteConverter )
110    {
111       delete PixelWriteConverter;
112    }
113    if( Archive )
114    {
115       delete Archive;
116    }
117
118    if( SelfHeader )
119    {
120       delete FileInternal;
121    }
122    FileInternal = 0;
123 }
124
125 //-----------------------------------------------------------------------------
126 // Public
127 /**
128  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
129  *          through it's (group, element) and modifies it's content with
130  *          the given value.
131  * @param   content new value (string) to substitute with
132  * @param   group  group number of the Dicom Element to modify
133  * @param   elem element number of the Dicom Element to modify
134  */
135 bool FileHelper::SetValEntry(std::string const &content,
136                              uint16_t group, uint16_t elem)
137
138    return FileInternal->SetValEntry(content,group,elem);
139 }
140
141
142 /**
143  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
144  *          through it's (group, element) and modifies it's content with
145  *          the given value.
146  * @param   content new value (void*  -> uint8_t*) to substitute with
147  * @param   lgth new value length
148  * @param   group  group number of the Dicom Element to modify
149  * @param   elem element number of the Dicom Element to modify
150  */
151 bool FileHelper::SetBinEntry(uint8_t *content, int lgth,
152                              uint16_t group, uint16_t elem)
153 {
154    return FileInternal->SetBinEntry(content,lgth,group,elem);
155 }
156
157 /**
158  * \brief   Modifies the value of a given DocEntry (Dicom entry)
159  *          when it exists. Create it with the given value when unexistant.
160  * @param   content (string) Value to be set
161  * @param   group   Group number of the Entry 
162  * @param   elem  Element number of the Entry
163  * \return  pointer to the modified/created Dicom entry (NULL when creation
164  *          failed).
165  */ 
166 ValEntry *FileHelper::InsertValEntry(std::string const &content,
167                                      uint16_t group, uint16_t elem)
168 {
169    return FileInternal->InsertValEntry(content,group,elem);
170 }
171
172 /**
173  * \brief   Modifies the value of a given DocEntry (Dicom entry)
174  *          when it exists. Create it with the given value when unexistant.
175  *          A copy of the binArea is made to be kept in the Document.
176  * @param   binArea (binary) value to be set
177  * @param   lgth new value length
178  * @param   group   Group number of the Entry 
179  * @param   elem  Element number of the Entry
180  * \return  pointer to the modified/created Dicom entry (NULL when creation
181  *          failed).
182  */
183 BinEntry *FileHelper::InsertBinEntry(uint8_t *binArea, int lgth,
184                                      uint16_t group, uint16_t elem)
185 {
186    return FileInternal->InsertBinEntry(binArea,lgth,group,elem);
187 }
188
189 /**
190  * \brief   Modifies the value of a given DocEntry (Dicom entry)
191  *          when it exists. Create it with the given value when unexistant.
192  *          A copy of the binArea is made to be kept in the Document.
193  * @param   group   Group number of the Entry 
194  * @param   elem  Element number of the Entry
195  * \return  pointer to the modified/created Dicom entry (NULL when creation
196  *          failed).
197  */
198 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
199 {
200    return FileInternal->InsertSeqEntry(group,elem);
201 }
202
203 /**
204  * \brief   Get the size of the image data
205  *          If the image can be RGB (with a lut or by default), the size 
206  *          corresponds to the RGB image
207  *         (use GetImageDataRawSize if you want to be sure to get *only*
208  *          the size of the pixels)
209  * @return  The image size
210  */
211 size_t FileHelper::GetImageDataSize()
212 {
213    if ( PixelWriteConverter->GetUserData() )
214    {
215       return PixelWriteConverter->GetUserDataSize();
216    }
217
218    return PixelReadConverter->GetRGBSize();
219 }
220
221 /**
222  * \brief   Get the size of the image data
223  *          If the image could be converted to RGB using a LUT, 
224  *          this transformation is not taken into account by GetImageDataRawSize
225  *          (use GetImageDataSize if you wish)
226  * @return  The raw image size
227  */
228 size_t FileHelper::GetImageDataRawSize()
229 {
230    if ( PixelWriteConverter->GetUserData() )
231    {
232       return PixelWriteConverter->GetUserDataSize();
233    }
234
235    return PixelReadConverter->GetRawSize();
236 }
237
238 /**
239  * \brief   - Allocates necessary memory,
240  *          - Reads the pixels from disk (uncompress if necessary),
241  *          - Transforms YBR pixels, if any, into RGB pixels,
242  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
243  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
244  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
245  * @return  Pointer to newly allocated pixel data.
246  *          NULL if alloc fails 
247  */
248 uint8_t *FileHelper::GetImageData()
249 {
250    if ( PixelWriteConverter->GetUserData() )
251    {
252       return PixelWriteConverter->GetUserData();
253    }
254
255    if ( ! GetRaw() )
256    {
257       // If the decompression failed nothing can be done.
258       return 0;
259    }
260
261    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
262    {
263       return PixelReadConverter->GetRGB();
264    }
265    else
266    {
267       // When no LUT or LUT conversion fails, return the Raw
268       return PixelReadConverter->GetRaw();
269    }
270 }
271
272 /**
273  * \brief   Allocates necessary memory, 
274  *          Transforms YBR pixels (if any) into RGB pixels
275  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
276  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
277  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
278  * @return  Pointer to newly allocated pixel data.
279  * \        NULL if alloc fails 
280  */
281 uint8_t *FileHelper::GetImageDataRaw ()
282 {
283    return GetRaw();
284 }
285
286 /**
287  * \brief
288  *          Read the pixels from disk (uncompress if necessary),
289  *          Transforms YBR pixels, if any, into RGB pixels
290  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
291  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
292  *          Copies at most MaxSize bytes of pixel data to caller allocated
293  *          memory space.
294  * \warning This function allows people that want to build a volume
295  *          from an image stack *not to* have, first to get the image pixels, 
296  *          and then move them to the volume area.
297  *          It's absolutely useless for any VTK user since vtk chooses 
298  *          to invert the lines of an image, that is the last line comes first
299  *          (for some axis related reasons?). Hence he will have 
300  *          to load the image line by line, starting from the end.
301  *          VTK users have to call GetImageData
302  *     
303  * @param   destination Address (in caller's memory space) at which the
304  *          pixel data should be copied
305  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
306  *          is not sufficient to hold the pixel data the copy is not
307  *          executed (i.e. no partial copy).
308  * @return  On success, the number of bytes actually copied. Zero on
309  *          failure e.g. MaxSize is lower than necessary.
310  */
311 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
312 {
313    if ( ! GetRaw() )
314    {
315       // If the decompression failed nothing can be done.
316       return 0;
317    }
318
319    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
320    {
321       if ( PixelReadConverter->GetRGBSize() > maxSize )
322       {
323          gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
324          return 0;
325       }
326       memcpy( destination,
327               (void*)PixelReadConverter->GetRGB(),
328               PixelReadConverter->GetRGBSize() );
329       return PixelReadConverter->GetRGBSize();
330    }
331
332    // Either no LUT conversion necessary or LUT conversion failed
333    if ( PixelReadConverter->GetRawSize() > maxSize )
334    {
335       gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
336       return 0;
337    }
338    memcpy( destination,
339            (void*)PixelReadConverter->GetRaw(),
340            PixelReadConverter->GetRawSize() );
341    return PixelReadConverter->GetRawSize();
342 }
343
344 /**
345  * \brief   Points the internal pointer to the callers inData
346  *          image representation, BUT WITHOUT COPYING THE DATA.
347  *          'image' Pixels are presented as C-like 2D arrays : line per line.
348  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
349  * \warning Since the pixels are not copied, it is the caller's responsability
350  *          not to deallocate its data before gdcm uses them (e.g. with
351  *          the Write() method )
352  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
353  *               user is allowed to pass any kind of pixelsn since the size is
354  *               given in bytes) 
355  * @param expectedSize total image size, *in Bytes*
356  *
357  * @return boolean
358  */
359 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
360 {
361    SetUserData(inData,expectedSize);
362 }
363
364 /**
365  * \brief   Set the image data defined by the user
366  * \warning When writting the file, this data are get as default data to write
367  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
368  *               user is allowed to pass any kind of pixelsn since the size is
369  *               given in bytes) 
370  * @param expectedSize total image size, *in Bytes*
371  
372  */
373 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
374 {
375    PixelWriteConverter->SetUserData(inData,expectedSize);
376 }
377
378 /**
379  * \brief   Get the image data defined by the user
380  * \warning When writting the file, this data are get as default data to write
381  */
382 uint8_t *FileHelper::GetUserData()
383 {
384    return PixelWriteConverter->GetUserData();
385 }
386
387 /**
388  * \brief   Get the image data size defined by the user
389  * \warning When writting the file, this data are get as default data to write
390  */
391 size_t FileHelper::GetUserDataSize()
392 {
393    return PixelWriteConverter->GetUserDataSize();
394 }
395
396 /**
397  * \brief   Get the image data from the file.
398  *          If a LUT is found, the data are expanded to be RGB
399  */
400 uint8_t *FileHelper::GetRGBData()
401 {
402    return PixelReadConverter->GetRGB();
403 }
404
405 /**
406  * \brief   Get the image data size from the file.
407  *          If a LUT is found, the data are expanded to be RGB
408  */
409 size_t FileHelper::GetRGBDataSize()
410 {
411    return PixelReadConverter->GetRGBSize();
412 }
413
414 /**
415  * \brief   Get the image data from the file.
416  *          If a LUT is found, the data are not expanded !
417  */
418 uint8_t *FileHelper::GetRawData()
419 {
420    return PixelReadConverter->GetRaw();
421 }
422
423 /**
424  * \brief   Get the image data size from the file.
425  *          If a LUT is found, the data are not expanded !
426  */
427 size_t FileHelper::GetRawDataSize()
428 {
429    return PixelReadConverter->GetRawSize();
430 }
431
432 /**
433  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
434  */
435 uint8_t* FileHelper::GetLutRGBA()
436 {
437    return PixelReadConverter->GetLutRGBA();
438 }
439
440 /**
441  * \brief Writes on disk A SINGLE Dicom file
442  *        NO test is performed on  processor "Endiannity".
443  *        It's up to the user to call his Reader properly
444  * @param fileName name of the file to be created
445  *                 (any already existing file is over written)
446  * @return false if write fails
447  */
448 bool FileHelper::WriteRawData(std::string const &fileName)
449 {
450   std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
451    if (!fp1)
452    {
453       gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
454       return false;
455    }
456
457    if( PixelWriteConverter->GetUserData() )
458    {
459       fp1.write( (char*)PixelWriteConverter->GetUserData(), 
460                  PixelWriteConverter->GetUserDataSize() );
461    }
462    else if ( PixelReadConverter->GetRGB() )
463    {
464       fp1.write( (char*)PixelReadConverter->GetRGB(), 
465                  PixelReadConverter->GetRGBSize());
466    }
467    else if ( PixelReadConverter->GetRaw() )
468    {
469       fp1.write( (char*)PixelReadConverter->GetRaw(), 
470                  PixelReadConverter->GetRawSize());
471    }
472    else
473    {
474       gdcmErrorMacro( "Nothing written." );
475    }
476
477    fp1.close();
478
479    return true;
480 }
481
482 /**
483  * \brief Writes on disk A SINGLE Dicom file, 
484  *        using the Implicit Value Representation convention
485  *        NO test is performed on  processor "Endiannity".
486  * @param fileName name of the file to be created
487  *                 (any already existing file is overwritten)
488  * @return false if write fails
489  */
490
491 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
492 {
493    SetWriteTypeToDcmImplVR();
494    return Write(fileName);
495 }
496
497 /**
498 * \brief Writes on disk A SINGLE Dicom file, 
499  *        using the Explicit Value Representation convention
500  *        NO test is performed on  processor "Endiannity". 
501  * @param fileName name of the file to be created
502  *                 (any already existing file is overwritten)
503  * @return false if write fails
504  */
505
506 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
507 {
508    SetWriteTypeToDcmExplVR();
509    return Write(fileName);
510 }
511
512 /**
513  * \brief Writes on disk A SINGLE Dicom file, 
514  *        using the ACR-NEMA convention
515  *        NO test is performed on  processor "Endiannity".
516  *        (a l'attention des logiciels cliniques 
517  *        qui ne prennent en entrée QUE des images ACR ...
518  * \warning if a DICOM_V3 header is supplied,
519  *         groups < 0x0008 and shadow groups are ignored
520  * \warning NO TEST is performed on processor "Endiannity".
521  * @param fileName name of the file to be created
522  *                 (any already existing file is overwritten)
523  * @return false if write fails
524  */
525
526 bool FileHelper::WriteAcr (std::string const &fileName)
527 {
528    SetWriteTypeToAcr();
529    return Write(fileName);
530 }
531
532 /**
533  * \brief Writes on disk A SINGLE Dicom file, 
534  * @param fileName name of the file to be created
535  *                 (any already existing file is overwritten)
536  * @return false if write fails
537  */
538 bool FileHelper::Write(std::string const &fileName)
539 {
540    switch(WriteType)
541    {
542       case ImplicitVR:
543          SetWriteFileTypeToImplicitVR();
544          break;
545       case ExplicitVR:
546          SetWriteFileTypeToExplicitVR();
547          break;
548       case ACR:
549       case ACR_LIBIDO:
550          SetWriteFileTypeToACR();
551          break;
552       default:
553          SetWriteFileTypeToExplicitVR();
554    }
555
556    // --------------------------------------------------------------
557    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
558    //
559    // if recognition code tells us we dealt with a LibIDO image
560    // we reproduce on disk the switch between lineNumber and columnNumber
561    // just before writting ...
562    /// \todo the best trick would be *change* the recognition code
563    ///       but pb expected if user deals with, e.g. COMPLEX images
564    if( WriteType == ACR_LIBIDO )
565    {
566       SetWriteToLibido();
567    }
568    else
569    {
570       SetWriteToNoLibido();
571    }
572    // ----------------- End of Special Patch ----------------
573   
574    switch(WriteMode)
575    {
576       case WMODE_RAW :
577          SetWriteToRaw();
578          break;
579       case WMODE_RGB :
580          SetWriteToRGB();
581          break;
582    }
583
584    bool check = CheckWriteIntegrity();
585    if(check)
586    {
587       check = FileInternal->Write(fileName,WriteType);
588    }
589
590    RestoreWrite();
591    RestoreWriteFileType();
592
593    // --------------------------------------------------------------
594    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
595    // 
596    // ...and we restore the header to be Dicom Compliant again 
597    // just after writting
598    RestoreWriteOfLibido();
599    // ----------------- End of Special Patch ----------------
600
601    return check;
602 }
603
604 //-----------------------------------------------------------------------------
605 // Protected
606 /**
607  * \brief Check the write integrity
608  *
609  * The tests made are :
610  *  - verify the size of the image to write with the possible write
611  *    when the user set an image data
612  * @return true if check is successfull
613  */
614 bool FileHelper::CheckWriteIntegrity()
615 {
616    if(PixelWriteConverter->GetUserData())
617    {
618       int numberBitsAllocated = FileInternal->GetBitsAllocated();
619       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
620       {
621          numberBitsAllocated = 16;
622       }
623
624       size_t decSize = FileInternal->GetXSize()
625                     * FileInternal->GetYSize() 
626                     * FileInternal->GetZSize()
627                     * ( numberBitsAllocated / 8 )
628                     * FileInternal->GetSamplesPerPixel();
629       size_t rgbSize = decSize;
630       if( FileInternal->HasLUT() )
631          rgbSize = decSize * 3;
632
633       switch(WriteMode)
634       {
635          case WMODE_RAW :
636             if( decSize!=PixelWriteConverter->GetUserDataSize() )
637             {
638                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
639                            << decSize << " / Found :" 
640                            << PixelWriteConverter->GetUserDataSize() );
641                return false;
642             }
643             break;
644          case WMODE_RGB :
645             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
646             {
647                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
648                           << decSize << " / Found " 
649                           << PixelWriteConverter->GetUserDataSize() );
650                return false;
651             }
652             break;
653       }
654    }
655    
656    return true;
657 }
658
659 /**
660  * \brief Update the File to write RAW datas  
661  */ 
662 void FileHelper::SetWriteToRaw()
663 {
664    if( FileInternal->GetNumberOfScalarComponents() == 3 
665     && !FileInternal->HasLUT())
666    {
667       SetWriteToRGB();
668    } 
669    else
670    {
671       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
672       if(FileInternal->HasLUT())
673       {
674          photInt->SetValue("PALETTE COLOR ");
675       }
676       else
677       {
678          photInt->SetValue("MONOCHROME2 ");
679       }
680
681       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
682                                        PixelReadConverter->GetRawSize());
683
684       std::string vr = "OB";
685       if( FileInternal->GetBitsAllocated()>8 )
686          vr = "OW";
687       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
688          vr = "OB";
689       BinEntry *pixel = 
690          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
691       pixel->SetValue(GDCM_BINLOADED);
692       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
693       pixel->SetLength(PixelWriteConverter->GetDataSize());
694
695       Archive->Push(photInt);
696       Archive->Push(pixel);
697    }
698 }
699
700 /**
701  * \brief Update the File to write RGB datas  
702  */ 
703 void FileHelper::SetWriteToRGB()
704 {
705    if(FileInternal->GetNumberOfScalarComponents()==3)
706    {
707       PixelReadConverter->BuildRGBImage();
708       
709       ValEntry *spp = CopyValEntry(0x0028,0x0002);
710       spp->SetValue("3 ");
711
712       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
713       planConfig->SetValue("0 ");
714
715       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
716       photInt->SetValue("RGB ");
717
718       if(PixelReadConverter->GetRGB())
719       {
720          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
721                                           PixelReadConverter->GetRGBSize());
722       }
723       else // Raw data
724       {
725          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
726                                           PixelReadConverter->GetRawSize());
727       }
728
729       std::string vr = "OB";
730       if( FileInternal->GetBitsAllocated()>8 )
731          vr = "OW";
732       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
733          vr = "OB";
734       BinEntry *pixel = 
735          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
736       pixel->SetValue(GDCM_BINLOADED);
737       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
738       pixel->SetLength(PixelWriteConverter->GetDataSize());
739
740       Archive->Push(spp);
741       Archive->Push(planConfig);
742       Archive->Push(photInt);
743       Archive->Push(pixel);
744
745       // Remove any LUT
746       Archive->Push(0x0028,0x1101);
747       Archive->Push(0x0028,0x1102);
748       Archive->Push(0x0028,0x1103);
749       Archive->Push(0x0028,0x1201);
750       Archive->Push(0x0028,0x1202);
751       Archive->Push(0x0028,0x1203);
752
753       // For old ACR-NEMA
754       // Thus, we have a RGB image and the bits allocated = 24 and 
755       // samples per pixels = 1 (in the read file)
756       if(FileInternal->GetBitsAllocated()==24) 
757       {
758          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
759          bitsAlloc->SetValue("8 ");
760
761          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
762          bitsStored->SetValue("8 ");
763
764          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
765          highBit->SetValue("7 ");
766
767          Archive->Push(bitsAlloc);
768          Archive->Push(bitsStored);
769          Archive->Push(highBit);
770       }
771    }
772    else
773    {
774       SetWriteToRaw();
775    }
776 }
777
778 /**
779  * \brief Restore the File write mode  
780  */ 
781 void FileHelper::RestoreWrite()
782 {
783    Archive->Restore(0x0028,0x0002);
784    Archive->Restore(0x0028,0x0004);
785    Archive->Restore(0x0028,0x0006);
786    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
787
788    // For old ACR-NEMA (24 bits problem)
789    Archive->Restore(0x0028,0x0100);
790    Archive->Restore(0x0028,0x0101);
791    Archive->Restore(0x0028,0x0102);
792
793    // For the LUT
794    Archive->Restore(0x0028,0x1101);
795    Archive->Restore(0x0028,0x1102);
796    Archive->Restore(0x0028,0x1103);
797    Archive->Restore(0x0028,0x1201);
798    Archive->Restore(0x0028,0x1202);
799    Archive->Restore(0x0028,0x1203);
800 }
801
802 /**
803  * \brief Set in the File the write type to ACR
804  */ 
805 void FileHelper::SetWriteFileTypeToACR()
806 {
807    Archive->Push(0x0002,0x0010);
808 }
809
810 /**
811  * \brief Set in the File the write type to Explicit VR   
812  */ 
813 void FileHelper::SetWriteFileTypeToExplicitVR()
814 {
815    std::string ts = Util::DicomString( 
816       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
817
818    ValEntry *tss = CopyValEntry(0x0002,0x0010);
819    tss->SetValue(ts);
820
821    Archive->Push(tss);
822 }
823
824 /**
825  * \brief Set in the File the write type to Implicit VR   
826  */ 
827 void FileHelper::SetWriteFileTypeToImplicitVR()
828 {
829    std::string ts = Util::DicomString(
830       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
831
832    ValEntry *tss = CopyValEntry(0x0002,0x0010);
833    tss->SetValue(ts);
834
835    Archive->Push(tss);
836 }
837
838
839 /**
840  * \brief Restore in the File the write type
841  */ 
842 void FileHelper::RestoreWriteFileType()
843 {
844    Archive->Restore(0x0002,0x0010);
845 }
846
847 /**
848  * \brief Set the Write not to Libido format
849  */ 
850 void FileHelper::SetWriteToLibido()
851 {
852    ValEntry *oldRow = dynamic_cast<ValEntry *>
853                 (FileInternal->GetDocEntry(0x0028, 0x0010));
854    ValEntry *oldCol = dynamic_cast<ValEntry *>
855                 (FileInternal->GetDocEntry(0x0028, 0x0011));
856    
857    if( oldRow && oldCol )
858    {
859       std::string rows, columns; 
860
861       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
862       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
863
864       newRow->Copy(oldCol);
865       newCol->Copy(oldRow);
866
867       newRow->SetValue(oldCol->GetValue());
868       newCol->SetValue(oldRow->GetValue());
869
870       Archive->Push(newRow);
871       Archive->Push(newCol);
872    }
873
874    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
875    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
876    Archive->Push(libidoCode);
877 }
878
879 /**
880  * \brief Set the Write not to No Libido format
881  */ 
882 void FileHelper::SetWriteToNoLibido()
883 {
884    ValEntry *recCode = dynamic_cast<ValEntry *>
885                 (FileInternal->GetDocEntry(0x0008,0x0010));
886    if( recCode )
887    {
888       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
889       {
890          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
891          libidoCode->SetValue("");
892          Archive->Push(libidoCode);
893       }
894    }
895 }
896
897 /**
898  * \brief Restore the Write format
899  */ 
900 void FileHelper::RestoreWriteOfLibido()
901 {
902    Archive->Restore(0x0028,0x0010);
903    Archive->Restore(0x0028,0x0011);
904    Archive->Restore(0x0008,0x0010);
905 }
906
907 /**
908  * \brief Copy a ValEntry content
909  * @param   group   Group number of the Entry 
910  * @param   elem  Element number of the Entry
911  * \return  pointer to the modified/created Val Entry (NULL when creation
912  *          failed).
913  */ 
914 ValEntry *FileHelper::CopyValEntry(uint16_t group,uint16_t elem)
915 {
916    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
917    ValEntry *newE;
918
919    if( oldE )
920    {
921       newE = new ValEntry(oldE->GetDictEntry());
922       newE->Copy(oldE);
923    }
924    else
925    {
926       newE = GetFile()->NewValEntry(group,elem);
927    }
928
929    return newE;
930 }
931
932 /**
933  * \brief   Modifies the value of a given Bin Entry (Dicom Element)
934  *          when it exists. Create it with the given value when unexistant.
935  * @param   group   Group number of the Entry 
936  * @param   elem  Element number of the Entry
937  * @param   vr  Value Representation of the Entry
938  * \return  pointer to the modified/created Bin Entry (NULL when creation
939  *          failed).
940  */ 
941 BinEntry *FileHelper::CopyBinEntry(uint16_t group,uint16_t elem,
942                                    const std::string &vr)
943 {
944    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
945    BinEntry *newE;
946
947    if( oldE )
948       if( oldE->GetVR()!=vr )
949          oldE = NULL;
950
951    if( oldE )
952    {
953       newE = new BinEntry(oldE->GetDictEntry());
954       newE->Copy(oldE);
955    }
956    else
957    {
958       newE = GetFile()->NewBinEntry(group,elem,vr);
959    }
960
961    return newE;
962 }
963
964 //-----------------------------------------------------------------------------
965 // Private
966 /**
967  * \brief Factorization for various forms of constructors.
968  */
969 void FileHelper::Initialize()
970 {
971    WriteMode = WMODE_RAW;
972    WriteType = ExplicitVR;
973
974    PixelReadConverter = new PixelReadConvert;
975    PixelWriteConverter = new PixelWriteConvert;
976    Archive = new DocEntryArchive( FileInternal );
977
978    if ( FileInternal->IsReadable() )
979    {
980       PixelReadConverter->GrabInformationsFromFile( FileInternal );
981    }
982 }
983
984 /**
985  * \brief   
986  */ 
987 uint8_t *FileHelper::GetRaw()
988 {
989    uint8_t *raw = PixelReadConverter->GetRaw();
990    if ( ! raw )
991    {
992       // The Raw image migth not be loaded yet:
993       std::ifstream *fp = FileInternal->OpenFile();
994       PixelReadConverter->ReadAndDecompressPixelData( fp );
995       if(fp) 
996          FileInternal->CloseFile();
997
998       raw = PixelReadConverter->GetRaw();
999       if ( ! raw )
1000       {
1001          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1002          return 0;
1003       }
1004    }
1005
1006    return raw;
1007 }
1008
1009 //-----------------------------------------------------------------------------
1010 // Print
1011 void FileHelper::Print(std::ostream &os, std::string const &)
1012 {
1013    FileInternal->SetPrintLevel(PrintLevel);
1014    FileInternal->Print(os);
1015
1016    PixelReadConverter->SetPrintLevel(PrintLevel);
1017    PixelReadConverter->Print(os);
1018 }
1019
1020 //-----------------------------------------------------------------------------
1021 } // end namespace gdcm