]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
* src/gdcmFile.cxx : bug fix under Window after JPR commit
[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       bool res = (bool)gdcm_read_JPEG_file (destination);
200       return res;
201 }   
202
203 /**
204  * \ingroup gdcmFile
205  * \brief   Allocates necessary memory, copies the pixel data
206  *          (image[s]/volume[s]) to newly allocated zone.
207  * @return  Pointer to newly allocated pixel data. 
208  */
209 void * gdcmFile::GetImageData (void) {
210    PixelData = (void *) malloc(lgrTotale);
211    GetImageDataIntoVector(PixelData, lgrTotale);
212    return(PixelData);
213 }
214
215 /**
216  * \ingroup gdcmFile
217  * \brief   Copies at most MaxSize bytes of pixel data to caller's
218  *          memory space.
219  * @param   destination Address (in caller's memory space) at which the
220  *          pixel data should be copied
221  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
222  *          is not sufficient to hold the pixel data the copy is not
223  *          executed (i.e. no partial copy).
224  * @return  On success, the number of bytes actually copied. Zero on
225  *          failure e.g. MaxSize is lower than necessary.
226  */
227
228 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
229
230    int nb, nbu, highBit, signe;
231    string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
232  
233    if ( lgrTotale > MaxSize ) {
234       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
235                      "than caller's expected MaxSize");
236       return (size_t)0; 
237    }
238         
239         (void)ReadPixelData(destination);
240                         
241         // Nombre de Bits Alloues pour le stockage d'un Pixel
242         str_nb = GetPubElValByNumber(0x0028,0x0100);
243         if (str_nb == "gdcm::Unfound" ) {
244                 nb = 16;
245         } else {
246                 nb = atoi(str_nb.c_str() );
247         }
248         
249         // Nombre de Bits Utilises
250         str_nbu=GetPubElValByNumber(0x0028,0x0101);
251         if (str_nbu == "gdcm::Unfound" ) {
252                 nbu = nb;
253         } else {
254                 nbu = atoi(str_nbu.c_str() );
255         }       
256         
257         // Position du Bit de Poids Fort
258         str_highBit=GetPubElValByNumber(0x0028,0x0102);
259         if (str_highBit == "gdcm::Unfound" ) {
260                 highBit = nb - 1;
261         } else {
262                 highBit = atoi(str_highBit.c_str() );
263         }
264                 
265         // Signe des Pixels 
266         str_signe=GetPubElValByNumber(0x0028,0x0103);
267         if (str_signe == "gdcm::Unfound" ) {
268                 signe = 1;
269         } else {
270                 signe = atoi(str_signe.c_str() );
271         }
272
273    // On remet les Octets dans le bon ordre si besoin est
274    if (nb != 8)
275      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
276  
277    // On remet les Bits des Octets dans le bon ordre si besoin est
278    if (nbu != nb){
279       int l = (int)lgrTotale / (nb/8);
280       if (nb == 16) {
281          guint16 mask = 0xffff;
282          mask = mask >> (nb-nbu);
283          guint16 *deb = (guint16 *)destination;
284          for(int i = 0; i<l; i++) {
285             *deb = (*deb >> (nbu-highBit-1)) & mask;
286             deb ++;
287          }
288       } else if (nb == 32 ) {
289          guint32 mask = 0xffffffff;
290          mask = mask >> (nb-nbu);
291          guint32 *deb = (guint32 *)destination;
292          for(int i = 0; i<l; i++) {
293             *deb = (*deb >> (nbu-highBit-1)) & mask;
294             deb ++;
295          }
296       } else {
297          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
298          return (size_t)0; 
299       }
300    }
301    
302  // ---
303    string str_PlanarConfiguration = GetPubElValByNumber(0x0028,0x0006);
304    int PlanarConfiguration;
305    if (str_PlanarConfiguration == "gdcm::Unfound" ) {
306       PlanarConfiguration = 0;
307    } else {
308       PlanarConfiguration = atoi(str_PlanarConfiguration.c_str() );
309    }   
310  // ---
311  
312    // TODO : replace by                  
313    // if (GetPlanarConfiguration() == 1) {
314    // after unfreeze
315    
316    if (PlanarConfiguration == 1) { // need to make RGB Pixels
317       int l = lgrTotale/3 ;
318
319       char * a = (char *)destination;
320       char * b = a + l;
321       char * c = b + l;
322       char * newDest = (char*) malloc(lgrTotale);
323       // TODO :
324       // any trick not to have to allocate temporary buffer is welcome ...
325       char *x = newDest;
326       for (int j=0;j<l; j++) {
327          *(x++) = *(a++);
328          *(x++) = *(b++);
329          *(x++) = *(c++);  
330       }
331       a = (char *)destination;
332       x = newDest;
333       for (int i=0;i<lgrTotale; i++) {
334          *(a++) = *(x++);
335       }
336       free(newDest);
337    }
338    return lgrTotale; 
339 }
340
341
342 //
343 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
344 //
345
346 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
347 guint32 s32;
348 guint16 fort,faible;
349 int i;
350
351 if(nb == 16)  
352    switch(swap) {
353       case 0:
354       case 12:
355       case 1234:
356          break;
357                 
358       case 21:
359       case 3412:
360       case 2143:
361       case 4321:
362
363          for(i=0;i<lgr;i++)
364             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
365                                         | ((((unsigned short int*)im)[i])<<8);
366          break;
367                         
368       default:
369          printf("valeur de SWAP (16 bits) non autorisee : %d\n", swap);
370    } 
371  
372 if( nb == 32 )
373    switch (swap) {
374       case 0:
375       case 1234:
376          break;
377
378       case 4321:
379          for(i=0;i<lgr;i++) {
380             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
381             fort  =((unsigned long int*)im)[i]>>16;
382             fort=  (fort>>8)   | (fort<<8);
383             faible=(faible>>8) | (faible<<8);
384             s32=faible;
385             ((unsigned long int*)im)[i]=(s32<<16)|fort;
386          }
387          break;
388
389       case 2143:
390          for(i=0;i<lgr;i++) {
391             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
392             fort=((unsigned long int*)im)[i]>>16;
393             fort=  (fort>>8)   | (fort<<8);
394             faible=(faible>>8) | (faible<<8);
395             s32=fort; 
396             ((unsigned long int*)im)[i]=(s32<<16)|faible;
397          }
398          break;
399   
400       case 3412:
401          for(i=0;i<lgr;i++) {
402             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
403             fort=((unsigned long int*)im)[i]>>16;                  
404             s32=faible; 
405             ((unsigned long int*)im)[i]=(s32<<16)|fort;
406          }                 
407          break; 
408                                 
409       default:
410          printf("valeur de SWAP (32 bits) non autorisee : %d\n", swap);
411    } 
412 return;
413 }
414
415 /////////////////////////////////////////////////////////////////
416 /**
417  * \ingroup   gdcmFile
418  * \brief TODO JPR
419  * \warning doit-etre etre publique ?  FIXME JPR
420  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
421  *
422  * @param inData TODO JPR
423  * @param ExpectedSize TODO JPR
424  *
425  * @return TODO JPR     
426  */
427 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
428    SetImageDataSize(ExpectedSize);
429    PixelData = inData;
430    lgrTotale = ExpectedSize;
431    return(1);
432 }
433
434
435 /////////////////////////////////////////////////////////////////
436 /**
437  * \ingroup   gdcmFile
438  * \brief TODO JPR
439  * \
440  * \warning WARNING doit-etre etre publique ? FIXME JPR
441  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
442  *
443  * @param ImageDataSize TODO JPR
444  *
445  */
446
447 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
448
449    string content1;
450    char car[20];
451         
452    // suppose que le ElValue (0x7fe0, 0x0010) existe ...
453         
454    sprintf(car,"%d",ImageDataSize);
455  
456    gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
457    a->SetLength(ImageDataSize);
458                 
459    ImageDataSize+=8;
460    sprintf(car,"%d",ImageDataSize);
461    content1=car;        
462    SetPubElValByNumber(content1, 0x7fe0, 0x0000);
463 }
464
465
466 /////////////////////////////////////////////////////////////////
467 /**
468  * \ingroup   gdcmFile
469  * \brief Ecrit sur disque les pixels d'UNE image
470  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
471  *        Ca sera à l'utilisateur d'appeler son Reader correctement
472  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
473  *
474  * @param nomFichier TODO JPR
475  *
476  * @return TODO JPR     
477  */
478
479 int gdcmFile::WriteRawData (string nomFichier) {
480
481    FILE * fp1;
482    fp1 = fopen(nomFichier.c_str(),"wb");
483    if (fp1 == NULL) {
484       printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
485       return (0);
486    } 
487         
488    fwrite (PixelData,lgrTotale, 1, fp1);
489    fclose (fp1);
490    return(1);
491 }
492
493
494
495 /////////////////////////////////////////////////////////////////
496 /**
497  * \ingroup   gdcmFile
498  * \brief Ecrit sur disque UNE image Dicom
499  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
500  *         Ca fonctionnera correctement (?) sur processeur Intel
501  *         (Equivalent a IdDcmWrite) FIXME JPR 
502  *
503  * @param nomFichier TODO JPR
504  *
505  * @return      TODO JPR
506  */
507
508 int gdcmFile::WriteDcmImplVR (string nomFichier) {
509    return WriteBase(nomFichier, ImplicitVR);
510 }
511
512 /////////////////////////////////////////////////////////////////
513 /**
514  * \ingroup   gdcmFile
515  *
516  * @param  nomFichier TODO JPR
517  *
518  * @return TODO JPR
519  */
520  
521 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
522    return WriteDcmImplVR (string (nomFichier));
523 }
524         
525 /////////////////////////////////////////////////////////////////
526 /**
527  * \ingroup   gdcmFile
528  *
529  * @param  nomFichier TODO JPR
530  *
531  * @return TODO JPR
532  */
533
534 int gdcmFile::WriteDcmExplVR (string nomFichier) {
535    return WriteBase(nomFichier, ExplicitVR);
536 }
537         
538 /////////////////////////////////////////////////////////////////
539 /**
540  * \ingroup   gdcmFile
541  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
542  *        (a l'attention des logiciels cliniques 
543  *        qui ne prennent en entrée QUE des images ACR ...
544  * \warning si un header DICOM est fourni en entree,
545  *        les groupes < 0x0008 et les groupes impairs sont ignores)
546  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
547  *        Ca fonctionnera correctement (?) sur processeur Intel
548  *        (Equivalent a IdDcmWrite) 
549  *
550  * @param nomFichier TODO JPR
551  *
552  * @return TODO JPR     
553  */
554
555 int gdcmFile::WriteAcr (string nomFichier) {
556    return WriteBase(nomFichier, ACR);
557 }
558
559 /////////////////////////////////////////////////////////////////
560 /**
561  * \ingroup   gdcmFile
562  *
563  * @param  FileName TODO JPR
564  * @param  type TODO JPR
565  *
566  * @return TODO JPR
567  */
568 int gdcmFile::WriteBase (string FileName, FileType type) {
569
570    FILE * fp1;
571    fp1 = fopen(FileName.c_str(),"wb");
572    if (fp1 == NULL) {
573       printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
574       return (0);
575    }
576
577    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
578       char * filePreamble;
579       // Ecriture Dicom File Preamble
580       filePreamble=(char*)calloc(128,1);
581       fwrite(filePreamble,128,1,fp1);
582       fwrite("DICM",4,1,fp1);
583    }
584
585    gdcmHeader::Write(fp1, type);
586    fwrite(PixelData, lgrTotale, 1, fp1);
587    fclose (fp1);
588    return(1);
589 }