]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
* src/gdcmFileHelper.[h|cxx] : now correctly set the VR of the datas when
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/09 16:28:41 $
7   Version:   $Revision: 1.14 $
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("MONOCHROME1 ");
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       BinEntry *pixel = 
688          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
689       pixel->SetValue(GDCM_BINLOADED);
690       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
691       pixel->SetLength(PixelWriteConverter->GetDataSize());
692
693       Archive->Push(photInt);
694       Archive->Push(pixel);
695    }
696 }
697
698 /**
699  * \brief Update the File to write RGB datas  
700  */ 
701 void FileHelper::SetWriteToRGB()
702 {
703    if(FileInternal->GetNumberOfScalarComponents()==3)
704    {
705       PixelReadConverter->BuildRGBImage();
706       
707       ValEntry *spp = CopyValEntry(0x0028,0x0002);
708       spp->SetValue("3 ");
709
710       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
711       planConfig->SetValue("0 ");
712
713       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
714       photInt->SetValue("RGB ");
715
716       if(PixelReadConverter->GetRGB())
717       {
718          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
719                                           PixelReadConverter->GetRGBSize());
720       }
721       else // Raw data
722       {
723          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
724                                           PixelReadConverter->GetRawSize());
725       }
726
727       std::string vr = "OB";
728       if( FileInternal->GetBitsAllocated()>8 )
729          vr = "OW";
730       BinEntry *pixel = 
731          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
732       pixel->SetValue(GDCM_BINLOADED);
733       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
734       pixel->SetLength(PixelWriteConverter->GetDataSize());
735
736       Archive->Push(spp);
737       Archive->Push(planConfig);
738       Archive->Push(photInt);
739       Archive->Push(pixel);
740
741       // Remove any LUT
742       Archive->Push(0x0028,0x1101);
743       Archive->Push(0x0028,0x1102);
744       Archive->Push(0x0028,0x1103);
745       Archive->Push(0x0028,0x1201);
746       Archive->Push(0x0028,0x1202);
747       Archive->Push(0x0028,0x1203);
748
749       // For old ACR-NEMA
750       // Thus, we have a RGB image and the bits allocated = 24 and 
751       // samples per pixels = 1 (in the read file)
752       if(FileInternal->GetBitsAllocated()==24) 
753       {
754          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
755          bitsAlloc->SetValue("8 ");
756
757          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
758          bitsStored->SetValue("8 ");
759
760          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
761          highBit->SetValue("7 ");
762
763          Archive->Push(bitsAlloc);
764          Archive->Push(bitsStored);
765          Archive->Push(highBit);
766       }
767    }
768    else
769    {
770       SetWriteToRaw();
771    }
772 }
773
774 /**
775  * \brief Restore the File write mode  
776  */ 
777 void FileHelper::RestoreWrite()
778 {
779    Archive->Restore(0x0028,0x0002);
780    Archive->Restore(0x0028,0x0004);
781    Archive->Restore(0x0028,0x0006);
782    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
783
784    // For old ACR-NEMA (24 bits problem)
785    Archive->Restore(0x0028,0x0100);
786    Archive->Restore(0x0028,0x0101);
787    Archive->Restore(0x0028,0x0102);
788
789    // For the LUT
790    Archive->Restore(0x0028,0x1101);
791    Archive->Restore(0x0028,0x1102);
792    Archive->Restore(0x0028,0x1103);
793    Archive->Restore(0x0028,0x1201);
794    Archive->Restore(0x0028,0x1202);
795    Archive->Restore(0x0028,0x1203);
796 }
797
798 /**
799  * \brief Set in the File the write type to ACR
800  */ 
801 void FileHelper::SetWriteFileTypeToACR()
802 {
803    Archive->Push(0x0002,0x0010);
804 }
805
806 /**
807  * \brief Set in the File the write type to Explicit VR   
808  */ 
809 void FileHelper::SetWriteFileTypeToExplicitVR()
810 {
811    std::string ts = Util::DicomString( 
812       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
813
814    ValEntry *tss = CopyValEntry(0x0002,0x0010);
815    tss->SetValue(ts);
816
817    Archive->Push(tss);
818 }
819
820 /**
821  * \brief Set in the File the write type to Implicit VR   
822  */ 
823 void FileHelper::SetWriteFileTypeToImplicitVR()
824 {
825    std::string ts = Util::DicomString(
826       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
827
828    ValEntry *tss = CopyValEntry(0x0002,0x0010);
829    tss->SetValue(ts);
830
831    Archive->Push(tss);
832 }
833
834
835 /**
836  * \brief Restore in the File the write type
837  */ 
838 void FileHelper::RestoreWriteFileType()
839 {
840    Archive->Restore(0x0002,0x0010);
841 }
842
843 /**
844  * \brief Set the Write not to Libido format
845  */ 
846 void FileHelper::SetWriteToLibido()
847 {
848    ValEntry *oldRow = dynamic_cast<ValEntry *>
849                 (FileInternal->GetDocEntry(0x0028, 0x0010));
850    ValEntry *oldCol = dynamic_cast<ValEntry *>
851                 (FileInternal->GetDocEntry(0x0028, 0x0011));
852    
853    if( oldRow && oldCol )
854    {
855       std::string rows, columns; 
856
857       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
858       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
859
860       newRow->Copy(oldCol);
861       newCol->Copy(oldRow);
862
863       newRow->SetValue(oldCol->GetValue());
864       newCol->SetValue(oldRow->GetValue());
865
866       Archive->Push(newRow);
867       Archive->Push(newCol);
868    }
869
870    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
871    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
872    Archive->Push(libidoCode);
873 }
874
875 /**
876  * \brief Set the Write not to No Libido format
877  */ 
878 void FileHelper::SetWriteToNoLibido()
879 {
880    ValEntry *recCode = dynamic_cast<ValEntry *>
881                 (FileInternal->GetDocEntry(0x0008,0x0010));
882    if( recCode )
883    {
884       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
885       {
886          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
887          libidoCode->SetValue("");
888          Archive->Push(libidoCode);
889       }
890    }
891 }
892
893 /**
894  * \brief Restore the Write format
895  */ 
896 void FileHelper::RestoreWriteOfLibido()
897 {
898    Archive->Restore(0x0028,0x0010);
899    Archive->Restore(0x0028,0x0011);
900    Archive->Restore(0x0008,0x0010);
901 }
902
903 /**
904  * \brief Copy a ValEntry content
905  * @param   group   Group number of the Entry 
906  * @param   elem  Element number of the Entry
907  * \return  pointer to the modified/created Val Entry (NULL when creation
908  *          failed).
909  */ 
910 ValEntry *FileHelper::CopyValEntry(uint16_t group,uint16_t elem)
911 {
912    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
913    ValEntry *newE;
914
915    if( oldE )
916    {
917       newE = new ValEntry(oldE->GetDictEntry());
918       newE->Copy(oldE);
919    }
920    else
921    {
922       newE = GetFile()->NewValEntry(group,elem);
923    }
924
925    return newE;
926 }
927
928 /**
929  * \brief   Modifies the value of a given Bin Entry (Dicom Element)
930  *          when it exists. Create it with the given value when unexistant.
931  * @param   group   Group number of the Entry 
932  * @param   elem  Element number of the Entry
933  * \return  pointer to the modified/created Bin Entry (NULL when creation
934  *          failed).
935  */ 
936 BinEntry *FileHelper::CopyBinEntry(uint16_t group,uint16_t elem,const std::string &vr)
937 {
938    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
939    BinEntry *newE;
940
941    if( oldE )
942       if( oldE->GetVR()!=vr )
943          oldE = NULL;
944
945    if( oldE )
946    {
947       newE = new BinEntry(oldE->GetDictEntry());
948       newE->Copy(oldE);
949    }
950    else
951    {
952       newE = GetFile()->NewBinEntry(group,elem,vr);
953    }
954
955    return newE;
956 }
957
958 //-----------------------------------------------------------------------------
959 // Private
960 /**
961  * \brief Factorization for various forms of constructors.
962  */
963 void FileHelper::Initialize()
964 {
965    WriteMode = WMODE_RAW;
966    WriteType = ExplicitVR;
967
968    PixelReadConverter = new PixelReadConvert;
969    PixelWriteConverter = new PixelWriteConvert;
970    Archive = new DocEntryArchive( FileInternal );
971
972    if ( FileInternal->IsReadable() )
973    {
974       PixelReadConverter->GrabInformationsFromFile( FileInternal );
975    }
976 }
977
978 /**
979  * \brief   
980  */ 
981 uint8_t *FileHelper::GetRaw()
982 {
983    uint8_t *raw = PixelReadConverter->GetRaw();
984    if ( ! raw )
985    {
986       // The Raw image migth not be loaded yet:
987       std::ifstream *fp = FileInternal->OpenFile();
988       PixelReadConverter->ReadAndDecompressPixelData( fp );
989       if(fp) 
990          FileInternal->CloseFile();
991
992       raw = PixelReadConverter->GetRaw();
993       if ( ! raw )
994       {
995          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
996          return 0;
997       }
998    }
999
1000    return raw;
1001 }
1002
1003 //-----------------------------------------------------------------------------
1004 // Print
1005 void FileHelper::Print(std::ostream &os, std::string const &)
1006 {
1007    FileInternal->SetPrintLevel(PrintLevel);
1008    FileInternal->Print(os);
1009
1010    PixelReadConverter->SetPrintLevel(PrintLevel);
1011    PixelReadConverter->Print(os);
1012 }
1013
1014 //-----------------------------------------------------------------------------
1015 } // end namespace gdcm