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