]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Modif prise en compte jpeg lossless
[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       
84     if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
85       CloseFile();
86       return false;
87    }     
88     
89    if ( !IsDicomV3()                             ||
90         IsImplicitVRLittleEndianTransferSyntax() ||
91         IsExplicitVRLittleEndianTransferSyntax() ||
92         IsExplicitVRBigEndianTransferSyntax()    ||
93         IsDeflatedExplicitVRLittleEndianTransferSyntax() ) { 
94              
95          size_t ItemRead = fread(destination, lgrTotale, 1, fp);
96          if ( ItemRead != 1 ) {
97             CloseFile();
98             return false;
99          } else {
100             CloseFile();
101             return true;
102          }
103    }
104          
105    if (IsJPEGLossless()) {
106       int ln;
107       fseek(fp,4,SEEK_CUR);
108       fread(&ln,4,1,fp); 
109       if(GetSwapCode()) 
110          ln=SwapLong(ln);
111       //if (DEBUG) 
112          printf ("ln %d\n",ln);
113       fseek(fp,ln,SEEK_CUR);
114       fseek(fp,4,SEEK_CUR);
115       fread(&ln,4,1,fp); 
116       if(GetSwapCode()) 
117          ln=SwapLong(ln);
118       //if (DEBUG) 
119          printf ("ln image comprimée %d\n",ln);
120
121       ClbJpeg* jpg = _IdDcmJpegRead(fp);
122       if(jpg == NULL) {
123          CloseFile();
124          return false;
125       }     
126       memcpy(destination,jpg->DataImg,lgrTotale);
127       _IdDcmJpegFree (jpg);
128       CloseFile();
129       return true;
130    }     
131
132     printf ("Sorry, TransfertSyntax not yet taken into account ...\n");
133     CloseFile();
134     return false;
135
136 }   
137
138 /////////////////////////////////////////////////////////////////
139 /**
140  * \ingroup gdcmFile
141  * \brief   Allocates necessary memory, copies the pixel data
142  *          (image[s]/volume[s]) to newly allocated zone and return a
143  *          pointer to it:
144  */
145 void * gdcmFile::GetImageData (void) {
146    PixelData = (void *) malloc(lgrTotale);
147    GetImageDataIntoVector(PixelData, lgrTotale);
148    return(PixelData);
149 }
150
151 /////////////////////////////////////////////////////////////////
152 /**
153  * \ingroup   gdcmFile
154  * \brief amene en mémoire dans une zone précisee par l'utilisateur
155  *        les Pixels d'une image 
156  *
157  * @param destination
158  * @param MaxSize
159  *
160  * @return The number of bytes actually copied.
161  */
162
163 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
164
165    int nb, nbu, highBit, signe;
166    string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
167  
168    if ( lgrTotale > MaxSize ) {
169       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
170                      "than caller's expected MaxSize");
171       return (size_t)0; 
172    }
173         
174         (void)ReadPixelData(destination);
175                         
176         // Nombre de Bits Alloues pour le stockage d'un Pixel
177         str_nb = GetPubElValByNumber(0x0028,0x0100);
178         if (str_nb == "gdcm::Unfound" ) {
179                 nb = 16;
180         } else {
181                 nb = atoi(str_nb.c_str() );
182         }
183         
184         // Nombre de Bits Utilises
185         str_nbu=GetPubElValByNumber(0x0028,0x0101);
186         if (str_nbu == "gdcm::Unfound" ) {
187                 nbu = nb;
188         } else {
189                 nbu = atoi(str_nbu.c_str() );
190         }       
191         
192         // Position du Bit de Poids Fort
193         str_highBit=GetPubElValByNumber(0x0028,0x0102);
194         if (str_highBit == "gdcm::Unfound" ) {
195                 highBit = nb - 1;
196         } else {
197                 highBit = atoi(str_highBit.c_str() );
198         }
199                 
200         // Signe des Pixels 
201         str_signe=GetPubElValByNumber(0x0028,0x0103);
202         if (str_signe == "gdcm::Unfound" ) {
203                 signe = 1;
204         } else {
205                 signe = atoi(str_signe.c_str() );
206         }
207
208    // On remet les Octets dans le bon ordre si besoin est
209    if (nb != 8)
210      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
211  
212    // On remet les Bits des Octets dans le bon ordre si besoin est
213    if (nbu != nb){
214       int l = (int)lgrTotale / (nb/8);
215       if (nb == 16) {
216          guint16 mask = 0xffff;
217          mask = mask >> (nb-nbu);
218          guint16 *deb = (guint16 *)destination;
219          for(int i = 0; i<l; i++) {
220             *deb = (*deb >> (nbu-highBit-1)) & mask;
221             deb ++;
222          }
223       } else if (nb == 32 ) {
224          guint32 mask = 0xffffffff;
225          mask = mask >> (nb-nbu);
226          guint32 *deb = (guint32 *)destination;
227          for(int i = 0; i<l; i++) {
228             *deb = (*deb >> (nbu-highBit-1)) & mask;
229             deb ++;
230          }
231       } else {
232          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
233          return (size_t)0; 
234       }
235    }
236    return lgrTotale; 
237 }
238
239
240 //
241 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
242 //
243
244 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
245 guint32 s32;
246 guint16 fort,faible;
247 int i;
248
249 if(nb == 16)
250     
251         switch(swap) {
252                 case 0:
253                 case 12:
254                 case 1234:
255                         break;
256                 
257                 case 21:
258                 case 3412:
259                 case 2143:
260                 case 4321:
261
262                         for(i=0;i<lgr;i++)
263                                 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
264                                                 | ((((unsigned short int*)im)[i])<<8);
265                         break;
266                         
267                 default:
268                         printf("valeur de SWAP (16 bits) non autorisee : %d\n", swap);
269         } 
270  
271 if( nb == 32 )
272
273         switch (swap) {
274                 case 0:
275                 case 1234:
276                          break;
277
278                 case 4321:
279                          for(i=0;i<lgr;i++) {
280                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
281                                 fort  =((unsigned long int*)im)[i]>>16;
282                                 fort=  (fort>>8)   | (fort<<8);
283                                 faible=(faible>>8) | (faible<<8);
284                                 s32=faible;
285                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
286                         }
287                         break;
288
289                 case 2143:
290                         for(i=0;i<lgr;i++) {
291                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
292                                 fort=((unsigned long int*)im)[i]>>16;
293                                 fort=  (fort>>8)   | (fort<<8);
294                                 faible=(faible>>8) | (faible<<8);
295                                 s32=fort; 
296                                 ((unsigned long int*)im)[i]=(s32<<16)|faible;
297                         }
298                         break;
299   
300                 case 3412:
301                         for(i=0;i<lgr;i++) {
302                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
303                                 fort=((unsigned long int*)im)[i]>>16;                  
304                                 s32=faible; 
305                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
306                         }                 
307                         break; 
308                                 
309                 default:
310                         printf("valeur de SWAP (32 bits) non autorisee : %d\n", swap);
311         } 
312 return;
313 }
314
315 /////////////////////////////////////////////////////////////////
316 /**
317  * \ingroup   gdcmFile
318  * \brief TODO JPR
319  * \warning doit-etre etre publique ?  FIXME JPR
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    return(1);
331 }
332
333
334 /////////////////////////////////////////////////////////////////
335 /**
336  * \ingroup   gdcmFile
337  * \brief TODO JPR
338  * \
339  * \warning WARNING doit-etre etre publique ? FIXME JPR
340  *
341  * @param ImageDataSize TODO JPR
342  *
343  */
344
345 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
346
347         string content1;
348         string content2;
349         char car[20];
350         
351         // suppose que le ElValue (0x7fe0, 0x0010) existe ...
352         
353         sprintf(car,"%d",ImageDataSize);
354         content2=car;
355         SetPubElValByNumber(content2, 0x7fe0, 0x0010);
356         
357         ImageDataSize+=8;
358         sprintf(car,"%d",ImageDataSize);
359         content1=car;   
360         SetPubElValByNumber(content1, 0x7fe0, 0x0000);
361 }
362
363
364 /////////////////////////////////////////////////////////////////
365 /**
366  * \ingroup   gdcmFile
367  * \brief Ecrit sur disque les pixels d'UNE image
368  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
369  *        Ca sera à l'utilisateur d'appeler son Reader correctement
370  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
371  *
372  * @param nomFichier TODO JPR
373  *
374  * @return TODO JPR     
375  */
376
377 int gdcmFile::WriteRawData (string nomFichier) {
378
379         FILE * fp1;
380         fp1 = fopen(nomFichier.c_str(),"wb");
381         if (fp1 == NULL) {
382                 printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
383                 return (0);
384         } 
385         
386         fwrite (PixelData,lgrTotale, 1, fp1);
387         fclose (fp1);
388         return(1);
389 }
390
391
392
393 /////////////////////////////////////////////////////////////////
394 /**
395  * \ingroup   gdcmFile
396  * \brief Ecrit sur disque UNE image Dicom
397  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
398  *         Ca fonctionnera correctement (?) sur processeur Intel
399  *         (Equivalent a IdDcmWrite) FIXME JPR 
400  *
401  * @param nomFichier TODO JPR
402  *
403  * @return      TODO JPR
404  */
405
406 int gdcmFile::WriteDcmImplVR (string nomFichier) {
407    return WriteBase(nomFichier, ImplicitVR);
408 }
409
410 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
411    return WriteDcmImplVR (string (nomFichier));
412 }
413         
414 /////////////////////////////////////////////////////////////////
415 /**
416  * \ingroup   gdcmFile
417  *
418  * @param  nomFichier TODO JPR
419  *
420  * @return TODO JPR
421  */
422
423 int gdcmFile::WriteDcmExplVR (string nomFichier) {
424    return WriteBase(nomFichier, ExplicitVR);
425 }
426         
427 /////////////////////////////////////////////////////////////////
428 /**
429  * \ingroup   gdcmFile
430  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
431  *        (a l'attention des logiciels cliniques 
432  *        qui ne prennent en entrée QUE des images ACR ...
433  * \warning si un header DICOM est fourni en entree,
434  *        les groupes < 0x0008 et les groupes impairs sont ignores)
435  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
436  *        Ca fonctionnera correctement (?) sur processeur Intel
437  *        (Equivalent a IdDcmWrite) 
438  *
439  * @param nomFichier TODO JPR
440  *
441  * @return TODO JPR     
442  */
443
444 int gdcmFile::WriteAcr (string nomFichier) {
445    return WriteBase(nomFichier, ACR);
446 }
447
448 int gdcmFile::WriteBase (string nomFichier, FileType type) {
449
450    FILE * fp1;
451    fp1 = fopen(nomFichier.c_str(),"wb");
452    if (fp1 == NULL) {
453       printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
454       return (0);
455    }
456
457    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
458       char * filePreamble;
459       // Ecriture Dicom File Preamble
460       filePreamble=(char*)calloc(128,1);
461       fwrite(filePreamble,128,1,fp1);
462       fwrite("DICM",4,1,fp1);
463    }
464
465    gdcmHeader::Write(fp1, type);
466    fwrite(PixelData, lgrTotale, 1, fp1);
467    fclose (fp1);
468    return(1);
469 }