fce65d000346e63cc94030220448a75a80709ea3
[openjpeg.git] / applications / codec / convert.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * Copyright (c) 2006-2007, Parvatha Elangovan
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 #include "opj_config.h"
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38
39 #ifdef HAVE_LIBTIFF
40 #include <tiffio.h>
41 #endif /* HAVE_LIBTIFF */
42
43 #ifdef HAVE_LIBPNG
44 #include <zlib.h>
45 #include <png.h>
46 #endif /* HAVE_LIBPNG */
47
48 #include "openjpeg.h"
49 #include "convert.h"
50
51 /*
52  * Get logarithm of an integer and round downwards.
53  *
54  * log2(a)
55  */
56 static int int_floorlog2(int a) {
57         int l;
58         for (l = 0; a > 1; l++) {
59                 a >>= 1;
60         }
61         return l;
62 }
63
64 /* -->> -->> -->> -->>
65
66   TGA IMAGE FORMAT
67
68  <<-- <<-- <<-- <<-- */
69
70 #ifdef INFORMATION_ONLY
71 /* TGA header definition. */
72 struct tga_header
73 {                           
74     unsigned char   id_length;              /* Image id field length    */
75     unsigned char   colour_map_type;        /* Colour map type          */
76     unsigned char   image_type;             /* Image type               */
77     /*
78     ** Colour map specification
79     */
80     unsigned short  colour_map_index;       /* First entry index        */
81     unsigned short  colour_map_length;      /* Colour map length        */
82     unsigned char   colour_map_entry_size;  /* Colour map entry size    */
83     /*
84     ** Image specification
85     */
86     unsigned short  x_origin;               /* x origin of image        */
87     unsigned short  y_origin;               /* u origin of image        */
88     unsigned short  image_width;            /* Image width              */
89     unsigned short  image_height;           /* Image height             */
90     unsigned char   pixel_depth;            /* Pixel depth              */
91     unsigned char   image_desc;             /* Image descriptor         */
92 };
93 #endif /* INFORMATION_ONLY */
94
95 static unsigned short get_ushort(unsigned short val) {
96
97 #ifdef ORDER_BIGENDIAN
98     return( ((val & 0xff) << 8) + (val >> 8) );
99 #else
100     return( val );
101 #endif
102
103 }
104
105 #define TGA_HEADER_SIZE 18
106
107 int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
108         unsigned int *width, unsigned int *height, int *flip_image)
109 {
110         int palette_size;
111         unsigned char *tga ;
112         unsigned char id_len, cmap_type, image_type;
113         unsigned char pixel_depth, image_desc;
114         unsigned short cmap_index, cmap_len, cmap_entry_size;
115         unsigned short x_origin, y_origin, image_w, image_h;
116
117         if (!bits_per_pixel || !width || !height || !flip_image)
118                 return 0;
119         tga = (unsigned char*)malloc(18);
120
121         if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
122         {
123                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
124             return 0 ;
125         }
126         id_len = (unsigned char)tga[0];
127         cmap_type = (unsigned char)tga[1];
128         image_type = (unsigned char)tga[2];
129         cmap_index = get_ushort(*(unsigned short*)(&tga[3]));
130         cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
131         cmap_entry_size = (unsigned char)tga[7];
132
133
134         x_origin = get_ushort(*(unsigned short*)(&tga[8]));
135         y_origin = get_ushort(*(unsigned short*)(&tga[10]));
136         image_w = get_ushort(*(unsigned short*)(&tga[12]));
137         image_h = get_ushort(*(unsigned short*)(&tga[14]));
138         pixel_depth = (unsigned char)tga[16];
139         image_desc  = (unsigned char)tga[17];
140
141         free(tga);
142
143         *bits_per_pixel = (unsigned int)pixel_depth;
144         *width  = (unsigned int)image_w;
145         *height = (unsigned int)image_h;
146
147         /* Ignore tga identifier, if present ... */
148         if (id_len)
149         {
150                 unsigned char *id = (unsigned char *) malloc(id_len);
151                 if ( !fread(id, id_len, 1, fp) )
152                 {
153                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
154                         free(id);
155                     return 0 ;
156                 }
157                 free(id);  
158         }
159
160         /* Test for compressed formats ... not yet supported ...
161         // Note :-  9 - RLE encoded palettized.
162         //                 10 - RLE encoded RGB. */
163         if (image_type > 8)
164         {
165                 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
166                 return 0 ;
167         }
168
169         *flip_image = !(image_desc & 32);
170
171         /* Palettized formats are not yet supported, skip over the palette, if present ... */
172         palette_size = cmap_len * (cmap_entry_size/8);
173         
174         if (palette_size>0)
175         {
176                 fprintf(stderr, "File contains a palette - not yet supported.");
177                 fseek(fp, palette_size, SEEK_CUR);
178         }
179         return 1;
180 }
181
182 int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
183         opj_bool flip_image)
184 {
185         unsigned short image_w, image_h, us0;
186         unsigned char uc0, image_type;
187         unsigned char pixel_depth, image_desc;
188
189         if (!bits_per_pixel || !width || !height)
190                 return 0;
191
192         pixel_depth = 0;
193
194         if ( bits_per_pixel < 256 )
195                 pixel_depth = (unsigned char)bits_per_pixel;
196         else{
197                 fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
198                 return 0;
199         }
200         uc0 = 0;
201
202         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
203         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
204
205         image_type = 2; /* Uncompressed. */
206         if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
207
208         us0 = 0;
209         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
210         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
211         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
212
213         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
214         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
215
216         image_w = (unsigned short)width;
217         image_h = (unsigned short) height;
218
219         if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
220         if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
221
222         if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
223
224         image_desc = 8; /* 8 bits per component. */
225
226         if (flip_image)
227                 image_desc |= 32;
228         if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
229
230         return 1;
231
232 fails:
233         fputs("\nwrite_tgaheader: write ERROR\n", stderr);
234         return 0;
235 }
236
237 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
238         FILE *f;
239         opj_image_t *image;
240         unsigned int image_width, image_height, pixel_bit_depth;
241         unsigned int x, y;
242         int flip_image=0;
243         opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
244         int numcomps;
245         OPJ_COLOR_SPACE color_space;
246         opj_bool mono ;
247         opj_bool save_alpha;
248         int subsampling_dx, subsampling_dy;
249         int i;  
250
251         f = fopen(filename, "rb");
252         if (!f) {
253                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
254                 return 0;
255         }
256
257         if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
258                 return NULL;
259
260         /* We currently only support 24 & 32 bit tga's ... */
261         if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
262                 return NULL;
263
264         /* initialize image components */   
265         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
266
267         mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
268         save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
269
270         if (mono) {
271                 color_space = CLRSPC_GRAY;
272                 numcomps = save_alpha ? 2 : 1;
273         }       
274         else {
275                 numcomps = save_alpha ? 4 : 3;
276                 color_space = CLRSPC_SRGB;
277         }
278
279         subsampling_dx = parameters->subsampling_dx;
280         subsampling_dy = parameters->subsampling_dy;
281
282         for (i = 0; i < numcomps; i++) {
283                 cmptparm[i].prec = 8;
284                 cmptparm[i].bpp = 8;
285                 cmptparm[i].sgnd = 0;
286                 cmptparm[i].dx = subsampling_dx;
287                 cmptparm[i].dy = subsampling_dy;
288                 cmptparm[i].w = image_width;
289                 cmptparm[i].h = image_height;
290         }
291
292         /* create the image */
293         image = opj_image_create(numcomps, &cmptparm[0], color_space);
294
295         if (!image)
296                 return NULL;
297
298         /* set image offset and reference grid */
299         image->x0 = parameters->image_offset_x0;
300         image->y0 = parameters->image_offset_y0;
301         image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
302         image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
303
304         /* set image data */
305         for (y=0; y < image_height; y++) 
306         {
307                 int index;
308
309                 if (flip_image)
310                         index = (image_height-y-1)*image_width;
311                 else
312                         index = y*image_width;
313
314                 if (numcomps==3)
315                 {
316                         for (x=0;x<image_width;x++) 
317                         {
318                                 unsigned char r,g,b;
319
320                                 if( !fread(&b, 1, 1, f) )
321                                 {
322                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
323                                         opj_image_destroy(image);
324                                     return NULL;
325                                 }
326                                 if ( !fread(&g, 1, 1, f) )
327                                 {
328                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
329                                         opj_image_destroy(image);
330                                     return NULL;
331                                 }
332                                 if ( !fread(&r, 1, 1, f) )
333                                 {
334                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
335                                         opj_image_destroy(image);
336                                     return NULL;
337                                 }
338
339                                 image->comps[0].data[index]=r;
340                                 image->comps[1].data[index]=g;
341                                 image->comps[2].data[index]=b;
342                                 index++;
343                         }
344                 }
345                 else if (numcomps==4)
346                 {
347                         for (x=0;x<image_width;x++) 
348                         {
349                                 unsigned char r,g,b,a;
350                                 if ( !fread(&b, 1, 1, f) )
351                                 {
352                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
353                                         opj_image_destroy(image);
354                                     return NULL;
355                                 }
356                                 if ( !fread(&g, 1, 1, f) )
357                                 {
358                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
359                                         opj_image_destroy(image);
360                                     return NULL;
361                                 }
362                                 if ( !fread(&r, 1, 1, f) )
363                                 {
364                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
365                                         opj_image_destroy(image);
366                                     return NULL;
367                                 }
368                                 if ( !fread(&a, 1, 1, f) )
369                                 {
370                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
371                                         opj_image_destroy(image);
372                                     return NULL;
373                                 }
374
375                                 image->comps[0].data[index]=r;
376                                 image->comps[1].data[index]=g;
377                                 image->comps[2].data[index]=b;
378                                 image->comps[3].data[index]=a;
379                                 index++;
380                         }
381                 }
382                 else {
383                         fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
384                 }
385         }       
386         return image;
387 }
388
389 int imagetotga(opj_image_t * image, const char *outfile) {
390         int width, height, bpp, x, y;
391         opj_bool write_alpha;
392         int i, adjustR, adjustG, adjustB;
393         unsigned int alpha_channel;
394         float r,g,b,a;
395         unsigned char value;
396         float scale;
397         FILE *fdest;
398   size_t res;
399
400         fdest = fopen(outfile, "wb");
401         if (!fdest) {
402                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
403                 return 1;
404         }
405
406         for (i = 0; i < image->numcomps-1; i++) {
407                 if ((image->comps[0].dx != image->comps[i+1].dx) 
408                         ||(image->comps[0].dy != image->comps[i+1].dy) 
409                         ||(image->comps[0].prec != image->comps[i+1].prec))     {
410       fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
411       return 1;
412    }
413         }
414
415         width = image->comps[0].w;
416         height = image->comps[0].h; 
417
418         /* Mono with alpha, or RGB with alpha. */
419         write_alpha = (image->numcomps==2) || (image->numcomps==4);   
420
421         /* Write TGA header  */
422         bpp = write_alpha ? 32 : 24;
423         if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
424                 return 1;
425
426         alpha_channel = image->numcomps-1; 
427
428         scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
429
430         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
431         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
432         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
433
434         for (y=0; y < height; y++) {
435                 unsigned int index=y*width;
436
437                 for (x=0; x < width; x++, index++)      {
438                         r = (float)(image->comps[0].data[index] + adjustR);
439
440                         if (image->numcomps>2) {
441                                 g = (float)(image->comps[1].data[index] + adjustG);
442                                 b = (float)(image->comps[2].data[index] + adjustB);
443                         }
444                         else  {/* Greyscale ... */
445                                 g = r;
446                                 b = r;
447                         }
448
449                         /* TGA format writes BGR ... */
450                         value = (unsigned char)(b*scale);
451                         res = fwrite(&value,1,1,fdest);
452       if( res < 1 ) {
453         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
454         return 1;
455       }
456
457                         value = (unsigned char)(g*scale);
458                         res = fwrite(&value,1,1,fdest);
459       if( res < 1 ) {
460         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
461         return 1;
462       }
463
464                         value = (unsigned char)(r*scale);
465                         res = fwrite(&value,1,1,fdest);
466       if( res < 1 ) {
467         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
468         return 1;
469       }
470
471                         if (write_alpha) {
472                                 a = (float)(image->comps[alpha_channel].data[index]);
473                                 value = (unsigned char)(a*scale);
474                                 res = fwrite(&value,1,1,fdest);
475         if( res < 1 ) {
476           fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
477           return 1;
478         }
479                         }
480                 }
481         }
482
483         return 0;
484 }
485
486 /* -->> -->> -->> -->>
487
488   BMP IMAGE FORMAT
489
490  <<-- <<-- <<-- <<-- */
491
492 /* WORD defines a two byte word */
493 typedef unsigned short int WORD;
494
495 /* DWORD defines a four byte word */
496 typedef unsigned long int DWORD;
497
498 typedef struct {
499   WORD bfType;                  /* 'BM' for Bitmap (19776) */
500   DWORD bfSize;                 /* Size of the file        */
501   WORD bfReserved1;             /* Reserved : 0            */
502   WORD bfReserved2;             /* Reserved : 0            */
503   DWORD bfOffBits;              /* Offset                  */
504 } BITMAPFILEHEADER_t;
505
506 typedef struct {
507   DWORD biSize;                 /* Size of the structure in bytes */
508   DWORD biWidth;                /* Width of the image in pixels */
509   DWORD biHeight;               /* Heigth of the image in pixels */
510   WORD biPlanes;                /* 1 */
511   WORD biBitCount;              /* Number of color bits by pixels */
512   DWORD biCompression;          /* Type of encoding 0: none 1: RLE8 2: RLE4 */
513   DWORD biSizeImage;            /* Size of the image in bytes */
514   DWORD biXpelsPerMeter;        /* Horizontal (X) resolution in pixels/meter */
515   DWORD biYpelsPerMeter;        /* Vertical (Y) resolution in pixels/meter */
516   DWORD biClrUsed;              /* Number of color used in the image (0: ALL) */
517   DWORD biClrImportant;         /* Number of important color (0: ALL) */
518 } BITMAPINFOHEADER_t;
519
520 opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) 
521 {
522         int subsampling_dx = parameters->subsampling_dx;
523         int subsampling_dy = parameters->subsampling_dy;
524
525         int i, numcomps, w, h;
526         OPJ_COLOR_SPACE color_space;
527         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
528         opj_image_t * image = NULL;
529
530         FILE *IN;
531         BITMAPFILEHEADER_t File_h;
532         BITMAPINFOHEADER_t Info_h;
533         unsigned char *RGB;
534         unsigned char *table_R, *table_G, *table_B;
535         unsigned int j, PAD = 0;
536
537         int x, y, index;
538         int gray_scale = 1;
539         int has_color;
540         DWORD W, H;
541   
542         IN = fopen(filename, "rb");
543         if (!IN) 
544    {
545         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
546         return NULL;
547    }
548         
549         File_h.bfType = getc(IN);
550         File_h.bfType = (getc(IN) << 8) + File_h.bfType;
551         
552         if (File_h.bfType != 19778) 
553    {
554         fprintf(stderr,"Error, not a BMP file!\n");
555         fclose(IN);
556         return NULL;
557    }
558                 /* FILE HEADER */
559                 /* ------------- */
560         File_h.bfSize = getc(IN);
561         File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
562         File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
563         File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
564
565         File_h.bfReserved1 = getc(IN);
566         File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
567
568         File_h.bfReserved2 = getc(IN);
569         File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
570
571         File_h.bfOffBits = getc(IN);
572         File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
573         File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
574         File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
575
576                 /* INFO HEADER */
577                 /* ------------- */
578
579         Info_h.biSize = getc(IN);
580         Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
581         Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
582         Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
583
584         if(Info_h.biSize != 40)
585    {
586         fprintf(stderr,"Error, unknown BMP header size %ld\n", Info_h.biSize);
587         fclose(IN);
588         return NULL;
589    }
590         Info_h.biWidth = getc(IN);
591         Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
592         Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
593         Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
594         w = Info_h.biWidth;
595
596         Info_h.biHeight = getc(IN);
597         Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
598         Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
599         Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
600         h = Info_h.biHeight;
601
602         Info_h.biPlanes = getc(IN);
603         Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
604
605         Info_h.biBitCount = getc(IN);
606         Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
607
608         Info_h.biCompression = getc(IN);
609         Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
610         Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
611         Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
612
613         Info_h.biSizeImage = getc(IN);
614         Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
615         Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
616         Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
617
618         Info_h.biXpelsPerMeter = getc(IN);
619         Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
620         Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
621         Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
622
623         Info_h.biYpelsPerMeter = getc(IN);
624         Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
625         Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
626         Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
627
628         Info_h.biClrUsed = getc(IN);
629         Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
630         Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
631         Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
632
633         Info_h.biClrImportant = getc(IN);
634         Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
635         Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
636         Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
637
638                 /* Read the data and store them in the OUT file */
639
640         if (Info_h.biBitCount == 24) 
641    {
642         numcomps = 3;
643         color_space = CLRSPC_SRGB;
644         /* initialize image components */
645         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
646         for(i = 0; i < numcomps; i++) 
647   {
648         cmptparm[i].prec = 8;
649         cmptparm[i].bpp = 8;
650         cmptparm[i].sgnd = 0;
651         cmptparm[i].dx = subsampling_dx;
652         cmptparm[i].dy = subsampling_dy;
653         cmptparm[i].w = w;
654         cmptparm[i].h = h;
655   }
656         /* create the image */
657         image = opj_image_create(numcomps, &cmptparm[0], color_space);
658         if(!image) 
659   {
660         fclose(IN);
661         return NULL;
662   }
663
664         /* set image offset and reference grid */
665         image->x0 = parameters->image_offset_x0;
666         image->y0 = parameters->image_offset_y0;
667         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
668         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
669
670         /* set image data */
671
672         /* Place the cursor at the beginning of the image information */
673         fseek(IN, 0, SEEK_SET);
674         fseek(IN, File_h.bfOffBits, SEEK_SET);
675                         
676         W = Info_h.biWidth;
677         H = Info_h.biHeight;
678
679         /* PAD = 4 - (3 * W) % 4; */
680         /* PAD = (PAD == 4) ? 0 : PAD; */
681         PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
682                         
683         RGB = (unsigned char *) 
684          malloc((3 * W + PAD) * H * sizeof(unsigned char));
685                         
686         if ( fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN) != (3 * W + PAD) * H )
687         {
688                 free(RGB);
689                 opj_image_destroy(image);
690                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
691             return NULL;
692         }
693                         
694         index = 0;
695
696         for(y = 0; y < (int)H; y++) 
697   {
698         unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
699         for(x = 0; x < (int)W; x++) 
700  {
701         unsigned char *pixel = &scanline[3 * x];
702         image->comps[0].data[index] = pixel[2]; /* R */
703         image->comps[1].data[index] = pixel[1]; /* G */
704         image->comps[2].data[index] = pixel[0]; /* B */
705         index++;
706  }
707   }
708         free(RGB);
709    }/* if (Info_h.biBitCount == 24) */ 
710         else 
711         if (Info_h.biBitCount == 8 && Info_h.biCompression == 0)/*RGB */
712    {
713         if(Info_h.biClrUsed == 0) Info_h.biClrUsed = 256;
714         else
715         if(Info_h.biClrUsed > 256) Info_h.biClrUsed = 256;
716
717         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
718         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
719         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
720                 
721         has_color = 0;  
722         for (j = 0; j < Info_h.biClrUsed; j++) 
723   {
724         table_B[j] = (unsigned char)getc(IN);
725         table_G[j] = (unsigned char)getc(IN);
726         table_R[j] = (unsigned char)getc(IN);
727         getc(IN);
728         has_color += 
729          !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
730   }
731         if(has_color) gray_scale = 0;
732                    
733         /* Place the cursor at the beginning of the image information */
734         fseek(IN, 0, SEEK_SET);
735         fseek(IN, File_h.bfOffBits, SEEK_SET);
736                         
737         W = Info_h.biWidth;
738         H = Info_h.biHeight;
739         if (Info_h.biWidth % 2)
740          W++;
741                         
742         numcomps = gray_scale ? 1 : 3;
743         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
744                 /* initialize image components */
745         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
746         for(i = 0; i < numcomps; i++) 
747   {
748         cmptparm[i].prec = 8;
749         cmptparm[i].bpp = 8;
750         cmptparm[i].sgnd = 0;
751         cmptparm[i].dx = subsampling_dx;
752         cmptparm[i].dy = subsampling_dy;
753         cmptparm[i].w = w;
754         cmptparm[i].h = h;
755   }
756         /* create the image */
757         image = opj_image_create(numcomps, &cmptparm[0], color_space);
758         if(!image) 
759   {
760         fclose(IN);
761         free(table_R); free(table_G); free(table_B);
762         return NULL;
763   }
764
765         /* set image offset and reference grid */
766         image->x0 = parameters->image_offset_x0;
767         image->y0 = parameters->image_offset_y0;
768         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
769         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
770
771         /* set image data */
772
773         RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
774                         
775         if ( fread(RGB, sizeof(unsigned char), W * H, IN) != W * H )
776         {
777                 free(table_R);
778                 free(table_G);
779                 free(table_B);
780                 free(RGB);
781                 opj_image_destroy(image);
782                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
783             return NULL;
784         }
785         if (gray_scale) 
786   {
787         index = 0;
788         for (j = 0; j < W * H; j++) 
789  {
790                 if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) 
791            {
792                 image->comps[0].data[index] = 
793                  table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
794                 index++;
795            }
796  }
797
798   } 
799         else 
800   {
801         index = 0;
802         for (j = 0; j < W * H; j++) 
803  {
804                 if ((j % W < W - 1 && Info_h.biWidth % 2) 
805                 || !(Info_h.biWidth % 2)) 
806            {
807                 unsigned char pixel_index = 
808                  RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
809                 image->comps[0].data[index] = table_R[pixel_index];
810                 image->comps[1].data[index] = table_G[pixel_index];
811                 image->comps[2].data[index] = table_B[pixel_index];
812                 index++;
813            }
814  }
815   }
816         free(RGB);
817         free(table_R);
818         free(table_G);
819         free(table_B);
820    }/* RGB8 */ 
821         else 
822         if (Info_h.biBitCount == 8 && Info_h.biCompression == 1)/*RLE8*/
823         {
824                 unsigned char *pix, *beyond;
825                 int *gray, *red, *green, *blue;
826                 unsigned int x, y, max;
827                 int i, c, c1;
828                 unsigned char uc;
829
830                 if (Info_h.biClrUsed == 0)
831                         Info_h.biClrUsed = 256;
832                 else if (Info_h.biClrUsed > 256)
833                         Info_h.biClrUsed = 256;
834
835                 table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
836                 table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
837                 table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
838
839                 has_color = 0;
840                 for (j = 0; j < Info_h.biClrUsed; j++)
841                 {
842                         table_B[j] = (unsigned char)getc(IN);
843                         table_G[j] = (unsigned char)getc(IN);
844                         table_R[j] = (unsigned char)getc(IN);
845                         getc(IN);
846                         has_color += !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
847                 }
848
849                 if (has_color)
850                         gray_scale = 0;
851
852                 numcomps = gray_scale ? 1 : 3;
853                 color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
854                 /* initialize image components */
855                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
856                 for (i = 0; i < numcomps; i++)
857                 {
858                         cmptparm[i].prec = 8;
859                         cmptparm[i].bpp = 8;
860                         cmptparm[i].sgnd = 0;
861                         cmptparm[i].dx = subsampling_dx;
862                         cmptparm[i].dy = subsampling_dy;
863                         cmptparm[i].w = w;
864                         cmptparm[i].h = h;
865                 }
866                 /* create the image */
867                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
868                 if (!image)
869                 {
870                         fclose(IN);
871                         free(table_R);
872                         free(table_G);
873                         free(table_B);
874                         return NULL;
875                 }
876
877                 /* set image offset and reference grid */
878                 image->x0 = parameters->image_offset_x0;
879                 image->y0 = parameters->image_offset_y0;
880                 image->x1 = !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w
881                                 - 1) * subsampling_dx + 1;
882                 image->y1 = !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h
883                                 - 1) * subsampling_dy + 1;
884
885                 /* set image data */
886
887                 /* Place the cursor at the beginning of the image information */
888                 fseek(IN, 0, SEEK_SET);
889                 fseek(IN, File_h.bfOffBits, SEEK_SET);
890
891                 W = Info_h.biWidth;
892                 H = Info_h.biHeight;
893                 RGB = (unsigned char *) calloc(1, W * H * sizeof(unsigned char));
894                 beyond = RGB + W * H;
895                 pix = beyond - W;
896                 x = y = 0;
897
898                 while (y < H)
899                 {
900                         c = getc(IN);
901
902                         if (c)
903                         {
904                                 c1 = getc(IN);
905
906                                 for (i = 0; i < c && x < W && pix < beyond; i++, x++, pix++)
907                                         *pix = (unsigned char)c1;
908                         }
909                         else
910                         {
911                                 c = getc(IN);
912
913                                 if (c == 0x00) /* EOL */
914                                 {
915                                         x = 0;
916                                         ++y;
917                                         pix = RGB + x + (H - y - 1) * W;
918                                 }
919                                 else if (c == 0x01) /* EOP */
920                                         break;
921                                 else if (c == 0x02) /* MOVE by dxdy */
922                                 {
923                                         c = getc(IN);
924                                         x += c;
925                                         c = getc(IN);
926                                         y += c;
927                                         pix = RGB + (H - y - 1) * W + x;
928                                 }
929                                 else /* 03 .. 255 */
930                                 {
931                                         i = 0;
932                                         for (; i < c && x < W && pix < beyond; i++, x++, pix++)
933                                         {
934                                                 c1 = getc(IN);
935                                                 *pix = (unsigned char)c1;
936                                         }
937                                         if (c & 1) /* skip padding byte */
938                                                 getc(IN);
939                                 }
940                         }
941                 }/* while() */
942
943                 if (gray_scale)
944                 {
945                         gray = image->comps[0].data;
946                         pix = RGB;
947                         max = W * H;
948
949                         while (max--)
950                         {
951                                 uc = *pix++;
952
953                                 *gray++ = table_R[uc];
954                         }
955                 }
956                 else
957                 {
958                         /*int *red, *green, *blue;*/
959
960                         red = image->comps[0].data;
961                         green = image->comps[1].data;
962                         blue = image->comps[2].data;
963                         pix = RGB;
964                         max = W * H;
965
966                         while (max--)
967                         {
968                                 uc = *pix++;
969
970                                 *red++ = table_R[uc];
971                                 *green++ = table_G[uc];
972                                 *blue++ = table_B[uc];
973                         }
974                 }
975                 free(RGB);
976                 free(table_R);
977                 free(table_G);
978                 free(table_B);
979         }/* RLE8 */
980         else 
981    {
982         fprintf(stderr, 
983         "Other system than 24 bits/pixels or 8 bits (no RLE coding) "
984                 "is not yet implemented [%d]\n", Info_h.biBitCount);
985    }
986         fclose(IN);
987         return image;
988 }
989
990 int imagetobmp(opj_image_t * image, const char *outfile) {
991         int w, h;
992         int i, pad;
993         FILE *fdest = NULL;
994         int adjustR, adjustG, adjustB;
995
996         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
997                 && image->comps[1].dx == image->comps[2].dx
998                 && image->comps[0].dy == image->comps[1].dy
999                 && image->comps[1].dy == image->comps[2].dy
1000                 && image->comps[0].prec == image->comps[1].prec
1001                 && image->comps[1].prec == image->comps[2].prec) {
1002                 
1003                 /* -->> -->> -->> -->>    
1004                 24 bits color       
1005                 <<-- <<-- <<-- <<-- */
1006             
1007                 fdest = fopen(outfile, "wb");
1008                 if (!fdest) {
1009                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1010                         return 1;
1011                 }
1012             
1013                 w = image->comps[0].w;      
1014                 h = image->comps[0].h;
1015             
1016                 fprintf(fdest, "BM");
1017             
1018                 /* FILE HEADER */
1019                 /* ------------- */
1020                 fprintf(fdest, "%c%c%c%c",
1021                         (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
1022                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
1023                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
1024                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
1025                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1026                 fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
1027             
1028                 /* INFO HEADER   */
1029                 /* ------------- */
1030                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1031                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1032                         (unsigned char) ((w) >> 8) & 0xff,
1033                         (unsigned char) ((w) >> 16) & 0xff,
1034                         (unsigned char) ((w) >> 24) & 0xff);
1035                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1036                         (unsigned char) ((h) >> 8) & 0xff,
1037                         (unsigned char) ((h) >> 16) & 0xff,
1038                         (unsigned char) ((h) >> 24) & 0xff);
1039                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1040                 fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
1041                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1042                 fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
1043                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
1044                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
1045                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
1046                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1047                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1048                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1049                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1050             
1051                 if (image->comps[0].prec > 8) {
1052                         adjustR = image->comps[0].prec - 8;
1053                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1054                 }
1055                 else 
1056                         adjustR = 0;
1057                 if (image->comps[1].prec > 8) {
1058                         adjustG = image->comps[1].prec - 8;
1059                         printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1060                 }
1061                 else 
1062                         adjustG = 0;
1063                 if (image->comps[2].prec > 8) {
1064                         adjustB = image->comps[2].prec - 8;
1065                         printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1066                 }
1067                 else 
1068                         adjustB = 0;
1069
1070                 for (i = 0; i < w * h; i++) {
1071                         unsigned char rc, gc, bc;
1072                         int r, g, b;
1073                                                         
1074                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1075                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1076                         r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1077                         if(r > 255) r = 255; else if(r < 0) r = 0;
1078                         rc = (unsigned char)r;
1079
1080                         g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1081                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1082                         g = ((g >> adjustG)+((g >> (adjustG-1))%2));
1083                         if(g > 255) g = 255; else if(g < 0) g = 0;
1084                         gc = (unsigned char)g;
1085
1086                         b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1087                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1088                         b = ((b >> adjustB)+((b >> (adjustB-1))%2));
1089                         if(b > 255) b = 255; else if(b < 0) b = 0;
1090                         bc = (unsigned char)b;
1091
1092                         fprintf(fdest, "%c%c%c", bc, gc, rc);
1093                         
1094                         if ((i + 1) % w == 0) {
1095                                 for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
1096                                         fprintf(fdest, "%c", 0);
1097                         }
1098                 }
1099                 fclose(fdest);
1100         } else {                        /* Gray-scale */
1101
1102                 /* -->> -->> -->> -->>
1103                 8 bits non code (Gray scale)
1104                 <<-- <<-- <<-- <<-- */
1105
1106                 fdest = fopen(outfile, "wb");
1107                 w = image->comps[0].w;      
1108                 h = image->comps[0].h;
1109             
1110                 fprintf(fdest, "BM");
1111             
1112                 /* FILE HEADER */
1113                 /* ------------- */
1114                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
1115                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
1116                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
1117                         (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
1118                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1119                 fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
1120                         ((54 + 1024) >> 16) & 0xff,
1121                         ((54 + 1024) >> 24) & 0xff);
1122             
1123                 /* INFO HEADER */
1124                 /* ------------- */
1125                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1126                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1127                         (unsigned char) ((w) >> 8) & 0xff,
1128                         (unsigned char) ((w) >> 16) & 0xff,
1129                         (unsigned char) ((w) >> 24) & 0xff);
1130                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1131                         (unsigned char) ((h) >> 8) & 0xff,
1132                         (unsigned char) ((h) >> 16) & 0xff,
1133                         (unsigned char) ((h) >> 24) & 0xff);
1134                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1135                 fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
1136                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1137                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
1138                         (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
1139                         (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
1140                         (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
1141                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1142                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1143                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1144                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1145
1146                 if (image->comps[0].prec > 8) {
1147                         adjustR = image->comps[0].prec - 8;
1148                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1149                 }else 
1150                         adjustR = 0;
1151
1152                 for (i = 0; i < 256; i++) {
1153                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
1154                 }
1155
1156                 for (i = 0; i < w * h; i++) {
1157                         int r;
1158                         
1159                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1160                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1161                         r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1162                         if(r > 255) r = 255; else if(r < 0) r = 0;
1163
1164                         fprintf(fdest, "%c", (unsigned char)r);
1165
1166                         if ((i + 1) % w == 0) {
1167                                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
1168                                         fprintf(fdest, "%c", 0);
1169                         }
1170                 }
1171                 fclose(fdest);
1172         }
1173
1174         return 0;
1175 }
1176
1177 /* -->> -->> -->> -->>
1178
1179 PGX IMAGE FORMAT
1180
1181 <<-- <<-- <<-- <<-- */
1182
1183
1184 unsigned char readuchar(FILE * f)
1185 {
1186   unsigned char c1;
1187   if ( !fread(&c1, 1, 1, f) )
1188   {
1189           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1190           return 0;
1191   }
1192   return c1;
1193 }
1194
1195 unsigned short readushort(FILE * f, int bigendian)
1196 {
1197   unsigned char c1, c2;
1198   if ( !fread(&c1, 1, 1, f) )
1199   {
1200           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1201           return 0;
1202   }
1203   if ( !fread(&c2, 1, 1, f) )
1204   {
1205           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1206           return 0;
1207   }
1208   if (bigendian)
1209     return (c1 << 8) + c2;
1210   else
1211     return (c2 << 8) + c1;
1212 }
1213
1214 unsigned int readuint(FILE * f, int bigendian)
1215 {
1216   unsigned char c1, c2, c3, c4;
1217   if ( !fread(&c1, 1, 1, f) )
1218   {
1219           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1220           return 0;
1221   }
1222   if ( !fread(&c2, 1, 1, f) )
1223   {
1224           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1225           return 0;
1226   }
1227   if ( !fread(&c3, 1, 1, f) )
1228   {
1229           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1230           return 0;
1231   }
1232   if ( !fread(&c4, 1, 1, f) )
1233   {
1234           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1235           return 0;
1236   }
1237   if (bigendian)
1238     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
1239   else
1240     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
1241 }
1242
1243 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
1244         FILE *f = NULL;
1245         int w, h, prec;
1246         int i, numcomps, max;
1247         OPJ_COLOR_SPACE color_space;
1248         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
1249         opj_image_t * image = NULL;
1250
1251         char endian1,endian2,sign;
1252         char signtmp[32];
1253
1254         char temp[32];
1255         int bigendian;
1256         opj_image_comp_t *comp = NULL;
1257
1258         numcomps = 1;
1259         color_space = CLRSPC_GRAY;
1260
1261         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1262
1263         max = 0;
1264
1265         f = fopen(filename, "rb");
1266         if (!f) {
1267           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1268           return NULL;
1269         }
1270
1271         fseek(f, 0, SEEK_SET);
1272         if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
1273                 fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1274                 return NULL;
1275         }
1276
1277         i=0;
1278         sign='+';               
1279         while (signtmp[i]!='\0') {
1280                 if (signtmp[i]=='-') sign='-';
1281                 i++;
1282         }
1283         
1284         fgetc(f);
1285         if (endian1=='M' && endian2=='L') {
1286                 bigendian = 1;
1287         } else if (endian2=='M' && endian1=='L') {
1288                 bigendian = 0;
1289         } else {
1290                 fprintf(stderr, "Bad pgx header, please check input file\n");
1291                 return NULL;
1292         }
1293
1294         /* initialize image component */
1295
1296         cmptparm.x0 = parameters->image_offset_x0;
1297         cmptparm.y0 = parameters->image_offset_y0;
1298         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1299         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1300         
1301         if (sign == '-') {
1302                 cmptparm.sgnd = 1;
1303         } else {
1304                 cmptparm.sgnd = 0;
1305         }
1306         cmptparm.prec = prec;
1307         cmptparm.bpp = prec;
1308         cmptparm.dx = parameters->subsampling_dx;
1309         cmptparm.dy = parameters->subsampling_dy;
1310         
1311         /* create the image */
1312         image = opj_image_create(numcomps, &cmptparm, color_space);
1313         if(!image) {
1314                 fclose(f);
1315                 return NULL;
1316         }
1317         /* set image offset and reference grid */
1318         image->x0 = cmptparm.x0;
1319         image->y0 = cmptparm.x0;
1320         image->x1 = cmptparm.w;
1321         image->y1 = cmptparm.h;
1322
1323         /* set image data */
1324
1325         comp = &image->comps[0];
1326
1327         for (i = 0; i < w * h; i++) {
1328                 int v;
1329                 if (comp->prec <= 8) {
1330                         if (!comp->sgnd) {
1331                                 v = readuchar(f);
1332                         } else {
1333                                 v = (char) readuchar(f);
1334                         }
1335                 } else if (comp->prec <= 16) {
1336                         if (!comp->sgnd) {
1337                                 v = readushort(f, bigendian);
1338                         } else {
1339                                 v = (short) readushort(f, bigendian);
1340                         }
1341                 } else {
1342                         if (!comp->sgnd) {
1343                                 v = readuint(f, bigendian);
1344                         } else {
1345                                 v = (int) readuint(f, bigendian);
1346                         }
1347                 }
1348                 if (v > max)
1349                         max = v;
1350                 comp->data[i] = v;
1351         }
1352         fclose(f);
1353         comp->bpp = int_floorlog2(max) + 1;
1354
1355         return image;
1356 }
1357
1358 int imagetopgx(opj_image_t * image, const char *outfile) {
1359         int w, h;
1360         int i, j, compno;
1361         FILE *fdest = NULL;
1362
1363         for (compno = 0; compno < image->numcomps; compno++) {
1364                 opj_image_comp_t *comp = &image->comps[compno];
1365                 char bname[256]; /* buffer for name */
1366     char *name = bname; /* pointer */
1367     int nbytes = 0;
1368     size_t res;
1369     const size_t olen = strlen(outfile);
1370     const size_t dotpos = olen - 4;
1371     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1372     if( outfile[dotpos] != '.' ) {
1373       /* `pgx` was recognized but there is no dot at expected position */
1374       fprintf(stderr, "ERROR -> Impossible happen." );
1375       return 1;
1376       }
1377     if( total > 256 ) {
1378       name = (char*)malloc(total+1);
1379       }
1380     strncpy(name, outfile, dotpos);
1381                 /*if (image->numcomps > 1) {*/
1382                         sprintf(name+dotpos, "_%d.pgx", compno);
1383                 /*} else {
1384                         strcpy(name+dotpos, ".pgx");
1385                 }*/
1386                 fdest = fopen(name, "wb");
1387                 if (!fdest) {
1388                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1389                         return 1;
1390                 }
1391     /* dont need name anymore */
1392     if( total > 256 ) {
1393       free(name);
1394       }
1395
1396                 w = image->comps[compno].w;
1397                 h = image->comps[compno].h;
1398             
1399                 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
1400                 if (comp->prec <= 8) {
1401                         nbytes = 1;
1402                 } else if (comp->prec <= 16) {
1403                         nbytes = 2;
1404                 } else {
1405                         nbytes = 4;
1406                 }
1407                 for (i = 0; i < w * h; i++) {
1408                         int v = image->comps[compno].data[i];
1409                         for (j = nbytes - 1; j >= 0; j--) {
1410                                 char byte = (char) (v >> (j * 8));
1411                                 res = fwrite(&byte, 1, 1, fdest);
1412         if( res < 1 ) {
1413           fprintf(stderr, "failed to write 1 byte for %s\n", name);
1414           return 1;
1415         }
1416                         }
1417                 }
1418                 fclose(fdest);
1419         }
1420
1421         return 0;
1422 }
1423
1424 /* -->> -->> -->> -->>
1425
1426 PNM IMAGE FORMAT
1427
1428 <<-- <<-- <<-- <<-- */
1429
1430 struct pnm_header
1431 {
1432     int width, height, maxval, depth, format;
1433     char rgb, rgba, gray, graya, bw;
1434     char ok;
1435 };
1436
1437 static char *skip_white(char *s)
1438 {
1439     while(*s)
1440    {
1441     if(*s == '\n' || *s == '\r') return NULL;
1442     if(isspace(*s)) { ++s; continue; }
1443     return s;
1444    }
1445     return NULL;
1446 }
1447
1448 static char *skip_int(char *start, int *out_n)
1449 {
1450     char *s;
1451     char c;
1452
1453     *out_n = 0; s = start;
1454
1455     s = skip_white(start);
1456     if(s == NULL) return NULL;
1457     start = s;
1458
1459     while(*s)
1460    {
1461     if( !isdigit(*s)) break;
1462     ++s;
1463    }
1464     c = *s; *s = 0; *out_n = atoi(start); *s = c;
1465     return s;
1466 }
1467
1468 static char *skip_idf(char *start, char out_idf[256])
1469 {
1470     char *s;
1471     char c;
1472
1473     s = skip_white(start);
1474     if(s == NULL) return NULL;
1475     start = s;
1476
1477     while(*s)
1478    {
1479     if(isalpha(*s) || *s == '_') { ++s; continue; }
1480     break;
1481    }
1482     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
1483     return s;
1484 }
1485
1486 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1487 {
1488     char *s;
1489     int format, have_wh, end, ttype;
1490     char idf[256], type[256];
1491     char line[256];
1492
1493     if (fgets(line, 250, reader) == NULL)
1494     {
1495         fprintf(stderr,"\nWARNING: fgets return a NULL value");
1496         return;
1497     }
1498
1499     if(line[0] != 'P')
1500    {
1501     fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
1502    }
1503     format = atoi(line + 1);
1504     if(format < 1 || format > 7)
1505    {
1506     fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1507     return;
1508    }
1509     ph->format = format;
1510     ttype = end = have_wh = 0;
1511
1512     while(fgets(line, 250, reader))
1513    {
1514     if(*line == '#') continue;
1515
1516     s = line;
1517
1518     if(format == 7)
1519   {
1520     s = skip_idf(s, idf);
1521
1522     if(s == NULL || *s == 0) return;
1523
1524     if(strcmp(idf, "ENDHDR") == 0)
1525  {
1526     end = 1; break;
1527  }
1528     if(strcmp(idf, "WIDTH") == 0)
1529  {
1530     s = skip_int(s, &ph->width);
1531     if(s == NULL || *s == 0) return;
1532
1533     continue;
1534  }
1535     if(strcmp(idf, "HEIGHT") == 0)
1536  {
1537     s = skip_int(s, &ph->height);
1538     if(s == NULL || *s == 0) return;
1539
1540     continue;
1541  }
1542     if(strcmp(idf, "DEPTH") == 0)
1543  {
1544     s = skip_int(s, &ph->depth);
1545     if(s == NULL || *s == 0) return;
1546
1547     continue;
1548  }
1549     if(strcmp(idf, "MAXVAL") == 0)
1550  {
1551     s = skip_int(s, &ph->maxval);
1552     if(s == NULL || *s == 0) return;
1553
1554     continue;
1555  }
1556     if(strcmp(idf, "TUPLTYPE") == 0)
1557  {
1558     s = skip_idf(s, type);
1559     if(s == NULL || *s == 0) return;
1560
1561         if(strcmp(type, "BLACKANDWHITE") == 0)
1562        {
1563         ph->bw = 1; ttype = 1; continue;
1564        }
1565         if(strcmp(type, "GRAYSCALE") == 0)
1566        {
1567         ph->gray = 1; ttype = 1; continue;
1568        }
1569         if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1570        {
1571         ph->graya = 1; ttype = 1; continue;
1572        }
1573         if(strcmp(type, "RGB") == 0)
1574        {
1575         ph->rgb = 1; ttype = 1; continue;
1576        }
1577         if(strcmp(type, "RGB_ALPHA") == 0)
1578        {
1579         ph->rgba = 1; ttype = 1; continue;
1580        }
1581     fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1582     return;
1583  }
1584     fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1585     return;
1586   } /* if(format == 7) */
1587
1588     if( !have_wh)
1589   {
1590     s = skip_int(s, &ph->width);
1591
1592     s = skip_int(s, &ph->height);
1593
1594     have_wh = 1;
1595
1596     if(format == 1 || format == 4) break;
1597
1598     continue;
1599   }
1600     if(format == 2 || format == 3 || format == 5 || format == 6)
1601   {
1602 /* P2, P3, P5, P6: */
1603     s = skip_int(s, &ph->maxval);
1604
1605     if(ph->maxval > 65535) return;
1606   }
1607     break;
1608    }/* while(fgets( ) */
1609     if(format == 2 || format == 3 || format > 4)
1610    {
1611     if(ph->maxval < 1 || ph->maxval > 65535) return;
1612    }
1613     if(ph->width < 1 || ph->height < 1) return;
1614
1615     if(format == 7)
1616    {
1617     if(!end)
1618   {
1619     fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1620   }
1621     if(ph->depth < 1 || ph->depth > 4) return;
1622
1623     if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
1624      ph->ok = 1;
1625    }
1626     else
1627    {
1628     if(format != 1 && format != 4)
1629   {
1630     if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1631   }
1632     else
1633   {
1634     if(ph->width && ph->height) ph->ok = 1;
1635     ph->maxval = 255;
1636   }
1637    }
1638 }
1639
1640 static int has_prec(int val)
1641 {
1642     if(val < 2) return 1;
1643     if(val < 4) return 2;
1644     if(val < 8) return 3;
1645     if(val < 16) return 4;
1646     if(val < 32) return 5;
1647     if(val < 64) return 6;
1648     if(val < 128) return 7;
1649     if(val < 256) return 8;
1650     if(val < 512) return 9;
1651     if(val < 1024) return 10;
1652     if(val < 2048) return 11;
1653     if(val < 4096) return 12;
1654     if(val < 8192) return 13;
1655     if(val < 16384) return 14;
1656     if(val < 32768) return 15;
1657     return 16;
1658 }
1659
1660 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1661         int subsampling_dx = parameters->subsampling_dx;
1662         int subsampling_dy = parameters->subsampling_dy;
1663
1664         FILE *fp = NULL;
1665         int i, compno, numcomps, w, h, prec, format;
1666         OPJ_COLOR_SPACE color_space;
1667         opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1668         opj_image_t * image = NULL;
1669         struct pnm_header header_info;
1670         
1671         if((fp = fopen(filename, "rb")) == NULL)
1672    {
1673         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1674         return NULL;
1675    }
1676         memset(&header_info, 0, sizeof(struct pnm_header));
1677
1678         read_pnm_header(fp, &header_info);
1679
1680         if(!header_info.ok) { fclose(fp); return NULL; }
1681
1682         format = header_info.format;
1683
1684     switch(format)
1685    {
1686     case 1: /* ascii bitmap */
1687     case 4: /* raw bitmap */
1688         numcomps = 1;
1689         break;
1690
1691     case 2: /* ascii greymap */
1692     case 5: /* raw greymap */
1693         numcomps = 1;
1694         break;
1695
1696     case 3: /* ascii pixmap */
1697     case 6: /* raw pixmap */
1698         numcomps = 3;
1699         break;
1700
1701     case 7: /* arbitrary map */
1702         numcomps = header_info.depth;
1703                 break;
1704
1705     default: fclose(fp); return NULL;
1706    }
1707     if(numcomps < 3)
1708      color_space = CLRSPC_GRAY;/* GRAY, GRAYA */
1709     else
1710      color_space = CLRSPC_SRGB;/* RGB, RGBA */
1711
1712     prec = has_prec(header_info.maxval);
1713
1714         if(prec < 8) prec = 8;
1715
1716     w = header_info.width;
1717     h = header_info.height;
1718     subsampling_dx = parameters->subsampling_dx;
1719     subsampling_dy = parameters->subsampling_dy;
1720
1721     memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1722
1723     for(i = 0; i < numcomps; i++)
1724    {
1725     cmptparm[i].prec = prec;
1726     cmptparm[i].bpp = prec;
1727     cmptparm[i].sgnd = 0;
1728     cmptparm[i].dx = subsampling_dx;
1729     cmptparm[i].dy = subsampling_dy;
1730     cmptparm[i].w = w;
1731     cmptparm[i].h = h;
1732    }
1733     image = opj_image_create(numcomps, &cmptparm[0], color_space);
1734
1735     if(!image) { fclose(fp); return NULL; }
1736
1737 /* set image offset and reference grid */
1738         image->x0 = parameters->image_offset_x0;
1739         image->y0 = parameters->image_offset_y0;
1740         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1741         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1742
1743     if((format == 2) || (format == 3)) /* ascii pixmap */
1744    {
1745     unsigned int index;
1746
1747     for (i = 0; i < w * h; i++)
1748   {
1749     for(compno = 0; compno < numcomps; compno++)
1750  {
1751         index = 0;
1752     if (fscanf(fp, "%u", &index) != 1)
1753         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1754
1755     image->comps[compno].data[i] = (index * 255)/header_info.maxval;
1756  }
1757   }
1758    }
1759     else
1760     if((format == 5)
1761     || (format == 6)
1762     ||((format == 7)
1763         && (   header_info.gray || header_info.graya
1764             || header_info.rgb || header_info.rgba)))/* binary pixmap */
1765    {
1766     unsigned char c0, c1, one;
1767
1768     one = (prec < 9); 
1769
1770     for (i = 0; i < w * h; i++)
1771   {
1772     for(compno = 0; compno < numcomps; compno++)
1773  {
1774           if ( !fread(&c0, 1, 1, fp) )
1775                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1776         if(one)
1777        {
1778         image->comps[compno].data[i] = c0;
1779        }
1780         else
1781        {
1782           if ( !fread(&c1, 1, 1, fp) )
1783                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1784 /* netpbm: */
1785                 image->comps[compno].data[i] = ((c0<<8) | c1);
1786        }
1787  }
1788   }
1789    }
1790     else
1791     if(format == 1) /* ascii bitmap */
1792    {
1793     for (i = 0; i < w * h; i++)
1794   {
1795     unsigned int index;
1796
1797     if ( fscanf(fp, "%u", &index) != 1)
1798         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1799
1800     image->comps[0].data[i] = (index?0:255);
1801   }
1802    }
1803     else
1804     if(format == 4)
1805    {
1806     int x, y, bit;
1807     unsigned char uc;
1808
1809     i = 0;
1810     for(y = 0; y < h; ++y)
1811   {
1812     bit = -1; uc = 0;
1813
1814     for(x = 0; x < w; ++x)
1815  {
1816         if(bit == -1)
1817        {
1818         bit = 7;
1819         uc = (unsigned char)getc(fp);
1820        }
1821     image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1822     --bit; ++i;
1823  }
1824   }
1825    }
1826         else
1827         if((format == 7 && header_info.bw)) /*MONO*/
1828    {
1829         unsigned char uc;
1830
1831         for(i = 0; i < w * h; ++i)
1832   {
1833           if ( !fread(&uc, 1, 1, fp) )
1834                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1835         image->comps[0].data[i] = (uc & 1)?0:255;
1836   }
1837    }
1838     fclose(fp);
1839
1840     return image;
1841 }/* pnmtoimage() */
1842
1843 int imagetopnm(opj_image_t * image, const char *outfile) 
1844 {
1845         int *red, *green, *blue, *alpha;
1846         int wr, hr, max;
1847         int i, compno, ncomp;
1848         int adjustR, adjustG, adjustB, adjustA;
1849         int fails, two, want_gray, has_alpha, triple;
1850         int prec, v;
1851         FILE *fdest = NULL;
1852         const char *tmp = outfile;
1853         char *destname;
1854
1855     if((prec = image->comps[0].prec) > 16)
1856    {
1857         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1858         "\n\t: refused.\n",__FILE__,__LINE__,prec);
1859         return 1;
1860    }
1861     two = has_alpha = 0; fails = 1;
1862         ncomp = image->numcomps;
1863
1864         while (*tmp) ++tmp; tmp -= 2; 
1865         want_gray = (*tmp == 'g' || *tmp == 'G'); 
1866         ncomp = image->numcomps;
1867
1868         if(want_gray) ncomp = 1;
1869
1870         if (ncomp == 2 /* GRAYA */
1871         || (ncomp > 2 /* RGB, RGBA */
1872                 && image->comps[0].dx == image->comps[1].dx
1873                 && image->comps[1].dx == image->comps[2].dx
1874                 && image->comps[0].dy == image->comps[1].dy
1875                 && image->comps[1].dy == image->comps[2].dy
1876                 && image->comps[0].prec == image->comps[1].prec
1877                 && image->comps[1].prec == image->comps[2].prec
1878            ))
1879    {
1880         fdest = fopen(outfile, "wb");
1881
1882         if (!fdest) 
1883   {
1884         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1885         return fails;
1886   }
1887         two = (prec > 8);
1888         triple = (ncomp > 2);
1889         wr = image->comps[0].w; hr = image->comps[0].h;
1890         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1891
1892     red = image->comps[0].data;
1893
1894         if(triple)
1895   {
1896     green = image->comps[1].data;
1897     blue = image->comps[2].data;
1898   }
1899         else green = blue = NULL;
1900         
1901         if(has_alpha)
1902   {
1903         const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1904
1905         fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1906                 "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1907                 wr, hr, ncomp, max, tt);
1908         alpha = image->comps[ncomp - 1].data;
1909         adjustA = (image->comps[ncomp - 1].sgnd ?
1910          1 << (image->comps[ncomp - 1].prec - 1) : 0);
1911   }
1912         else
1913   {
1914         fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n", 
1915                 opj_version(), wr, hr, max);
1916         alpha = NULL; adjustA = 0;
1917   }
1918     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1919
1920         if(triple)
1921   {
1922     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1923     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1924   }
1925         else adjustG = adjustB = 0;
1926
1927     for(i = 0; i < wr * hr; ++i)
1928   {
1929         if(two)
1930  {
1931         v = *red + adjustR; ++red;
1932 /* netpbm: */
1933         fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1934
1935                 if(triple)
1936            {
1937                 v = *green + adjustG; ++green;
1938 /* netpbm: */
1939                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1940
1941                 v =  *blue + adjustB; ++blue;
1942 /* netpbm: */
1943                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1944
1945            }/* if(triple) */
1946
1947         if(has_alpha)
1948        {
1949         v = *alpha + adjustA; ++alpha;
1950 /* netpbm: */
1951                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1952        }
1953         continue;
1954
1955  }      /* if(two) */
1956
1957 /* prec <= 8: */
1958
1959         fprintf(fdest, "%c", (unsigned char)*red++);
1960         if(triple)
1961          fprintf(fdest, "%c%c",(unsigned char)*green++, (unsigned char)*blue++);
1962
1963         if(has_alpha)
1964          fprintf(fdest, "%c", (unsigned char)*alpha++);
1965
1966   }     /* for(i */
1967
1968         fclose(fdest); return 0;
1969    }
1970
1971 /* YUV or MONO: */
1972
1973         if (image->numcomps > ncomp) 
1974    {
1975         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1976         fprintf(stderr,"           is written to the file\n");
1977    }
1978         destname = (char*)malloc(strlen(outfile) + 8);
1979
1980         for (compno = 0; compno < ncomp; compno++) 
1981    {
1982         if (ncomp > 1) 
1983          sprintf(destname, "%d.%s", compno, outfile);
1984         else
1985          sprintf(destname, "%s", outfile);
1986
1987         fdest = fopen(destname, "wb");
1988         if (!fdest) 
1989   {
1990         fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1991         free(destname);
1992         return 1;
1993   }
1994         wr = image->comps[compno].w; hr = image->comps[compno].h;
1995         prec = image->comps[compno].prec;
1996         max = (1<<prec) - 1;
1997
1998         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n", 
1999                 opj_version(), wr, hr, max);
2000
2001         red = image->comps[compno].data;
2002         adjustR = 
2003         (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
2004
2005     if(prec > 8)
2006   {
2007         for (i = 0; i < wr * hr; i++) 
2008  {
2009         v = *red + adjustR; ++red;
2010 /* netpbm: */
2011         fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2012
2013         if(has_alpha)
2014       {
2015         v = *alpha++;
2016 /* netpbm: */
2017                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2018       }
2019  }/* for(i */
2020   }
2021         else /* prec <= 8 */
2022   {
2023         for(i = 0; i < wr * hr; ++i)
2024  {
2025          fprintf(fdest, "%c", (unsigned char)(*red + adjustR)); ++red;
2026  }
2027   }
2028         fclose(fdest);
2029    } /* for (compno */
2030         free(destname);
2031
2032         return 0;
2033 }/* imagetopnm() */
2034
2035 #ifdef HAVE_LIBTIFF
2036 /* -->> -->> -->> -->>
2037
2038         TIFF IMAGE FORMAT
2039
2040  <<-- <<-- <<-- <<-- */
2041
2042 typedef struct tiff_infoheader{
2043         DWORD tiWidth;  /* Width of Image in pixel*/
2044         DWORD tiHeight; /* Height of Image in pixel */
2045         DWORD tiPhoto;  /* Photometric */
2046         WORD  tiBps;      /* Bits per sample */
2047         WORD  tiSf;               /* Sample Format */
2048         WORD  tiSpp;      /* Sample per pixel 1-bilevel,gray scale , 2- RGB */
2049         WORD  tiPC;         /* Planar config (1-Interleaved, 2-Planarcomp) */
2050 }tiff_infoheader_t;
2051
2052 int imagetotif(opj_image_t * image, const char *outfile) 
2053 {
2054         int width, height, imgsize;
2055         int bps,index,adjust, sgnd;
2056         int ushift, dshift, has_alpha, force16;
2057         TIFF *tif;
2058         tdata_t buf;
2059         tstrip_t strip;
2060         tsize_t strip_size;
2061
2062         ushift = dshift = force16 = has_alpha = 0;
2063         bps = image->comps[0].prec;
2064
2065         if(bps > 8 && bps < 16)
2066    {
2067         ushift = 16 - bps; dshift = bps - ushift;
2068         bps = 16; force16 = 1;
2069    }
2070
2071         if(bps != 8 && bps != 16)
2072    {
2073         fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
2074          bps);
2075         fprintf(stderr,"\tAborting\n");
2076         return 1;
2077    }
2078         tif = TIFFOpen(outfile, "wb");
2079
2080         if (!tif) 
2081    {
2082         fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
2083         return 1;
2084    }
2085         sgnd = image->comps[0].sgnd;
2086         adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
2087
2088         if(image->numcomps >= 3 
2089         && image->comps[0].dx == image->comps[1].dx
2090         && image->comps[1].dx == image->comps[2].dx
2091         && image->comps[0].dy == image->comps[1].dy
2092         && image->comps[1].dy == image->comps[2].dy
2093         && image->comps[0].prec == image->comps[1].prec
2094         && image->comps[1].prec == image->comps[2].prec) 
2095    {
2096         has_alpha = (image->numcomps == 4);
2097
2098         width   = image->comps[0].w;
2099         height  = image->comps[0].h;
2100         imgsize = width * height ;
2101  
2102         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2103         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2104         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
2105         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2106         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2107         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2108         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
2109         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2110         strip_size = TIFFStripSize(tif);
2111         buf = _TIFFmalloc(strip_size);
2112         index=0;
2113
2114         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2115   {
2116         unsigned char *dat8;
2117         tsize_t i, ssize, last_i = 0;
2118   int step, restx;
2119         ssize = TIFFStripSize(tif);
2120         dat8 = (unsigned char*)buf;
2121
2122         if(bps == 8)
2123  {
2124         step = 3 + has_alpha;
2125         restx = step - 1;
2126
2127                 for(i=0; i < ssize - restx; i += step) 
2128            {    
2129                 int r, g, b, a = 0;
2130
2131                 if(index < imgsize)
2132           {
2133                 r = image->comps[0].data[index];
2134                 g = image->comps[1].data[index];
2135                 b = image->comps[2].data[index];
2136                 if(has_alpha) a = image->comps[3].data[index];
2137
2138                 if(sgnd)
2139          {
2140                 r += adjust;
2141                 g += adjust;
2142                 b += adjust;
2143                 if(has_alpha) a += adjust;
2144          }
2145                 dat8[i+0] = r ;
2146                 dat8[i+1] = g ;
2147                 dat8[i+2] = b ;
2148                 if(has_alpha) dat8[i+3] = a;
2149
2150                 index++;
2151                 last_i = i + step;
2152           }
2153                 else
2154                  break;
2155            }/*for(i = 0;)*/
2156
2157                 if(last_i < ssize)
2158            {
2159                 for(i = last_i; i < ssize; i += step) 
2160           { 
2161                 int r, g, b, a = 0;
2162
2163                 if(index < imgsize)
2164          {
2165                 r = image->comps[0].data[index];
2166                 g = image->comps[1].data[index];
2167                 b = image->comps[2].data[index];
2168                 if(has_alpha) a = image->comps[3].data[index];
2169
2170                 if(sgnd)
2171         {
2172                 r += adjust;
2173                 g += adjust;
2174                 b += adjust;
2175                 if(has_alpha) a += adjust;
2176         }
2177                 dat8[i+0] = r ;
2178                 if(i+1 < ssize) dat8[i+1] = g ;  else break;
2179                 if(i+2 < ssize) dat8[i+2] = b ;  else break;
2180                 if(has_alpha)
2181         {
2182                 if(i+3 < ssize) dat8[i+3] = a ;  else break;
2183         }
2184                 index++;
2185          }
2186                 else
2187                  break;
2188           }/*for(i)*/
2189            }/*if(last_i < ssize)*/
2190
2191  }      /*if(bps == 8)*/
2192         else 
2193         if(bps == 16)
2194  {
2195         step = 6 + has_alpha + has_alpha;
2196         restx = step - 1;
2197
2198                 for(i = 0; i < ssize - restx ; i += step) 
2199            {  
2200                 int r, g, b, a = 0;
2201
2202                 if(index < imgsize)
2203           {
2204                 r = image->comps[0].data[index];
2205                 g = image->comps[1].data[index];
2206                 b = image->comps[2].data[index];
2207                 if(has_alpha) a = image->comps[3].data[index];
2208
2209                 if(sgnd)
2210          {
2211                 r += adjust;
2212                 g += adjust;
2213                 b += adjust;
2214                 if(has_alpha) a += adjust;
2215          }
2216                 if(force16) 
2217          { 
2218                 r = (r<<ushift) + (r>>dshift); 
2219                 g = (g<<ushift) + (g>>dshift); 
2220                 b = (b<<ushift) + (b>>dshift); 
2221                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2222          }
2223                 dat8[i+0] =  r;/*LSB*/
2224                 dat8[i+1] = (r >> 8);/*MSB*/
2225                 dat8[i+2] =  g;
2226                 dat8[i+3] = (g >> 8);
2227                 dat8[i+4] =  b;
2228                 dat8[i+5] = (b >> 8);
2229                 if(has_alpha) 
2230          { 
2231                 dat8[i+6] =  a; 
2232                 dat8[i+7] = (a >> 8); 
2233          }
2234                 index++;
2235                 last_i = i + step;
2236           }
2237                 else
2238                  break;
2239            }/*for(i = 0;)*/
2240
2241                 if(last_i < ssize)
2242            {
2243                 for(i = last_i ; i < ssize ; i += step) 
2244           {    
2245                 int r, g, b, a = 0;
2246
2247                 if(index < imgsize)
2248          {
2249                 r = image->comps[0].data[index];
2250                 g = image->comps[1].data[index];
2251                 b = image->comps[2].data[index];
2252                 if(has_alpha) a = image->comps[3].data[index];
2253
2254                 if(sgnd)
2255         {
2256                 r += adjust;
2257                 g += adjust;
2258                 b += adjust;
2259                 if(has_alpha) a += adjust;
2260         }
2261             if(force16)
2262         {
2263             r = (r<<ushift) + (r>>dshift);
2264             g = (g<<ushift) + (g>>dshift);
2265             b = (b<<ushift) + (b>>dshift);
2266             if(has_alpha) a = (a<<ushift) + (a>>dshift);
2267         }
2268                 dat8[i+0] =  r;/*LSB*/
2269                 if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;/*MSB*/
2270                 if(i+2 < ssize) dat8[i+2] =  g;      else break;
2271                 if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
2272                 if(i+4 < ssize) dat8[i+4] =  b;      else break;
2273                 if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
2274
2275                 if(has_alpha)
2276         {
2277                 if(i+6 < ssize) dat8[i+6] = a; else break;
2278                 if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
2279         }
2280                 index++;
2281          }
2282                 else
2283                  break;
2284           }/*for(i)*/
2285            }/*if(last_i < ssize)*/
2286
2287  }/*if(bps == 16)*/
2288         (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2289   }/*for(strip = 0; )*/
2290
2291         _TIFFfree((void*)buf);
2292         TIFFClose(tif);
2293
2294         return 0;
2295    }/*RGB(A)*/
2296
2297         if(image->numcomps == 1 /* GRAY */
2298         || (   image->numcomps == 2 /* GRAY_ALPHA */
2299                 && image->comps[0].dx == image->comps[1].dx
2300                 && image->comps[0].dy == image->comps[1].dy
2301                 && image->comps[0].prec == image->comps[1].prec))
2302    {
2303         int step;
2304
2305         has_alpha = (image->numcomps == 2);
2306
2307         width   = image->comps[0].w;
2308         height  = image->comps[0].h;
2309         imgsize = width * height;
2310
2311 /* Set tags */
2312         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2313         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2314         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
2315         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2316         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2317         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2318         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
2319         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2320
2321 /* Get a buffer for the data */
2322         strip_size = TIFFStripSize(tif);
2323         buf = _TIFFmalloc(strip_size);
2324         index = 0;
2325
2326         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2327   {
2328         unsigned char *dat8;
2329         tsize_t i, ssize = TIFFStripSize(tif);
2330         dat8 = (unsigned char*)buf;
2331
2332         if(bps == 8)
2333  {
2334         step = 1 + has_alpha;
2335
2336                 for(i=0; i < ssize; i += step) 
2337            { 
2338                 if(index < imgsize)
2339           {
2340                 int r, a = 0;
2341
2342                 r = image->comps[0].data[index];
2343                 if(has_alpha) a = image->comps[1].data[index];
2344
2345                 if(sgnd)
2346          {
2347                 r += adjust;
2348                 if(has_alpha) a += adjust;
2349          }
2350                 dat8[i+0] = r;
2351                 if(has_alpha) dat8[i+1] = a;
2352                 index++;
2353          }
2354                 else
2355                  break;
2356           }/*for(i )*/
2357  }/*if(bps == 8*/
2358         else 
2359         if(bps == 16)
2360  {
2361         step = 2 + has_alpha + has_alpha;
2362
2363                 for(i=0; i < ssize; i += step) 
2364            {
2365                 if(index < imgsize)
2366           {
2367                 int r, a = 0;
2368
2369                 r = image->comps[0].data[index];
2370                 if(has_alpha) a = image->comps[1].data[index];
2371
2372                 if(sgnd)
2373          {
2374                 r += adjust;
2375                 if(has_alpha) a += adjust;
2376          }
2377                 if(force16)
2378          {
2379                 r = (r<<ushift) + (r>>dshift);
2380                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2381          }
2382                 dat8[i+0] = r;/*LSB*/
2383                 dat8[i+1] = r >> 8;/*MSB*/
2384                 if(has_alpha)
2385          {
2386                 dat8[i+2] = a;
2387                 dat8[i+3] = a >> 8;
2388          }
2389                 index++;
2390           }/*if(index < imgsize)*/
2391                 else
2392                  break;
2393            }/*for(i )*/
2394  }
2395         (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2396   }/*for(strip*/
2397
2398         _TIFFfree(buf);
2399         TIFFClose(tif);
2400
2401         return 0;
2402    }
2403
2404         TIFFClose(tif);
2405
2406         fprintf(stderr,"imagetotif: Bad color format.\n"
2407          "\tOnly RGB(A) and GRAY(A) has been implemented\n");
2408         fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
2409          image->numcomps);
2410
2411         return 1;
2412 }/* imagetotif() */
2413
2414 /*
2415  * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
2416  * CINEMA                 : 12 bit precision
2417 */
2418 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
2419 {
2420         int subsampling_dx = parameters->subsampling_dx;
2421         int subsampling_dy = parameters->subsampling_dy;
2422         TIFF *tif;
2423         tiff_infoheader_t Info;
2424         tdata_t buf;
2425         tstrip_t strip;
2426         tsize_t strip_size;
2427         int j, numcomps, w, h,index;
2428         OPJ_COLOR_SPACE color_space;
2429         opj_image_cmptparm_t cmptparm[4]; /* RGBA */
2430         opj_image_t *image = NULL;
2431         int imgsize = 0;
2432         int has_alpha = 0;
2433
2434         tif = TIFFOpen(filename, "r");
2435
2436         if(!tif) 
2437    {
2438         fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2439         return 0;
2440    }
2441         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
2442         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
2443         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
2444         TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
2445         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
2446         Info.tiPhoto = 0;
2447         TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
2448         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
2449         w= Info.tiWidth;
2450         h= Info.tiHeight;
2451
2452    {
2453         int b, p;
2454
2455         if((b = Info.tiBps) != 8 && b != 16 && b != 12) b = 0;
2456         if((p = Info.tiPhoto) != 1 && p != 2) p = 0;
2457
2458     if( !b || !p)
2459   {
2460         if( !b)
2461      fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits"
2462       " implemented\n",Info.tiBps);
2463         else
2464         if( !p)
2465      fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2466       " and GRAY(A) has been implemented\n",(int) Info.tiPhoto);
2467
2468     fprintf(stderr,"\tAborting\n");
2469         TIFFClose(tif);
2470
2471     return NULL;
2472   }
2473    }
2474
2475    {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2476         uint16* sampleinfo;
2477         uint16 extrasamples;
2478
2479         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2480          &extrasamples, &sampleinfo);
2481
2482         if(extrasamples >= 1)
2483   {
2484         switch(sampleinfo[0]) 
2485  {
2486         case EXTRASAMPLE_UNSPECIFIED: 
2487 /* Workaround for some images without correct info about alpha channel
2488 */
2489                 if(Info.tiSpp > 3)
2490                  has_alpha = 1;
2491                 break;
2492
2493         case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2494         case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2495                 has_alpha = 1;
2496                 break;
2497  }
2498   }
2499    }
2500 /* initialize image components
2501 */ 
2502         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2503
2504         if(Info.tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2505    {
2506         numcomps = 3 + has_alpha;
2507         color_space = CLRSPC_SRGB;
2508
2509         for(j = 0; j < numcomps; j++) 
2510   {
2511         if(parameters->cp_cinema) 
2512  {
2513         cmptparm[j].prec = 12;
2514         cmptparm[j].bpp = 12;
2515  }
2516         else
2517  {
2518         cmptparm[j].prec = Info.tiBps;
2519         cmptparm[j].bpp = Info.tiBps;
2520  }
2521         cmptparm[j].dx = subsampling_dx;
2522         cmptparm[j].dy = subsampling_dy;
2523         cmptparm[j].w = w;
2524         cmptparm[j].h = h;
2525   }
2526
2527         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2528
2529         if(!image) 
2530   {
2531         TIFFClose(tif);
2532         return NULL;
2533   }
2534 /* set image offset and reference grid 
2535 */
2536         image->x0 = parameters->image_offset_x0;
2537         image->y0 = parameters->image_offset_y0;
2538         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2539                 image->x0 + (w - 1) * subsampling_dx + 1;
2540         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2541                 image->y0 + (h - 1) * subsampling_dy + 1;
2542
2543         buf = _TIFFmalloc(TIFFStripSize(tif));
2544
2545         strip_size=TIFFStripSize(tif);
2546         index = 0;
2547         imgsize = image->comps[0].w * image->comps[0].h ;
2548 /* Read the Image components
2549 */
2550         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2551   {
2552         unsigned char *dat8;
2553         int step;
2554         tsize_t i, ssize;
2555         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2556         dat8 = (unsigned char*)buf;
2557
2558         if(Info.tiBps == 16)
2559  {
2560         step = 6 + has_alpha + has_alpha;
2561
2562                 for(i = 0; i < ssize; i += step) 
2563            {
2564                 if(index < imgsize)
2565           {
2566                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2567                 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2568                 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2569                 if(has_alpha)
2570                  image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2571
2572                 if(parameters->cp_cinema)
2573          {
2574 /* Rounding 16 to 12 bits
2575 */
2576                 image->comps[0].data[index] = 
2577                         (image->comps[0].data[index] + 0x08) >> 4 ;
2578                 image->comps[1].data[index] = 
2579                         (image->comps[1].data[index] + 0x08) >> 4 ;
2580                 image->comps[2].data[index] = 
2581                         (image->comps[2].data[index] + 0x08) >> 4 ;
2582                 if(has_alpha)
2583                  image->comps[3].data[index] =
2584                         (image->comps[3].data[index] + 0x08) >> 4 ;
2585          }
2586                 index++;
2587           }
2588                 else
2589                  break;
2590            }/*for(i = 0)*/
2591  }/*if(Info.tiBps == 16)*/
2592         else 
2593         if(Info.tiBps == 8)
2594  {
2595         step = 3 + has_alpha;
2596
2597                 for(i = 0; i < ssize; i += step) 
2598            {
2599                 if(index < imgsize)
2600           {
2601                 image->comps[0].data[index] = dat8[i+0];/* R */
2602                 image->comps[1].data[index] = dat8[i+1];/* G */
2603                 image->comps[2].data[index] = dat8[i+2];/* B */
2604                 if(has_alpha)
2605                  image->comps[3].data[index] = dat8[i+3];
2606
2607                 if(parameters->cp_cinema)
2608          {
2609 /* Rounding 8 to 12 bits
2610 */
2611                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2612                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2613                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2614                 if(has_alpha)
2615                  image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2616          }
2617                 index++;
2618           }/*if(index*/
2619                 else
2620                  break;
2621            }/*for(i )*/
2622  }/*if( Info.tiBps == 8)*/
2623         else
2624         if(Info.tiBps == 12)/* CINEMA file */
2625  {
2626         step = 9;
2627
2628                 for(i = 0; i < ssize; i += step) 
2629            {
2630                 if((index < imgsize)&(index+1 < imgsize))
2631           {
2632                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
2633                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2634
2635                 image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
2636                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2637
2638                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
2639                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2640
2641                 index += 2;
2642           }
2643                 else
2644                  break;
2645            }/*for(i )*/
2646  }
2647   }/*for(strip = 0; )*/
2648
2649         _TIFFfree(buf);
2650         TIFFClose(tif);
2651
2652         return image;
2653    }/*RGB(A)*/
2654
2655         if(Info.tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2656    {
2657         numcomps = 1 + has_alpha;
2658         color_space = CLRSPC_GRAY;
2659
2660         for(j = 0; j < numcomps; ++j)
2661   {
2662         cmptparm[j].prec = Info.tiBps;
2663         cmptparm[j].bpp = Info.tiBps;
2664         cmptparm[j].dx = subsampling_dx;
2665         cmptparm[j].dy = subsampling_dy;
2666         cmptparm[j].w = w;
2667         cmptparm[j].h = h;
2668   }
2669         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2670
2671         if(!image) 
2672   {
2673         TIFFClose(tif);
2674         return NULL;
2675   }
2676 /* set image offset and reference grid 
2677 */
2678         image->x0 = parameters->image_offset_x0;
2679         image->y0 = parameters->image_offset_y0;
2680         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2681                 image->x0 + (w - 1) * subsampling_dx + 1;
2682         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2683                 image->y0 + (h - 1) * subsampling_dy + 1;
2684
2685         buf = _TIFFmalloc(TIFFStripSize(tif));
2686
2687         strip_size = TIFFStripSize(tif);
2688         index = 0;
2689         imgsize = image->comps[0].w * image->comps[0].h ;
2690 /* Read the Image components
2691 */
2692         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2693   {
2694         unsigned char *dat8;
2695         tsize_t i, ssize;
2696         int step;
2697
2698         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2699         dat8 = (unsigned char*)buf;
2700
2701                 if(Info.tiBps == 16)
2702            {
2703                 step = 2 + has_alpha + has_alpha;
2704
2705                 for(i = 0; i < ssize; i += step) 
2706           {
2707                 if(index < imgsize)
2708          {
2709                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2710                 if(has_alpha)
2711                  image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2712                 index++;
2713          }
2714                 else
2715                  break;
2716           }/*for(i )*/
2717            }
2718                 else 
2719                 if(Info.tiBps == 8)
2720            {
2721                 step = 1 + has_alpha;
2722
2723                 for(i = 0; i < ssize; i += step) 
2724           {
2725                 if(index < imgsize)
2726          {
2727                 image->comps[0].data[index] = dat8[i+0];
2728                 if(has_alpha)
2729                  image->comps[1].data[index] = dat8[i+1];
2730                 index++;
2731          }
2732                 else
2733                  break;
2734           }/*for(i )*/
2735            }
2736   }/*for(strip = 0;*/
2737
2738         _TIFFfree(buf);
2739         TIFFClose(tif);
2740
2741    }/*GRAY(A)*/
2742
2743         return image;
2744
2745 }/* tiftoimage() */
2746
2747 #endif /* HAVE_LIBTIFF */
2748
2749 /* -->> -->> -->> -->>
2750
2751         RAW IMAGE FORMAT
2752
2753  <<-- <<-- <<-- <<-- */
2754
2755 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2756         int subsampling_dx = parameters->subsampling_dx;
2757         int subsampling_dy = parameters->subsampling_dy;
2758
2759         FILE *f = NULL;
2760         int i, compno, numcomps, w, h;
2761         OPJ_COLOR_SPACE color_space;
2762         opj_image_cmptparm_t *cmptparm; 
2763         opj_image_t * image = NULL;
2764         unsigned short ch;
2765         
2766         if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2767         {
2768                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2769                 fprintf(stderr,"Please use the Format option -F:\n");
2770                 fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
2771                 fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
2772                 fprintf(stderr,"Aborting\n");
2773                 return NULL;
2774         }
2775
2776         f = fopen(filename, "rb");
2777         if (!f) {
2778                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2779                 fprintf(stderr,"Aborting\n");
2780                 return NULL;
2781         }
2782         numcomps = raw_cp->rawComp;
2783         color_space = CLRSPC_SRGB;
2784         w = raw_cp->rawWidth;
2785         h = raw_cp->rawHeight;
2786         cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
2787         
2788         /* initialize image components */       
2789         memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
2790         for(i = 0; i < numcomps; i++) {         
2791                 cmptparm[i].prec = raw_cp->rawBitDepth;
2792                 cmptparm[i].bpp = raw_cp->rawBitDepth;
2793                 cmptparm[i].sgnd = raw_cp->rawSigned;
2794                 cmptparm[i].dx = subsampling_dx;
2795                 cmptparm[i].dy = subsampling_dy;
2796                 cmptparm[i].w = w;
2797                 cmptparm[i].h = h;
2798         }
2799         /* create the image */
2800         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2801         if(!image) {
2802                 fclose(f);
2803                 return NULL;
2804         }
2805         /* set image offset and reference grid */
2806         image->x0 = parameters->image_offset_x0;
2807         image->y0 = parameters->image_offset_y0;
2808         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
2809         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
2810
2811         if(raw_cp->rawBitDepth <= 8)
2812         {
2813                 unsigned char value = 0;
2814                 for(compno = 0; compno < numcomps; compno++) {
2815                         for (i = 0; i < w * h; i++) {
2816                                 if (!fread(&value, 1, 1, f)) {
2817                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2818                                         return NULL;
2819                                 }
2820                                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2821                         }
2822                 }
2823         }
2824         else if(raw_cp->rawBitDepth <= 16)
2825         {
2826                 unsigned short value;
2827                 for(compno = 0; compno < numcomps; compno++) {
2828                         for (i = 0; i < w * h; i++) {
2829                                 unsigned char temp;
2830                                 if (!fread(&temp, 1, 1, f)) {
2831                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2832                                         return NULL;
2833                                 }
2834                                 value = temp << 8;
2835                                 if (!fread(&temp, 1, 1, f)) {
2836                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2837                                         return NULL;
2838                                 }
2839                                 value += temp;
2840                                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2841                         }
2842                 }
2843         }
2844         else {
2845                 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2846                 return NULL;
2847         }
2848
2849         if (fread(&ch, 1, 1, f)) {
2850                 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2851         }
2852         fclose(f);
2853
2854         return image;
2855 }
2856
2857 int imagetoraw(opj_image_t * image, const char *outfile)
2858 {
2859         FILE *rawFile = NULL;
2860   size_t res;
2861         int compno;
2862         int w, h;
2863         int line, row;
2864         int *ptr;
2865
2866         if((image->numcomps * image->x1 * image->y1) == 0)
2867         {
2868                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2869                 return 1;
2870         }
2871
2872         rawFile = fopen(outfile, "wb");
2873         if (!rawFile) {
2874                 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2875                 return 1;
2876         }
2877
2878         fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2879
2880         for(compno = 0; compno < image->numcomps; compno++)
2881         {
2882                 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2883                         image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2884
2885                 w = image->comps[compno].w;
2886                 h = image->comps[compno].h;
2887
2888                 if(image->comps[compno].prec <= 8)
2889                 {
2890                         if(image->comps[compno].sgnd == 1)
2891                         {
2892                                 signed char curr;
2893                                 int mask = (1 << image->comps[compno].prec) - 1;
2894                                 ptr = image->comps[compno].data;
2895                                 for (line = 0; line < h; line++) {
2896                                         for(row = 0; row < w; row++)    {                               
2897                                                 curr = (signed char) (*ptr & mask);
2898                                                 res = fwrite(&curr, sizeof(signed char), 1, rawFile);
2899             if( res < 1 ) {
2900               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2901               return 1;
2902             }
2903                                                 ptr++;
2904                                         }
2905                                 }
2906                         }
2907                         else if(image->comps[compno].sgnd == 0)
2908                         {
2909                                 unsigned char curr;
2910                                 int mask = (1 << image->comps[compno].prec) - 1;
2911                                 ptr = image->comps[compno].data;
2912                                 for (line = 0; line < h; line++) {
2913                                         for(row = 0; row < w; row++)    {       
2914                                                 curr = (unsigned char) (*ptr & mask);
2915                                                 res = fwrite(&curr, sizeof(unsigned char), 1, rawFile);
2916             if( res < 1 ) {
2917               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2918               return 1;
2919             }
2920                                                 ptr++;
2921                                         }
2922                                 }
2923                         }
2924                 }
2925                 else if(image->comps[compno].prec <= 16)
2926                 {
2927                         if(image->comps[compno].sgnd == 1)
2928                         {
2929                                 signed short int curr;
2930                                 int mask = (1 << image->comps[compno].prec) - 1;
2931                                 ptr = image->comps[compno].data;
2932                                 for (line = 0; line < h; line++) {
2933                                         for(row = 0; row < w; row++)    {                                       
2934                                                 unsigned char temp;
2935                                                 curr = (signed short int) (*ptr & mask);
2936                                                 temp = (unsigned char) (curr >> 8);
2937                                                 res = fwrite(&temp, 1, 1, rawFile);
2938             if( res < 1 ) {
2939               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2940               return 1;
2941             }
2942                                                 temp = (unsigned char) curr;
2943                                                 res = fwrite(&temp, 1, 1, rawFile);
2944             if( res < 1 ) {
2945               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2946               return 1;
2947             }
2948                                                 ptr++;
2949                                         }
2950                                 }
2951                         }
2952                         else if(image->comps[compno].sgnd == 0)
2953                         {
2954                                 unsigned short int curr;
2955                                 int mask = (1 << image->comps[compno].prec) - 1;
2956                                 ptr = image->comps[compno].data;
2957                                 for (line = 0; line < h; line++) {
2958                                         for(row = 0; row < w; row++)    {                               
2959                                                 unsigned char temp;
2960                                                 curr = (unsigned short int) (*ptr & mask);
2961                                                 temp = (unsigned char) (curr >> 8);
2962                                                 res = fwrite(&temp, 1, 1, rawFile);
2963             if( res < 1 ) {
2964               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2965               return 1;
2966             }
2967                                                 temp = (unsigned char) curr;
2968                                                 res = fwrite(&temp, 1, 1, rawFile);
2969             if( res < 1 ) {
2970               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2971               return 1;
2972             }
2973                                                 ptr++;
2974                                         }
2975                                 }
2976                         }
2977                 }
2978                 else if (image->comps[compno].prec <= 32)
2979                 {
2980                         fprintf(stderr,"More than 16 bits per component no handled yet\n");
2981                         return 1;
2982                 }
2983                 else
2984                 {
2985                         fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2986                         return 1;
2987                 }
2988         }
2989         fclose(rawFile);
2990         return 0;
2991 }
2992
2993 #ifdef HAVE_LIBPNG
2994
2995 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
2996 #define MAGIC_SIZE 8
2997 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
2998
2999 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
3000 {
3001         png_structp  png;
3002         png_infop    info;
3003         double gamma, display_exponent;
3004         int bit_depth, interlace_type,compression_type, filter_type;
3005         int unit;
3006         png_uint_32 resx, resy;
3007         unsigned int i, j;
3008         png_uint_32  width, height;
3009         int color_type, has_alpha, is16;
3010         unsigned char *s;
3011         FILE *reader;
3012         unsigned char **rows;
3013 /* j2k: */
3014         opj_image_t *image;
3015         opj_image_cmptparm_t cmptparm[4];
3016         int sub_dx, sub_dy;
3017         unsigned int nr_comp;
3018         int *r, *g, *b, *a;
3019         unsigned char sigbuf[8];
3020
3021         if((reader = fopen(read_idf, "rb")) == NULL)
3022    {
3023         fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
3024         return NULL;
3025    }
3026         image = NULL; png = NULL; rows = NULL;
3027
3028         if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
3029         || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
3030    {
3031         fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
3032         goto fin;
3033    }
3034 /* libpng-VERSION/example.c: 
3035  * PC : screen_gamma = 2.2;
3036  * Mac: screen_gamma = 1.7 or 1.0;
3037 */
3038         display_exponent = 2.2;
3039
3040         if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
3041                                     NULL, NULL, NULL)) == NULL)
3042           goto fin;
3043         if((info = png_create_info_struct(png)) == NULL)
3044           goto fin;
3045
3046         if(setjmp(png_jmpbuf(png)))
3047           goto fin;
3048
3049         png_init_io(png, reader);
3050         png_set_sig_bytes(png, MAGIC_SIZE);
3051
3052         png_read_info(png, info);
3053
3054         if(png_get_IHDR(png, info, &width, &height,
3055                 &bit_depth, &color_type, &interlace_type, 
3056                 &compression_type, &filter_type) == 0)
3057          goto fin;
3058
3059 /* png_set_expand():
3060  * expand paletted images to RGB, expand grayscale images of
3061  * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
3062  * to alpha channels.
3063 */
3064         if(color_type == PNG_COLOR_TYPE_PALETTE)
3065           png_set_expand(png);
3066         else
3067         if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
3068           png_set_expand(png);
3069
3070         if(png_get_valid(png, info, PNG_INFO_tRNS))
3071           png_set_expand(png);
3072
3073         is16 = (bit_depth == 16);
3074
3075 /* GRAY => RGB; GRAY_ALPHA => RGBA
3076 */
3077         if(color_type == PNG_COLOR_TYPE_GRAY
3078         || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
3079    {
3080         png_set_gray_to_rgb(png);
3081         color_type = 
3082          (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
3083                 PNG_COLOR_TYPE_RGB_ALPHA);
3084    }
3085         if( !png_get_gAMA(png, info, &gamma))
3086           gamma = 0.45455;
3087
3088         png_set_gamma(png, display_exponent, gamma);
3089
3090         png_read_update_info(png, info);
3091
3092         png_get_pHYs(png, info, &resx, &resy, &unit);
3093
3094         color_type = png_get_color_type(png, info);
3095
3096         has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
3097
3098         nr_comp = 3 + has_alpha;
3099
3100         bit_depth = png_get_bit_depth(png, info);
3101
3102         rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
3103         for(i = 0; i < height; ++i)
3104          rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
3105
3106         png_read_image(png, rows);
3107
3108         memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
3109
3110         sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
3111
3112         for(i = 0; i < nr_comp; ++i)
3113    {
3114         cmptparm[i].prec = bit_depth;
3115 /* bits_per_pixel: 8 or 16 */
3116         cmptparm[i].bpp = bit_depth;
3117         cmptparm[i].sgnd = 0;
3118         cmptparm[i].dx = sub_dx;
3119         cmptparm[i].dy = sub_dy;
3120         cmptparm[i].w = width;
3121         cmptparm[i].h = height;
3122    }
3123
3124         image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
3125
3126         if(image == NULL) goto fin;
3127
3128     image->x0 = params->image_offset_x0;
3129     image->y0 = params->image_offset_y0;
3130     image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
3131     image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
3132
3133         r = image->comps[0].data;
3134         g = image->comps[1].data;
3135         b = image->comps[2].data;
3136         a = image->comps[3].data;
3137
3138         for(i = 0; i < height; ++i)
3139    {
3140         s = rows[i];
3141
3142         for(j = 0; j < width; ++j)
3143   {
3144         if(is16)
3145  {
3146         *r++ = s[0]<<8|s[1]; s += 2;
3147
3148         *g++ = s[0]<<8|s[1]; s += 2;
3149         
3150         *b++ = s[0]<<8|s[1]; s += 2;
3151         
3152         if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
3153
3154         continue;
3155  }
3156         *r++ = *s++; *g++ = *s++; *b++ = *s++;
3157
3158         if(has_alpha) *a++ = *s++;
3159   }
3160    }
3161 fin:
3162         if(rows)
3163    {
3164         for(i = 0; i < height; ++i)
3165          free(rows[i]);
3166         free(rows);
3167    }
3168         if(png)
3169           png_destroy_read_struct(&png, &info, NULL);
3170
3171         fclose(reader);
3172
3173         return image;
3174
3175 }/* pngtoimage() */
3176
3177 int imagetopng(opj_image_t * image, const char *write_idf)
3178 {
3179         FILE *writer;
3180         png_structp png;
3181         png_infop info;
3182         int *red, *green, *blue, *alpha;
3183         unsigned char *row_buf, *d;
3184         int has_alpha, width, height, nr_comp, color_type;
3185         int adjustR, adjustG, adjustB, x, y, fails, is16, force16;
3186   int opj_prec, prec, ushift, dshift;
3187         unsigned short mask = 0xffff;
3188         png_color_8 sig_bit;
3189
3190         is16 = force16 = ushift = dshift = 0; fails = 1;
3191         prec = opj_prec = image->comps[0].prec;
3192
3193         if(prec > 8 && prec < 16)
3194    {
3195          prec = 16; force16 = 1;
3196    }
3197         if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
3198    {
3199         fprintf(stderr,"imagetopng: can not create %s"
3200          "\n\twrong bit_depth %d\n", write_idf, prec);
3201         return fails;
3202    }
3203         writer = fopen(write_idf, "wb");
3204
3205         if(writer == NULL) return fails;
3206
3207         info = NULL; has_alpha = 0;
3208
3209 /* Create and initialize the png_struct with the desired error handler
3210  * functions.  If you want to use the default stderr and longjump method,
3211  * you can supply NULL for the last three parameters.  We also check that
3212  * the library version is compatible with the one used at compile time,
3213  * in case we are using dynamically linked libraries.  REQUIRED.
3214 */
3215         png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
3216                 NULL, NULL, NULL);
3217 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
3218
3219         if(png == NULL) goto fin;
3220
3221 /* Allocate/initialize the image information data.  REQUIRED 
3222 */
3223         info = png_create_info_struct(png);
3224
3225         if(info == NULL) goto fin;
3226
3227 /* Set error handling.  REQUIRED if you are not supplying your own
3228  * error handling functions in the png_create_write_struct() call.
3229 */
3230         if(setjmp(png_jmpbuf(png))) goto fin;
3231
3232 /* I/O initialization functions is REQUIRED 
3233 */
3234         png_init_io(png, writer);
3235
3236 /* Set the image information here.  Width and height are up to 2^31,
3237  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
3238  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
3239  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
3240  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
3241  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
3242  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
3243  * REQUIRED
3244 */
3245         png_set_compression_level(png, Z_BEST_COMPRESSION);
3246
3247         if(prec == 16) mask = 0xffff;
3248         else
3249         if(prec == 8) mask = 0x00ff;
3250         else
3251         if(prec == 4) mask = 0x000f;
3252         else
3253         if(prec == 2) mask = 0x0003;
3254         else
3255         if(prec == 1) mask = 0x0001;
3256
3257         nr_comp = image->numcomps;
3258
3259         if(nr_comp >= 3
3260     && image->comps[0].dx == image->comps[1].dx
3261     && image->comps[1].dx == image->comps[2].dx
3262     && image->comps[0].dy == image->comps[1].dy
3263     && image->comps[1].dy == image->comps[2].dy
3264     && image->comps[0].prec == image->comps[1].prec
3265     && image->comps[1].prec == image->comps[2].prec)
3266    {
3267         int v;
3268
3269     has_alpha = (nr_comp > 3); 
3270
3271         is16 = (prec == 16);
3272         
3273     width = image->comps[0].w;
3274     height = image->comps[0].h;
3275
3276         red = image->comps[0].data;
3277         green = image->comps[1].data;
3278         blue = image->comps[2].data;
3279
3280     sig_bit.red = sig_bit.green = sig_bit.blue = prec;
3281
3282         if(has_alpha) 
3283   {
3284         sig_bit.alpha = prec;
3285         alpha = image->comps[3].data; 
3286         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
3287   }
3288         else 
3289   {
3290         sig_bit.alpha = 0; alpha = NULL;
3291         color_type = PNG_COLOR_TYPE_RGB;
3292   }
3293         png_set_sBIT(png, info, &sig_bit);
3294
3295         png_set_IHDR(png, info, width, height, prec, 
3296          color_type,
3297          PNG_INTERLACE_NONE,
3298          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3299
3300 /*=============================*/
3301         png_write_info(png, info);
3302 /*=============================*/
3303         if(opj_prec < 8)
3304   {
3305         png_set_packing(png);
3306   }
3307         if(force16)
3308   {
3309         ushift = 16 - opj_prec; dshift = opj_prec - ushift;     
3310   }
3311     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3312     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3313     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
3314
3315         row_buf = (unsigned char*)malloc(width * nr_comp * 2);
3316
3317         for(y = 0; y < height; ++y)
3318   {
3319         d = row_buf;
3320
3321         for(x = 0; x < width; ++x)
3322  {
3323                 if(is16)
3324            {
3325                 v = *red + adjustR; ++red;
3326                 
3327                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3328
3329                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3330
3331                 v = *green + adjustG; ++green;
3332                 
3333                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3334
3335                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3336
3337                 v =  *blue + adjustB; ++blue;
3338                 
3339                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3340
3341                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3342
3343                 if(has_alpha)
3344           {
3345                 v = *alpha++;
3346                 
3347                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3348
3349                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3350           }
3351                 continue;
3352            }
3353                 *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
3354                 *d++ = (unsigned char)((*green + adjustG) & mask); ++green;
3355                 *d++ = (unsigned char)((*blue + adjustB) & mask); ++blue;
3356
3357                 if(has_alpha)
3358            {
3359                 *d++ = (unsigned char)(*alpha & mask); ++alpha;
3360            }
3361  }      /* for(x) */
3362
3363         png_write_row(png, row_buf);
3364
3365   }     /* for(y) */
3366         free(row_buf);
3367
3368    }/* nr_comp >= 3 */
3369         else
3370         if(nr_comp == 1 /* GRAY */
3371         || (   nr_comp == 2 /* GRAY_ALPHA */
3372                 && image->comps[0].dx == image->comps[1].dx
3373                 && image->comps[0].dy == image->comps[1].dy
3374                 && image->comps[0].prec == image->comps[1].prec))
3375    {
3376         int v;
3377
3378         red = image->comps[0].data;
3379
3380     if(force16)
3381   {
3382     ushift = 16 - opj_prec; dshift = opj_prec - ushift;
3383   }
3384     sig_bit.gray = prec;
3385     sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3386         alpha = NULL;
3387         color_type = PNG_COLOR_TYPE_GRAY;
3388
3389     if(nr_comp == 2) 
3390   { 
3391         has_alpha = 1; sig_bit.alpha = prec;
3392         alpha = image->comps[1].data;
3393         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3394   }
3395     width = image->comps[0].w;
3396     height = image->comps[0].h;
3397
3398         png_set_IHDR(png, info, width, height, sig_bit.gray,
3399      color_type,
3400      PNG_INTERLACE_NONE,
3401      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3402
3403         png_set_sBIT(png, info, &sig_bit);
3404 /*=============================*/
3405         png_write_info(png, info);
3406 /*=============================*/
3407         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3408
3409         if(opj_prec < 8)
3410   {
3411         png_set_packing(png);
3412   }
3413
3414         if(prec > 8)
3415   {
3416         row_buf = (unsigned char*)
3417          malloc(width * nr_comp * sizeof(unsigned short));
3418
3419         for(y = 0; y < height; ++y)
3420  {
3421         d = row_buf;
3422
3423                 for(x = 0; x < width; ++x)
3424            {
3425                 v = *red + adjustR; ++red;
3426
3427                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3428
3429                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3430
3431                 if(has_alpha)
3432           {
3433                 v = *alpha++;
3434
3435                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3436
3437                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3438           }
3439            }/* for(x) */
3440         png_write_row(png, row_buf);
3441
3442  }      /* for(y) */
3443         free(row_buf);
3444   }
3445         else /* prec <= 8 */
3446   {
3447         row_buf = (unsigned char*)calloc(width, nr_comp * 2);
3448
3449         for(y = 0; y < height; ++y)
3450  {
3451         d = row_buf;
3452
3453                 for(x = 0; x < width; ++x)
3454            {
3455                 *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
3456
3457                 if(has_alpha)
3458           {
3459                 *d++ = (unsigned char)(*alpha & mask); ++alpha;
3460           }
3461            }/* for(x) */
3462
3463         png_write_row(png, row_buf);
3464
3465  }      /* for(y) */
3466         free(row_buf);
3467   }
3468    }
3469         else
3470    {
3471         fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3472         goto fin;
3473    }
3474         png_write_end(png, info);
3475
3476         fails = 0;
3477
3478 fin:
3479
3480         if(png)
3481    {
3482     png_destroy_write_struct(&png, &info);
3483    }
3484         fclose(writer);
3485
3486         if(fails) remove(write_idf);
3487
3488         return fails;
3489 }/* imagetopng() */
3490 #endif /* HAVE_LIBPNG */