]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Clean up with JPR. Frog
[gdcm.git] / src / gdcmFile.cxx
1 // gdcmFile.cxx
2
3 #include "gdcmFile.h"
4 #include "gdcmUtil.h"
5 #include "iddcmjpeg.h"
6
7 /////////////////////////////////////////////////////////////////
8 /**
9  * \ingroup   gdcmFile
10  * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
11  *        file (see SetFileName, SetDcmTag and Write)
12  *        Opens (in read only and when possible) an existing file and checks
13  *        for DICOM compliance. Returns NULL on failure.
14  * \Note  the in-memory representation of all available tags found in
15  *        the DICOM header is post-poned to first header information access.
16  *        This avoid a double parsing of public part of the header when
17  *        one sets an a posteriori shadow dictionary (efficiency can be
18  *        seen as a side effect).   
19  *
20  * @param filename file to be opened for parsing
21  *
22  * @return      
23  */
24  
25 gdcmFile::gdcmFile(string & filename) 
26         :gdcmHeader(filename.c_str())   
27 {
28    SetPixelDataSizeFromHeader();
29 }
30
31 gdcmFile::gdcmFile(const char * filename) 
32         :gdcmHeader(filename)   
33 {
34    SetPixelDataSizeFromHeader();
35 }
36
37
38 /////////////////////////////////////////////////////////////////
39 /**
40  * \ingroup   gdcmFile
41  * \brief     calcule la longueur (in bytes) A ALLOUER pour recevoir les
42  *        pixels de l'image
43  *              ou DES images dans le cas d'un multiframe
44  *              ATTENTION : il ne s'agit PAS de la longueur du groupe des Pixels        
45  *              (dans le cas d'images compressees, elle n'a pas de sens).
46  *
47  * @return      longueur a allouer 
48  */
49
50 void gdcmFile::SetPixelDataSizeFromHeader(void) {
51    int nb;
52    string str_nb;
53
54    str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
55    if (str_nb == "gdcm::Unfound" ) {
56       nb = 16;
57    } else {
58       nb = atoi(str_nb.c_str() );
59       if (nb == 12) nb =16;
60    }
61    lgrTotale =  GetXSize() *  GetYSize() *  GetZSize() * (nb/8);
62 }
63
64 /**
65  * \ingroup   gdcmFile
66  * \brief     Accessor
67  */
68 size_t gdcmFile::GetImageDataSize(void) {
69    return (lgrTotale);
70 }
71
72
73 /**
74  * \ingroup gdcmFile
75  * \brief   Read pixel data from disk (optionaly decompressing) into the
76  *          caller specified memory location.
77  * @param   destination Where the pixel data should be stored.
78  *
79  */
80 bool gdcmFile::ReadPixelData(void* destination) {
81    if ( !OpenFile())
82       return false;
83    if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
84       CloseFile();
85       return false;
86    }
87    if (IsJPEGLossless()) {
88       destination = _IdDcmJpegRead(fp);
89    } else { 
90       size_t ItemRead = fread(destination, lgrTotale, 1, fp);
91       if ( ItemRead != 1 ) {
92          CloseFile();
93          return false;
94       }
95    }
96    CloseFile();
97    return true;
98 }   
99
100 /////////////////////////////////////////////////////////////////
101 /**
102  * \ingroup gdcmFile
103  * \brief   Allocates necessary memory, copies the pixel data
104  *          (image[s]/volume[s]) to newly allocated zone and return a
105  *          pointer to it:
106  */
107 void * gdcmFile::GetImageData (void) {
108    PixelData = (void *) malloc(lgrTotale);
109    GetImageDataIntoVector(PixelData, lgrTotale);
110    return(PixelData);
111 }
112
113 /////////////////////////////////////////////////////////////////
114 /**
115  * \ingroup   gdcmFile
116  * \brief amene en mémoire dans une zone précisee par l'utilisateur
117  *        les Pixels d'une image 
118  *
119  * @param destination
120  * @param MaxSize
121  *
122  * @return The number of bytes actually copied.
123  */
124
125 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
126
127    int nb, nbu, highBit, signe;
128    string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
129  
130    if ( lgrTotale > MaxSize ) {
131       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
132                      "than caller's expected MaxSize");
133       return (size_t)0; 
134    }
135         
136         (void)ReadPixelData(destination);
137                         
138         // Nombre de Bits Alloues pour le stockage d'un Pixel
139         str_nb = GetPubElValByNumber(0x0028,0x0100);
140         if (str_nb == "gdcm::Unfound" ) {
141                 nb = 16;
142         } else {
143                 nb = atoi(str_nb.c_str() );
144         }
145         
146         // Nombre de Bits Utilises
147         str_nbu=GetPubElValByNumber(0x0028,0x0101);
148         if (str_nbu == "gdcm::Unfound" ) {
149                 nbu = nb;
150         } else {
151                 nbu = atoi(str_nbu.c_str() );
152         }       
153         
154         // Position du Bit de Poids Fort
155         str_highBit=GetPubElValByNumber(0x0028,0x0102);
156         if (str_highBit == "gdcm::Unfound" ) {
157                 highBit = nb - 1;
158         } else {
159                 highBit = atoi(str_highBit.c_str() );
160         }
161                 
162         // Signe des Pixels 
163         str_signe=GetPubElValByNumber(0x0028,0x0103);
164         if (str_signe == "gdcm::Unfound" ) {
165                 signe = 1;
166         } else {
167                 signe = atoi(str_signe.c_str() );
168         }
169
170    // On remet les Octets dans le bon ordre si besoin est
171    if (nb != 8)
172      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
173  
174    // On remet les Bits des Octets dans le bon ordre si besoin est
175    if (nbu != nb){
176       int l = (int)lgrTotale / (nb/8);
177       if (nb == 16) {
178          guint16 mask = 0xffff;
179          mask = mask >> (nb-nbu);
180          guint16 *deb = (guint16 *)destination;
181          for(int i = 0; i<l; i++) {
182             *deb = (*deb >> (nbu-highBit-1)) & mask;
183             deb ++;
184          }
185       } else if (nb == 32 ) {
186          guint32 mask = 0xffffffff;
187          mask = mask >> (nb-nbu);
188          guint32 *deb = (guint32 *)destination;
189          for(int i = 0; i<l; i++) {
190             *deb = (*deb >> (nbu-highBit-1)) & mask;
191             deb ++;
192          }
193       } else {
194          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
195          return (size_t)0; 
196       }
197    }
198    return lgrTotale; 
199 }
200
201
202 //
203 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
204 //
205
206 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
207 guint32 s32;
208 guint16 fort,faible;
209 int i;
210
211 if(nb == 16)
212     
213         switch(swap) {
214                 case 0:
215                 case 12:
216                 case 1234:
217                         break;
218                 
219                 case 21:
220                 case 3412:
221                 case 2143:
222                 case 4321:
223
224                         for(i=0;i<lgr;i++)
225                                 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
226                                                 | ((((unsigned short int*)im)[i])<<8);
227                         break;
228                         
229                 default:
230                         printf("valeur de SWAP (16 bits) non autorisee : %d\n", swap);
231         } 
232  
233 if( nb == 32 )
234
235         switch (swap) {
236                 case 0:
237                 case 1234:
238                          break;
239
240                 case 4321:
241                          for(i=0;i<lgr;i++) {
242                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
243                                 fort  =((unsigned long int*)im)[i]>>16;
244                                 fort=  (fort>>8)   | (fort<<8);
245                                 faible=(faible>>8) | (faible<<8);
246                                 s32=faible;
247                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
248                         }
249                         break;
250
251                 case 2143:
252                         for(i=0;i<lgr;i++) {
253                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
254                                 fort=((unsigned long int*)im)[i]>>16;
255                                 fort=  (fort>>8)   | (fort<<8);
256                                 faible=(faible>>8) | (faible<<8);
257                                 s32=fort; 
258                                 ((unsigned long int*)im)[i]=(s32<<16)|faible;
259                         }
260                         break;
261   
262                 case 3412:
263                         for(i=0;i<lgr;i++) {
264                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
265                                 fort=((unsigned long int*)im)[i]>>16;                  
266                                 s32=faible; 
267                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
268                         }                 
269                         break; 
270                                 
271                 default:
272                         printf("valeur de SWAP (32 bits) non autorisee : %d\n", swap);
273         } 
274 return;
275 }
276
277 /////////////////////////////////////////////////////////////////
278 /**
279  * \ingroup   gdcmFile
280  * \brief TODO JPR
281  * \warning doit-etre etre publique ?  FIXME JPR
282  *
283  * @param Data TODO JPR
284  * @param ExpectedSize TODO JPR
285  *
286  * @return TODO JPR     
287  */
288 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
289    SetImageDataSize(ExpectedSize);
290    PixelData = inData;
291    lgrTotale = ExpectedSize;
292    return(1);
293 }
294
295
296 /////////////////////////////////////////////////////////////////
297 /**
298  * \ingroup   gdcmFile
299  * \brief TODO JPR
300  * \
301  * \warning WARNING doit-etre etre publique ? FIXME JPR
302  *
303  * @param ImageDataSize TODO JPR
304  *
305  */
306
307 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
308
309         string content1;
310         string content2;
311         char car[20];
312         
313         // suppose que le ElValue (0x7fe0, 0x0010) existe ...
314         
315         sprintf(car,"%d",ImageDataSize);
316         content2=car;
317         SetPubElValByNumber(content2, 0x7fe0, 0x0010);
318         
319         ImageDataSize+=8;
320         sprintf(car,"%d",ImageDataSize);
321         content1=car;   
322         SetPubElValByNumber(content1, 0x7fe0, 0x0000);
323 }
324
325
326 /////////////////////////////////////////////////////////////////
327 /**
328  * \ingroup   gdcmFile
329  * \brief Ecrit sur disque les pixels d'UNE image
330  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
331  *        Ca sera à l'utilisateur d'appeler son Reader correctement
332  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
333  *
334  * @param nomFichier TODO JPR
335  *
336  * @return TODO JPR     
337  */
338
339 int gdcmFile::WriteRawData (string nomFichier) {
340
341         FILE * fp1;
342         fp1 = fopen(nomFichier.c_str(),"wb");
343         if (fp1 == NULL) {
344                 printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
345                 return (0);
346         } 
347         
348         fwrite (PixelData,lgrTotale, 1, fp1);
349         fclose (fp1);
350         return(1);
351 }
352
353
354
355 /////////////////////////////////////////////////////////////////
356 /**
357  * \ingroup   gdcmFile
358  * \brief Ecrit sur disque UNE image Dicom
359  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
360  *         Ca fonctionnera correctement (?) sur processeur Intel
361  *         (Equivalent a IdDcmWrite) FIXME JPR 
362  *
363  * @param nomFichier TODO JPR
364  *
365  * @return      TODO JPR
366  */
367
368 int gdcmFile::WriteDcmImplVR (string nomFichier) {
369    return WriteBase(nomFichier, ImplicitVR);
370 }
371
372 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
373    return WriteDcmImplVR (string (nomFichier));
374 }
375         
376 /////////////////////////////////////////////////////////////////
377 /**
378  * \ingroup   gdcmFile
379  *
380  * @param  nomFichier TODO JPR
381  *
382  * @return TODO JPR
383  */
384
385 int gdcmFile::WriteDcmExplVR (string nomFichier) {
386    return WriteBase(nomFichier, ExplicitVR);
387 }
388         
389 /////////////////////////////////////////////////////////////////
390 /**
391  * \ingroup   gdcmFile
392  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
393  *        (a l'attention des logiciels cliniques 
394  *        qui ne prennent en entrée QUE des images ACR ...
395  * \warning si un header DICOM est fourni en entree,
396  *        les groupes < 0x0008 et les groupes impairs sont ignores)
397  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
398  *        Ca fonctionnera correctement (?) sur processeur Intel
399  *        (Equivalent a IdDcmWrite) 
400  *
401  * @param nomFichier TODO JPR
402  *
403  * @return TODO JPR     
404  */
405
406 int gdcmFile::WriteAcr (string nomFichier) {
407    return WriteBase(nomFichier, ACR);
408 }
409
410 int gdcmFile::WriteBase (string nomFichier, FileType type) {
411
412    FILE * fp1;
413    fp1 = fopen(nomFichier.c_str(),"wb");
414    if (fp1 == NULL) {
415       printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
416       return (0);
417    }
418
419    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
420       char * filePreamble;
421       // Ecriture Dicom File Preamble
422       filePreamble=(char*)calloc(128,1);
423       fwrite(filePreamble,128,1,fp1);
424       fwrite("DICM",4,1,fp1);
425    }
426
427    gdcmHeader::Write(fp1, type);
428    fwrite(PixelData, lgrTotale, 1, fp1);
429    fclose (fp1);
430    return(1);
431 }