]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
* gdcmPython/Makefile.am now avoids calling the wrappers for the
[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           
133   // ------------------------------- JPEG LossLess : call to Jpeg Libido
134    
135    if (IsJPEGLossless()) {
136  
137        ClbJpeg* jpg = _IdDcmJpegRead(fp);
138       if(jpg == NULL) {
139          CloseFile();
140          return false;
141       } 
142       // Gros soucis : 
143       //  jpg->DataImg est alloue en int32 systematiquement :
144       //  il faut le copier pixel par pixel dans destination ...
145       //  ... qui est un void *
146       // --> du CAST sportif a faire ... 
147       
148      // memcpy(destination,jpg->DataImg,lgrTotale);
149      
150      // Bon ...
151      // ... y'a p't etre + ruse (?)
152           
153       int nb;
154       string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
155       if (str_nb == "gdcm::Unfound" ) {
156          nb = 16;
157       } else {
158          nb = atoi(str_nb.c_str() );
159          if (nb == 12) nb =16;
160       }
161       int nBytes= nb/8;
162       int * dataJpg = jpg->DataImg;
163       int taille = GetXSize() *  GetYSize() *  GetZSize() * GetSamplesPerPixel();
164           
165       switch (nBytes) {
166       
167          case 1:
168          {
169             unsigned short *dest = (unsigned short *)destination;
170             for (int i=0; i<taille; i++) {
171                if (DEBUG) 
172                   if (*(dataJpg +i) >255) printf("data %d\n",*(dataJpg +i) );
173                *((unsigned char *)dest+i) = *(dataJpg +i);    
174             }
175          }
176          break;        
177          
178          case 2:
179          {
180             unsigned short *dest = (unsigned short *)destination;
181             
182             // etonnant (?)
183             // la ligne commentee ci-dessous fait passer l'exec de 0.15 sec a 5.5 sec
184             // pour la meme image 512*512 ...
185             // optimiseur pas mis en oeuvre (?)
186             //for (int i=0; i<GetXSize() *  GetYSize() *  GetZSize(); i++) 
187             
188              for (int i=0; i<taille; i++) {           
189                *((unsigned short *)dest+i) = *(dataJpg +i);    
190             }
191          }
192          break;
193             
194           case 4:
195           {
196             unsigned int *dest=(unsigned int *)destination;
197             for (int i=0;i<taille; i++) {
198                *((unsigned int *)dest+i) = *(dataJpg +i);    
199             }
200           }
201          break;          
202      }
203       
204       _IdDcmJpegFree (jpg);
205       return true;
206    }  
207  
208   // ------------------------------- JPEG Lossy : call to IJG 6b
209   
210   // TODO : faire qq chose d'intelligent pour limiter 
211   // la duplication du code JPEG <bits=8 / bits=12>
212   // TODO : eplucher icelui pour traiter *egalement* bits=16
213       int nBS;        
214       if  ((nBS = GetBitsStored()) != 12) {
215          printf("Sorry, Bits Stored = %d not yet taken into account\n",nBS);
216          return false;
217       }
218       
219       int res = gdcm_read_JPEG_file (destination);
220          if (DEBUG) 
221             printf ("res : %d\n",res);
222       return res;
223  
224 }   
225
226 /**
227  * \ingroup gdcmFile
228  * \brief   Allocates necessary memory, copies the pixel data
229  *          (image[s]/volume[s]) to newly allocated zone.
230  * @return  Pointer to newly allocated pixel data. 
231  */
232 void * gdcmFile::GetImageData (void) {
233    PixelData = (void *) malloc(lgrTotale);
234    GetImageDataIntoVector(PixelData, lgrTotale);
235    return(PixelData);
236 }
237
238 /**
239  * \ingroup gdcmFile
240  * \brief   Copies at most MaxSize bytes of pixel data to caller's
241  *          memory space.
242  * @param   destination Address (in caller's memory space) at which the
243  *          pixel data should be copied
244  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
245  *          is not sufficient to hold the pixel data the copy is not
246  *          executed (i.e. no partial copy).
247  * @return  On success, the number of bytes actually copied. Zero on
248  *          failure e.g. MaxSize is lower than necessary.
249  */
250
251 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
252
253    int nb, nbu, highBit, signe;
254    string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
255  
256    if ( lgrTotale > MaxSize ) {
257       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
258                      "than caller's expected MaxSize");
259       return (size_t)0; 
260    }
261         
262         (void)ReadPixelData(destination);
263                         
264         // Nombre de Bits Alloues pour le stockage d'un Pixel
265         str_nb = GetPubElValByNumber(0x0028,0x0100);
266         if (str_nb == "gdcm::Unfound" ) {
267                 nb = 16;
268         } else {
269                 nb = atoi(str_nb.c_str() );
270         }
271         
272         // Nombre de Bits Utilises
273         str_nbu=GetPubElValByNumber(0x0028,0x0101);
274         if (str_nbu == "gdcm::Unfound" ) {
275                 nbu = nb;
276         } else {
277                 nbu = atoi(str_nbu.c_str() );
278         }       
279         
280         // Position du Bit de Poids Fort
281         str_highBit=GetPubElValByNumber(0x0028,0x0102);
282         if (str_highBit == "gdcm::Unfound" ) {
283                 highBit = nb - 1;
284         } else {
285                 highBit = atoi(str_highBit.c_str() );
286         }
287                 
288         // Signe des Pixels 
289         str_signe=GetPubElValByNumber(0x0028,0x0103);
290         if (str_signe == "gdcm::Unfound" ) {
291                 signe = 1;
292         } else {
293                 signe = atoi(str_signe.c_str() );
294         }
295
296    // On remet les Octets dans le bon ordre si besoin est
297    if (nb != 8)
298      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
299  
300    // On remet les Bits des Octets dans le bon ordre si besoin est
301    if (nbu != nb){
302       int l = (int)lgrTotale / (nb/8);
303       if (nb == 16) {
304          guint16 mask = 0xffff;
305          mask = mask >> (nb-nbu);
306          guint16 *deb = (guint16 *)destination;
307          for(int i = 0; i<l; i++) {
308             *deb = (*deb >> (nbu-highBit-1)) & mask;
309             deb ++;
310          }
311       } else if (nb == 32 ) {
312          guint32 mask = 0xffffffff;
313          mask = mask >> (nb-nbu);
314          guint32 *deb = (guint32 *)destination;
315          for(int i = 0; i<l; i++) {
316             *deb = (*deb >> (nbu-highBit-1)) & mask;
317             deb ++;
318          }
319       } else {
320          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
321          return (size_t)0; 
322       }
323    }
324    return lgrTotale; 
325 }
326
327
328 //
329 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
330 //
331
332 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
333 guint32 s32;
334 guint16 fort,faible;
335 int i;
336
337 if(nb == 16)
338     
339         switch(swap) {
340                 case 0:
341                 case 12:
342                 case 1234:
343                         break;
344                 
345                 case 21:
346                 case 3412:
347                 case 2143:
348                 case 4321:
349
350                         for(i=0;i<lgr;i++)
351                                 ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
352                                                 | ((((unsigned short int*)im)[i])<<8);
353                         break;
354                         
355                 default:
356                         printf("valeur de SWAP (16 bits) non autorisee : %d\n", swap);
357         } 
358  
359 if( nb == 32 )
360
361         switch (swap) {
362                 case 0:
363                 case 1234:
364                          break;
365
366                 case 4321:
367                          for(i=0;i<lgr;i++) {
368                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
369                                 fort  =((unsigned long int*)im)[i]>>16;
370                                 fort=  (fort>>8)   | (fort<<8);
371                                 faible=(faible>>8) | (faible<<8);
372                                 s32=faible;
373                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
374                         }
375                         break;
376
377                 case 2143:
378                         for(i=0;i<lgr;i++) {
379                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
380                                 fort=((unsigned long int*)im)[i]>>16;
381                                 fort=  (fort>>8)   | (fort<<8);
382                                 faible=(faible>>8) | (faible<<8);
383                                 s32=fort; 
384                                 ((unsigned long int*)im)[i]=(s32<<16)|faible;
385                         }
386                         break;
387   
388                 case 3412:
389                         for(i=0;i<lgr;i++) {
390                                 faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
391                                 fort=((unsigned long int*)im)[i]>>16;                  
392                                 s32=faible; 
393                                 ((unsigned long int*)im)[i]=(s32<<16)|fort;
394                         }                 
395                         break; 
396                                 
397                 default:
398                         printf("valeur de SWAP (32 bits) non autorisee : %d\n", swap);
399         } 
400 return;
401 }
402
403 /////////////////////////////////////////////////////////////////
404 /**
405  * \ingroup   gdcmFile
406  * \brief TODO JPR
407  * \warning doit-etre etre publique ?  FIXME JPR
408  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
409  *
410  * @param inData TODO JPR
411  * @param ExpectedSize TODO JPR
412  *
413  * @return TODO JPR     
414  */
415 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
416    SetImageDataSize(ExpectedSize);
417    PixelData = inData;
418    lgrTotale = ExpectedSize;
419    
420    
421    return(1);
422 }
423
424
425 /////////////////////////////////////////////////////////////////
426 /**
427  * \ingroup   gdcmFile
428  * \brief TODO JPR
429  * \
430  * \warning WARNING doit-etre etre publique ? FIXME JPR
431  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
432  *
433  * @param ImageDataSize TODO JPR
434  *
435  */
436
437 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
438
439         string content1;
440         char car[20];
441         
442         // suppose que le ElValue (0x7fe0, 0x0010) existe ...
443         
444         sprintf(car,"%d",ImageDataSize);
445  
446         gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
447         a->SetLength(ImageDataSize);
448                 
449         ImageDataSize+=8;
450         sprintf(car,"%d",ImageDataSize);
451         content1=car;   
452         SetPubElValByNumber(content1, 0x7fe0, 0x0000);
453 }
454
455
456 /////////////////////////////////////////////////////////////////
457 /**
458  * \ingroup   gdcmFile
459  * \brief Ecrit sur disque les pixels d'UNE image
460  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
461  *        Ca sera à l'utilisateur d'appeler son Reader correctement
462  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
463  *
464  * @param nomFichier TODO JPR
465  *
466  * @return TODO JPR     
467  */
468
469 int gdcmFile::WriteRawData (string nomFichier) {
470
471         FILE * fp1;
472         fp1 = fopen(nomFichier.c_str(),"wb");
473         if (fp1 == NULL) {
474                 printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
475                 return (0);
476         } 
477         
478         fwrite (PixelData,lgrTotale, 1, fp1);
479         fclose (fp1);
480         return(1);
481 }
482
483
484
485 /////////////////////////////////////////////////////////////////
486 /**
487  * \ingroup   gdcmFile
488  * \brief Ecrit sur disque UNE image Dicom
489  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
490  *         Ca fonctionnera correctement (?) sur processeur Intel
491  *         (Equivalent a IdDcmWrite) FIXME JPR 
492  *
493  * @param nomFichier TODO JPR
494  *
495  * @return      TODO JPR
496  */
497
498 int gdcmFile::WriteDcmImplVR (string nomFichier) {
499    return WriteBase(nomFichier, ImplicitVR);
500 }
501
502 /////////////////////////////////////////////////////////////////
503 /**
504  * \ingroup   gdcmFile
505  *
506  * @param  nomFichier TODO JPR
507  *
508  * @return TODO JPR
509  */
510  
511 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
512    return WriteDcmImplVR (string (nomFichier));
513 }
514         
515 /////////////////////////////////////////////////////////////////
516 /**
517  * \ingroup   gdcmFile
518  *
519  * @param  nomFichier TODO JPR
520  *
521  * @return TODO JPR
522  */
523
524 int gdcmFile::WriteDcmExplVR (string nomFichier) {
525    return WriteBase(nomFichier, ExplicitVR);
526 }
527         
528 /////////////////////////////////////////////////////////////////
529 /**
530  * \ingroup   gdcmFile
531  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
532  *        (a l'attention des logiciels cliniques 
533  *        qui ne prennent en entrée QUE des images ACR ...
534  * \warning si un header DICOM est fourni en entree,
535  *        les groupes < 0x0008 et les groupes impairs sont ignores)
536  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
537  *        Ca fonctionnera correctement (?) sur processeur Intel
538  *        (Equivalent a IdDcmWrite) 
539  *
540  * @param nomFichier TODO JPR
541  *
542  * @return TODO JPR     
543  */
544
545 int gdcmFile::WriteAcr (string nomFichier) {
546    return WriteBase(nomFichier, ACR);
547 }
548
549 /////////////////////////////////////////////////////////////////
550 /**
551  * \ingroup   gdcmFile
552  *
553  * @param  FileName TODO JPR
554  * @param  type TODO JPR
555  *
556  * @return TODO JPR
557  */
558 int gdcmFile::WriteBase (string FileName, FileType type) {
559
560    FILE * fp1;
561    fp1 = fopen(FileName.c_str(),"wb");
562    if (fp1 == NULL) {
563       printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
564       return (0);
565    }
566
567    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
568       char * filePreamble;
569       // Ecriture Dicom File Preamble
570       filePreamble=(char*)calloc(128,1);
571       fwrite(filePreamble,128,1,fp1);
572       fwrite("DICM",4,1,fp1);
573    }
574
575    gdcmHeader::Write(fp1, type);
576    fwrite(PixelData, lgrTotale, 1, fp1);
577    fclose (fp1);
578    return(1);
579 }