]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Add protected method : gdcmElValue * GetElValueByNumber(guint16 group, guint16...
[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  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
321  *
322  * @param inData TODO JPR
323  * @param ExpectedSize TODO JPR
324  *
325  * @return TODO JPR     
326  */
327 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
328    SetImageDataSize(ExpectedSize);
329    PixelData = inData;
330    lgrTotale = ExpectedSize;
331    
332    
333    return(1);
334 }
335
336
337 /////////////////////////////////////////////////////////////////
338 /**
339  * \ingroup   gdcmFile
340  * \brief TODO JPR
341  * \
342  * \warning WARNING doit-etre etre publique ? FIXME JPR
343  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
344  *
345  * @param ImageDataSize TODO JPR
346  *
347  */
348
349 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
350
351         string content1;
352         char car[20];
353         
354         // suppose que le ElValue (0x7fe0, 0x0010) existe ...
355         
356         sprintf(car,"%d",ImageDataSize);
357  
358         gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
359         a->SetLength(ImageDataSize);
360                 
361         ImageDataSize+=8;
362         sprintf(car,"%d",ImageDataSize);
363         content1=car;   
364         SetPubElValByNumber(content1, 0x7fe0, 0x0000);
365 }
366
367
368 /////////////////////////////////////////////////////////////////
369 /**
370  * \ingroup   gdcmFile
371  * \brief Ecrit sur disque les pixels d'UNE image
372  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
373  *        Ca sera à l'utilisateur d'appeler son Reader correctement
374  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
375  *
376  * @param nomFichier TODO JPR
377  *
378  * @return TODO JPR     
379  */
380
381 int gdcmFile::WriteRawData (string nomFichier) {
382
383         FILE * fp1;
384         fp1 = fopen(nomFichier.c_str(),"wb");
385         if (fp1 == NULL) {
386                 printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
387                 return (0);
388         } 
389         
390         fwrite (PixelData,lgrTotale, 1, fp1);
391         fclose (fp1);
392         return(1);
393 }
394
395
396
397 /////////////////////////////////////////////////////////////////
398 /**
399  * \ingroup   gdcmFile
400  * \brief Ecrit sur disque UNE image Dicom
401  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
402  *         Ca fonctionnera correctement (?) sur processeur Intel
403  *         (Equivalent a IdDcmWrite) FIXME JPR 
404  *
405  * @param nomFichier TODO JPR
406  *
407  * @return      TODO JPR
408  */
409
410 int gdcmFile::WriteDcmImplVR (string nomFichier) {
411    return WriteBase(nomFichier, ImplicitVR);
412 }
413
414 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
415    return WriteDcmImplVR (string (nomFichier));
416 }
417         
418 /////////////////////////////////////////////////////////////////
419 /**
420  * \ingroup   gdcmFile
421  *
422  * @param  nomFichier TODO JPR
423  *
424  * @return TODO JPR
425  */
426
427 int gdcmFile::WriteDcmExplVR (string nomFichier) {
428    return WriteBase(nomFichier, ExplicitVR);
429 }
430         
431 /////////////////////////////////////////////////////////////////
432 /**
433  * \ingroup   gdcmFile
434  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
435  *        (a l'attention des logiciels cliniques 
436  *        qui ne prennent en entrée QUE des images ACR ...
437  * \warning si un header DICOM est fourni en entree,
438  *        les groupes < 0x0008 et les groupes impairs sont ignores)
439  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
440  *        Ca fonctionnera correctement (?) sur processeur Intel
441  *        (Equivalent a IdDcmWrite) 
442  *
443  * @param nomFichier TODO JPR
444  *
445  * @return TODO JPR     
446  */
447
448 int gdcmFile::WriteAcr (string nomFichier) {
449    return WriteBase(nomFichier, ACR);
450 }
451
452 int gdcmFile::WriteBase (string nomFichier, FileType type) {
453
454    FILE * fp1;
455    fp1 = fopen(nomFichier.c_str(),"wb");
456    if (fp1 == NULL) {
457       printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
458       return (0);
459    }
460
461    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
462       char * filePreamble;
463       // Ecriture Dicom File Preamble
464       filePreamble=(char*)calloc(128,1);
465       fwrite(filePreamble,128,1,fp1);
466       fwrite("DICM",4,1,fp1);
467    }
468
469    gdcmHeader::Write(fp1, type);
470    fwrite(PixelData, lgrTotale, 1, fp1);
471    fclose (fp1);
472    return(1);
473 }