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