Added support for PNG image format [Not yet functional under WIN32]. Thanks to Winfri...
[openjpeg.git] / 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 <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #ifdef WIN32
36 #include "../libs/libtiff/tiffio.h"
37 #include "../libs/libpng/png.h"
38 #else
39 #include <tiffio.h>
40 #include <png.h>
41 #endif /* WIN32 */
42 #include "openjpeg.h"
43 #include "convert.h"
44
45 /*
46  * Get logarithm of an integer and round downwards.
47  *
48  * log2(a)
49  */
50 static int int_floorlog2(int a) {
51         int l;
52         for (l = 0; a > 1; l++) {
53                 a >>= 1;
54         }
55         return l;
56 }
57
58 /*
59  * Divide an integer by a power of 2 and round upwards.
60  *
61  * a divided by 2^b
62  */
63 static int int_ceildivpow2(int a, int b) {
64         return (a + (1 << b) - 1) >> b;
65 }
66
67 /*
68  * Divide an integer and round upwards.
69  *
70  * a divided by b
71  */
72 static int int_ceildiv(int a, int b) {
73         return (a + b - 1) / b;
74 }
75
76
77 /* -->> -->> -->> -->>
78
79   TGA IMAGE FORMAT
80
81  <<-- <<-- <<-- <<-- */
82
83 // TGA header definition.
84 #pragma pack(push,1) // Pack structure byte aligned
85 typedef struct tga_header
86 {                           
87     uint8   id_length;              /* Image id field length    */
88     uint8   colour_map_type;        /* Colour map type          */
89     uint8   image_type;             /* Image type               */
90     /*
91     ** Colour map specification
92     */
93     uint16  colour_map_index;       /* First entry index        */
94     uint16  colour_map_length;      /* Colour map length        */
95     uint8   colour_map_entry_size;  /* Colour map entry size    */
96     /*
97     ** Image specification
98     */
99     uint16  x_origin;               /* x origin of image        */
100     uint16  y_origin;               /* u origin of image        */
101     uint16  image_width;            /* Image width              */
102     uint16  image_height;           /* Image height             */
103     uint8   pixel_depth;            /* Pixel depth              */
104     uint8   image_desc;             /* Image descriptor         */
105 } tga_header;
106 #pragma pack(pop) // Return to normal structure packing alignment.
107
108 int tga_readheader(FILE *fp, uint32 *bits_per_pixel, uint32 *width, uint32 *height, int *flip_image)
109 {
110         int palette_size;
111         tga_header tga ;
112
113         if (!bits_per_pixel || !width || !height || !flip_image)
114                 return 0;
115         
116         // Read TGA header
117         fread((uint8*)&tga, sizeof(tga_header), 1, fp);
118
119         *bits_per_pixel = tga.pixel_depth;
120         
121         *width  = tga.image_width;
122         *height = tga.image_height ;
123
124         // Ignore tga identifier, if present ...
125         if (tga.id_length)
126         {
127                 uint8 *id = (uint8 *) malloc(tga.id_length);
128                 fread(id, tga.id_length, 1, fp);
129                 free(id);  
130         }
131
132         // Test for compressed formats ... not yet supported ...
133         // Note :-  9 - RLE encoded palettized.
134         //                 10 - RLE encoded RGB.
135         if (tga.image_type > 8)
136         {
137                 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
138                 return 0 ;
139         }
140
141         *flip_image = !(tga.image_desc & 32);
142
143         // Palettized formats are not yet supported, skip over the palette, if present ... 
144         palette_size = tga.colour_map_length * (tga.colour_map_entry_size/8);
145         
146         if (palette_size>0)
147         {
148                 fprintf(stderr, "File contains a palette - not yet supported.");
149                 fseek(fp, palette_size, SEEK_CUR);
150         }
151         return 1;
152 }
153
154 int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, bool flip_image)
155 {
156         tga_header tga;
157
158         if (!bits_per_pixel || !width || !height)
159                 return 0;
160
161         memset(&tga, 0, sizeof(tga_header));
162
163         tga.pixel_depth = bits_per_pixel;
164         tga.image_width  = width;
165         tga.image_height = height;
166         tga.image_type = 2; // Uncompressed.
167         tga.image_desc = 8; // 8 bits per component.
168
169         if (flip_image)
170                 tga.image_desc |= 32;
171
172         // Write TGA header
173         fwrite((uint8*)&tga, sizeof(tga_header), 1, fp);
174
175         return 1;
176 }
177
178 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
179         FILE *f;
180         opj_image_t *image;
181         uint32 image_width, image_height, pixel_bit_depth;
182         uint32 x, y;
183         int flip_image=0;
184         opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
185         int numcomps;
186         OPJ_COLOR_SPACE color_space;
187         bool mono ;
188         bool save_alpha;
189         int subsampling_dx, subsampling_dy;
190         int i;  
191
192         f = fopen(filename, "rb");
193         if (!f) {
194                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
195                 return 0;
196         }
197
198         if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
199                 return NULL;
200
201         // We currently only support 24 & 32 bit tga's ...
202         if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
203                 return NULL;
204
205         /* initialize image components */   
206         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
207
208         mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  // Mono with & without alpha.
209         save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); // Mono with alpha, or RGB with alpha
210
211         if (mono) {
212                 color_space = CLRSPC_GRAY;
213                 numcomps = save_alpha ? 2 : 1;
214         }       
215         else {
216                 numcomps = save_alpha ? 4 : 3;
217                 color_space = CLRSPC_SRGB;
218         }
219
220         subsampling_dx = parameters->subsampling_dx;
221         subsampling_dy = parameters->subsampling_dy;
222
223         for (i = 0; i < numcomps; i++) {
224                 cmptparm[i].prec = 8;
225                 cmptparm[i].bpp = 8;
226                 cmptparm[i].sgnd = 0;
227                 cmptparm[i].dx = subsampling_dx;
228                 cmptparm[i].dy = subsampling_dy;
229                 cmptparm[i].w = image_width;
230                 cmptparm[i].h = image_height;
231         }
232
233         /* create the image */
234         image = opj_image_create(numcomps, &cmptparm[0], color_space);
235
236         if (!image)
237                 return NULL;
238
239         /* set image offset and reference grid */
240         image->x0 = parameters->image_offset_x0;
241         image->y0 = parameters->image_offset_y0;
242         image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
243         image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
244
245         /* set image data */
246         for (y=0; y < image_height; y++) 
247         {
248                 int index;
249
250                 if (flip_image)
251                         index = (image_height-y-1)*image_width;
252                 else
253                         index = y*image_width;
254
255                 if (numcomps==3)
256                 {
257                         for (x=0;x<image_width;x++) 
258                         {
259                                 uint8 r,g,b;
260                                 fread(&b, 1, 1, f);
261                                 fread(&g, 1, 1, f);
262                                 fread(&r, 1, 1, f);
263
264                                 image->comps[0].data[index]=r;
265                                 image->comps[1].data[index]=g;
266                                 image->comps[2].data[index]=b;
267                                 index++;
268                         }
269                 }
270                 else if (numcomps==4)
271                 {
272                         for (x=0;x<image_width;x++) 
273                         {
274                                 uint8 r,g,b,a;
275                                 fread(&b, 1, 1, f);
276                                 fread(&g, 1, 1, f);
277                                 fread(&r, 1, 1, f);
278                                 fread(&a, 1, 1, f);
279
280                                 image->comps[0].data[index]=r;
281                                 image->comps[1].data[index]=g;
282                                 image->comps[2].data[index]=b;
283                                 image->comps[3].data[index]=a;
284                                 index++;
285                         }
286                 }
287                 else {
288                         fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
289                 }
290         }       
291         return image;
292 }
293
294 int imagetotga(opj_image_t * image, const char *outfile) {
295         int width, height, bpp, x, y;
296         bool write_alpha;
297         int i;
298         uint32 alpha_channel;
299         float r,g,b,a;
300         uint8 value;
301         float scale;
302         FILE *fdest;
303
304         fdest = fopen(outfile, "wb");
305         if (!fdest) {
306                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
307                 return 1;
308         }
309
310         for (i = 0; i < image->numcomps-1; i++) {
311                 if ((image->comps[0].dx != image->comps[i+1].dx) 
312                         ||(image->comps[0].dy != image->comps[i+1].dy) 
313                         ||(image->comps[0].prec != image->comps[i+1].prec))     {
314       fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
315       return 1;
316    }
317         }
318
319         width = image->comps[0].w;
320         height = image->comps[0].h; 
321
322         // Mono with alpha, or RGB with alpha.
323         write_alpha = (image->numcomps==2) || (image->numcomps==4);   
324
325         // Write TGA header 
326         bpp = write_alpha ? 32 : 24;
327         if (!tga_writeheader(fdest, bpp, width , height, true))
328                 return 1;
329
330         alpha_channel = image->numcomps-1; 
331
332         scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
333
334         for (y=0; y < height; y++) {
335                 uint32 index=y*width;
336
337                 for (x=0; x < width; x++, index++)      {
338                         r = (float)(image->comps[0].data[index]);
339
340                         if (image->numcomps>2) {
341                                 g = (float)(image->comps[1].data[index]);
342                                 b = (float)(image->comps[2].data[index]);
343                         }
344                         else  {// Greyscale ...
345                                 g = r;
346                                 b = r;
347                         }
348
349                         // TGA format writes BGR ...
350                         value = (uint8)(b*scale);
351                         fwrite(&value,1,1,fdest);
352
353                         value = (uint8)(g*scale);
354                         fwrite(&value,1,1,fdest);
355
356                         value = (uint8)(r*scale);
357                         fwrite(&value,1,1,fdest);
358
359                         if (write_alpha) {
360                                 a = (float)(image->comps[alpha_channel].data[index]);
361                                 value = (uint8)(a*scale);
362                                 fwrite(&value,1,1,fdest);
363                         }
364                 }
365         }
366
367         return 0;
368 }
369
370 /* -->> -->> -->> -->>
371
372   BMP IMAGE FORMAT
373
374  <<-- <<-- <<-- <<-- */
375
376 /* WORD defines a two byte word */
377 typedef unsigned short int WORD;
378
379 /* DWORD defines a four byte word */
380 typedef unsigned long int DWORD;
381
382 typedef struct {
383   WORD bfType;                  /* 'BM' for Bitmap (19776) */
384   DWORD bfSize;                 /* Size of the file        */
385   WORD bfReserved1;             /* Reserved : 0            */
386   WORD bfReserved2;             /* Reserved : 0            */
387   DWORD bfOffBits;              /* Offset                  */
388 } BITMAPFILEHEADER_t;
389
390 typedef struct {
391   DWORD biSize;                 /* Size of the structure in bytes */
392   DWORD biWidth;                /* Width of the image in pixels */
393   DWORD biHeight;               /* Heigth of the image in pixels */
394   WORD biPlanes;                /* 1 */
395   WORD biBitCount;              /* Number of color bits by pixels */
396   DWORD biCompression;          /* Type of encoding 0: none 1: RLE8 2: RLE4 */
397   DWORD biSizeImage;            /* Size of the image in bytes */
398   DWORD biXpelsPerMeter;        /* Horizontal (X) resolution in pixels/meter */
399   DWORD biYpelsPerMeter;        /* Vertical (Y) resolution in pixels/meter */
400   DWORD biClrUsed;              /* Number of color used in the image (0: ALL) */
401   DWORD biClrImportant;         /* Number of important color (0: ALL) */
402 } BITMAPINFOHEADER_t;
403
404 opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) {
405         int subsampling_dx = parameters->subsampling_dx;
406         int subsampling_dy = parameters->subsampling_dy;
407
408         int i, numcomps, w, h;
409         OPJ_COLOR_SPACE color_space;
410         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
411         opj_image_t * image = NULL;
412
413         FILE *IN;
414         BITMAPFILEHEADER_t File_h;
415         BITMAPINFOHEADER_t Info_h;
416         unsigned char *RGB;
417         unsigned char *table_R, *table_G, *table_B;
418         unsigned int j, PAD = 0;
419
420         int x, y, index;
421         int gray_scale = 1, not_end_file = 1; 
422
423         unsigned int line = 0, col = 0;
424         unsigned char v, v2;
425         DWORD W, H;
426   
427         IN = fopen(filename, "rb");
428         if (!IN) {
429                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
430                 return 0;
431         }
432         
433         File_h.bfType = getc(IN);
434         File_h.bfType = (getc(IN) << 8) + File_h.bfType;
435         
436         if (File_h.bfType != 19778) {
437                 fprintf(stderr,"Error, not a BMP file!\n");
438                 return 0;
439         } else {
440                 /* FILE HEADER */
441                 /* ------------- */
442                 File_h.bfSize = getc(IN);
443                 File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
444                 File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
445                 File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
446
447                 File_h.bfReserved1 = getc(IN);
448                 File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
449
450                 File_h.bfReserved2 = getc(IN);
451                 File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
452
453                 File_h.bfOffBits = getc(IN);
454                 File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
455                 File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
456                 File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
457
458                 /* INFO HEADER */
459                 /* ------------- */
460
461                 Info_h.biSize = getc(IN);
462                 Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
463                 Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
464                 Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
465
466                 Info_h.biWidth = getc(IN);
467                 Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
468                 Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
469                 Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
470                 w = Info_h.biWidth;
471
472                 Info_h.biHeight = getc(IN);
473                 Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
474                 Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
475                 Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
476                 h = Info_h.biHeight;
477
478                 Info_h.biPlanes = getc(IN);
479                 Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
480
481                 Info_h.biBitCount = getc(IN);
482                 Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
483
484                 Info_h.biCompression = getc(IN);
485                 Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
486                 Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
487                 Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
488
489                 Info_h.biSizeImage = getc(IN);
490                 Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
491                 Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
492                 Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
493
494                 Info_h.biXpelsPerMeter = getc(IN);
495                 Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
496                 Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
497                 Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
498
499                 Info_h.biYpelsPerMeter = getc(IN);
500                 Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
501                 Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
502                 Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
503
504                 Info_h.biClrUsed = getc(IN);
505                 Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
506                 Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
507                 Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
508
509                 Info_h.biClrImportant = getc(IN);
510                 Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
511                 Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
512                 Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
513
514                 /* Read the data and store them in the OUT file */
515     
516                 if (Info_h.biBitCount == 24) {
517                         numcomps = 3;
518                         color_space = CLRSPC_SRGB;
519                         /* initialize image components */
520                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
521                         for(i = 0; i < numcomps; i++) {
522                                 cmptparm[i].prec = 8;
523                                 cmptparm[i].bpp = 8;
524                                 cmptparm[i].sgnd = 0;
525                                 cmptparm[i].dx = subsampling_dx;
526                                 cmptparm[i].dy = subsampling_dy;
527                                 cmptparm[i].w = w;
528                                 cmptparm[i].h = h;
529                         }
530                         /* create the image */
531                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
532                         if(!image) {
533                                 fclose(IN);
534                                 return NULL;
535                         }
536
537                         /* set image offset and reference grid */
538                         image->x0 = parameters->image_offset_x0;
539                         image->y0 = parameters->image_offset_y0;
540                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
541                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
542
543                         /* set image data */
544
545                         /* Place the cursor at the beginning of the image information */
546                         fseek(IN, 0, SEEK_SET);
547                         fseek(IN, File_h.bfOffBits, SEEK_SET);
548                         
549                         W = Info_h.biWidth;
550                         H = Info_h.biHeight;
551
552                         /* PAD = 4 - (3 * W) % 4; */
553                         /* PAD = (PAD == 4) ? 0 : PAD; */
554                         PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
555                         
556                         RGB = (unsigned char *) malloc((3 * W + PAD) * H * sizeof(unsigned char));
557                         
558                         fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN);
559                         
560                         index = 0;
561
562                         for(y = 0; y < (int)H; y++) {
563                                 unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
564                                 for(x = 0; x < (int)W; x++) {
565                                         unsigned char *pixel = &scanline[3 * x];
566                                         image->comps[0].data[index] = pixel[2]; /* R */
567                                         image->comps[1].data[index] = pixel[1]; /* G */
568                                         image->comps[2].data[index] = pixel[0]; /* B */
569                                         index++;
570                                 }
571                         }
572
573                         free(RGB);
574
575                 } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) {
576                         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
577                         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
578                         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
579                         
580                         for (j = 0; j < Info_h.biClrUsed; j++) {
581                                 table_B[j] = getc(IN);
582                                 table_G[j] = getc(IN);
583                                 table_R[j] = getc(IN);
584                                 getc(IN);
585                                 if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
586                                         gray_scale = 0;
587                         }
588                         
589                         /* Place the cursor at the beginning of the image information */
590                         fseek(IN, 0, SEEK_SET);
591                         fseek(IN, File_h.bfOffBits, SEEK_SET);
592                         
593                         W = Info_h.biWidth;
594                         H = Info_h.biHeight;
595                         if (Info_h.biWidth % 2)
596                                 W++;
597                         
598                         numcomps = gray_scale ? 1 : 3;
599                         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
600                         /* initialize image components */
601                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
602                         for(i = 0; i < numcomps; i++) {
603                                 cmptparm[i].prec = 8;
604                                 cmptparm[i].bpp = 8;
605                                 cmptparm[i].sgnd = 0;
606                                 cmptparm[i].dx = subsampling_dx;
607                                 cmptparm[i].dy = subsampling_dy;
608                                 cmptparm[i].w = w;
609                                 cmptparm[i].h = h;
610                         }
611                         /* create the image */
612                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
613                         if(!image) {
614                                 fclose(IN);
615                                 return NULL;
616                         }
617
618                         /* set image offset and reference grid */
619                         image->x0 = parameters->image_offset_x0;
620                         image->y0 = parameters->image_offset_y0;
621                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
622                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
623
624                         /* set image data */
625
626                         RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
627                         
628                         fread(RGB, sizeof(unsigned char), W * H, IN);
629                         if (gray_scale) {
630                                 index = 0;
631                                 for (j = 0; j < W * H; j++) {
632                                         if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
633                                                 image->comps[0].data[index] = table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
634                                                 index++;
635                                         }
636                                 }
637
638                         } else {                
639                                 index = 0;
640                                 for (j = 0; j < W * H; j++) {
641                                         if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
642                                                 unsigned char pixel_index = RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
643                                                 image->comps[0].data[index] = table_R[pixel_index];
644                                                 image->comps[1].data[index] = table_G[pixel_index];
645                                                 image->comps[2].data[index] = table_B[pixel_index];
646                                                 index++;
647                                         }
648                                 }
649                         }
650                         free(RGB);
651       free(table_R);
652       free(table_G);
653       free(table_B);
654                 } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) {                               
655                         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
656                         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
657                         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
658                         
659                         for (j = 0; j < Info_h.biClrUsed; j++) {
660                                 table_B[j] = getc(IN);
661                                 table_G[j] = getc(IN);
662                                 table_R[j] = getc(IN);
663                                 getc(IN);
664                                 if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
665                                         gray_scale = 0;
666                         }
667
668                         numcomps = gray_scale ? 1 : 3;
669                         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
670                         /* initialize image components */
671                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
672                         for(i = 0; i < numcomps; i++) {
673                                 cmptparm[i].prec = 8;
674                                 cmptparm[i].bpp = 8;
675                                 cmptparm[i].sgnd = 0;
676                                 cmptparm[i].dx = subsampling_dx;
677                                 cmptparm[i].dy = subsampling_dy;
678                                 cmptparm[i].w = w;
679                                 cmptparm[i].h = h;
680                         }
681                         /* create the image */
682                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
683                         if(!image) {
684                                 fclose(IN);
685                                 return NULL;
686                         }
687
688                         /* set image offset and reference grid */
689                         image->x0 = parameters->image_offset_x0;
690                         image->y0 = parameters->image_offset_y0;
691                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
692                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
693
694                         /* set image data */
695                         
696                         /* Place the cursor at the beginning of the image information */
697                         fseek(IN, 0, SEEK_SET);
698                         fseek(IN, File_h.bfOffBits, SEEK_SET);
699                         
700                         RGB = (unsigned char *) malloc(Info_h.biWidth * Info_h.biHeight * sizeof(unsigned char));
701             
702                         while (not_end_file) {
703                                 v = getc(IN);
704                                 if (v) {
705                                         v2 = getc(IN);
706                                         for (i = 0; i < (int) v; i++) {
707                                                 RGB[line * Info_h.biWidth + col] = v2;
708                                                 col++;
709                                         }
710                                 } else {
711                                         v = getc(IN);
712                                         switch (v) {
713                                                 case 0:
714                                                         col = 0;
715                                                         line++;
716                                                         break;
717                                                 case 1:
718                                                         line++;
719                                                         not_end_file = 0;
720                                                         break;
721                                                 case 2:
722                                                         fprintf(stderr,"No Delta supported\n");
723                                                         opj_image_destroy(image);
724                                                         fclose(IN);
725                                                         return NULL;
726                                                 default:
727                                                         for (i = 0; i < v; i++) {
728                                                                 v2 = getc(IN);
729                                                                 RGB[line * Info_h.biWidth + col] = v2;
730                                                                 col++;
731                                                         }
732                                                         if (v % 2)
733                                                                 v2 = getc(IN);
734                                                         break;
735                                         }
736                                 }
737                         }
738                         if (gray_scale) {
739                                 index = 0;
740                                 for (line = 0; line < Info_h.biHeight; line++) {
741                                         for (col = 0; col < Info_h.biWidth; col++) {
742                                                 image->comps[0].data[index] = table_R[(int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col]];
743                                                 index++;
744                                         }
745                                 }
746                         } else {
747                                 index = 0;
748                                 for (line = 0; line < Info_h.biHeight; line++) {
749                                         for (col = 0; col < Info_h.biWidth; col++) {
750                                                 unsigned char pixel_index = (int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col];
751                                                 image->comps[0].data[index] = table_R[pixel_index];
752                                                 image->comps[1].data[index] = table_G[pixel_index];
753                                                 image->comps[2].data[index] = table_B[pixel_index];
754                                                 index++;
755                                         }
756                                 }
757                         }
758                         free(RGB);
759       free(table_R);
760       free(table_G);
761       free(table_B);
762         } else {
763                 fprintf(stderr, 
764                         "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
765         }
766         fclose(IN);
767  }
768  
769  return image;
770 }
771
772 int imagetobmp(opj_image_t * image, const char *outfile) {
773         int w, h;
774         int i, pad;
775         FILE *fdest = NULL;
776         int adjustR, adjustG, adjustB;
777
778         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
779                 && image->comps[1].dx == image->comps[2].dx
780                 && image->comps[0].dy == image->comps[1].dy
781                 && image->comps[1].dy == image->comps[2].dy
782                 && image->comps[0].prec == image->comps[1].prec
783                 && image->comps[1].prec == image->comps[2].prec) {
784                 
785                 /* -->> -->> -->> -->>    
786                 24 bits color       
787                 <<-- <<-- <<-- <<-- */
788             
789                 fdest = fopen(outfile, "wb");
790                 if (!fdest) {
791                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
792                         return 1;
793                 }
794             
795                 w = image->comps[0].w;      
796                 h = image->comps[0].h;
797             
798                 fprintf(fdest, "BM");
799             
800                 /* FILE HEADER */
801                 /* ------------- */
802                 fprintf(fdest, "%c%c%c%c",
803                         (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
804                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
805                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
806                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
807                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
808                 fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
809             
810                 /* INFO HEADER   */
811                 /* ------------- */
812                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
813                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
814                         (unsigned char) ((w) >> 8) & 0xff,
815                         (unsigned char) ((w) >> 16) & 0xff,
816                         (unsigned char) ((w) >> 24) & 0xff);
817                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
818                         (unsigned char) ((h) >> 8) & 0xff,
819                         (unsigned char) ((h) >> 16) & 0xff,
820                         (unsigned char) ((h) >> 24) & 0xff);
821                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
822                 fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
823                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
824                 fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
825                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
826                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
827                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
828                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
829                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
830                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
831                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
832             
833                 if (image->comps[0].prec > 8) {
834                         adjustR = image->comps[0].prec - 8;
835                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
836                 }
837                 else 
838                         adjustR = 0;
839                 if (image->comps[1].prec > 8) {
840                         adjustG = image->comps[1].prec - 8;
841                         printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
842                 }
843                 else 
844                         adjustG = 0;
845                 if (image->comps[2].prec > 8) {
846                         adjustB = image->comps[2].prec - 8;
847                         printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
848                 }
849                 else 
850                         adjustB = 0;
851
852                 for (i = 0; i < w * h; i++) {
853                         unsigned char rc, gc, bc;
854                         int r, g, b;
855                                                         
856                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
857                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
858                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
859                         g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
860                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
861                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
862                         b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
863                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
864                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
865
866                         fprintf(fdest, "%c%c%c", bc, gc, rc);
867                         
868                         if ((i + 1) % w == 0) {
869                                 for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
870                                         fprintf(fdest, "%c", 0);
871                         }
872                 }
873                 fclose(fdest);
874         } else {                        /* Gray-scale */
875
876                 /* -->> -->> -->> -->>
877                 8 bits non code (Gray scale)
878                 <<-- <<-- <<-- <<-- */
879
880                 fdest = fopen(outfile, "wb");
881                 w = image->comps[0].w;      
882                 h = image->comps[0].h;
883             
884                 fprintf(fdest, "BM");
885             
886                 /* FILE HEADER */
887                 /* ------------- */
888                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
889                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
890                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
891                         (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
892                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
893                 fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
894                         ((54 + 1024) >> 16) & 0xff,
895                         ((54 + 1024) >> 24) & 0xff);
896             
897                 /* INFO HEADER */
898                 /* ------------- */
899                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
900                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
901                         (unsigned char) ((w) >> 8) & 0xff,
902                         (unsigned char) ((w) >> 16) & 0xff,
903                         (unsigned char) ((w) >> 24) & 0xff);
904                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
905                         (unsigned char) ((h) >> 8) & 0xff,
906                         (unsigned char) ((h) >> 16) & 0xff,
907                         (unsigned char) ((h) >> 24) & 0xff);
908                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
909                 fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
910                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
911                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
912                         (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
913                         (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
914                         (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
915                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
916                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
917                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
918                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
919
920                 if (image->comps[0].prec > 8) {
921                         adjustR = image->comps[0].prec - 8;
922                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
923                 }else 
924                         adjustR = 0;
925
926                 for (i = 0; i < 256; i++) {
927                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
928                 }
929
930                 for (i = 0; i < w * h; i++) {
931                         unsigned char rc;
932                         int r;
933                         
934                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
935                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
936                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
937                         
938                         fprintf(fdest, "%c", rc);
939
940                         if ((i + 1) % w == 0) {
941                                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
942                                         fprintf(fdest, "%c", 0);
943                         }
944                 }
945                 fclose(fdest);
946         }
947
948         return 0;
949 }
950
951 /* -->> -->> -->> -->>
952
953 PGX IMAGE FORMAT
954
955 <<-- <<-- <<-- <<-- */
956
957
958 unsigned char readuchar(FILE * f)
959 {
960   unsigned char c1;
961   fread(&c1, 1, 1, f);
962   return c1;
963 }
964
965 unsigned short readushort(FILE * f, int bigendian)
966 {
967   unsigned char c1, c2;
968   fread(&c1, 1, 1, f);
969   fread(&c2, 1, 1, f);
970   if (bigendian)
971     return (c1 << 8) + c2;
972   else
973     return (c2 << 8) + c1;
974 }
975
976 unsigned int readuint(FILE * f, int bigendian)
977 {
978   unsigned char c1, c2, c3, c4;
979   fread(&c1, 1, 1, f);
980   fread(&c2, 1, 1, f);
981   fread(&c3, 1, 1, f);
982   fread(&c4, 1, 1, f);
983   if (bigendian)
984     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
985   else
986     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
987 }
988
989 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
990         FILE *f = NULL;
991         int w, h, prec;
992         int i, numcomps, max;
993         OPJ_COLOR_SPACE color_space;
994         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
995         opj_image_t * image = NULL;
996
997         char endian1,endian2,sign;
998         char signtmp[32];
999
1000         char temp[32];
1001         int bigendian;
1002         opj_image_comp_t *comp = NULL;
1003
1004         numcomps = 1;
1005         color_space = CLRSPC_GRAY;
1006
1007         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1008
1009         max = 0;
1010
1011         f = fopen(filename, "rb");
1012         if (!f) {
1013           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1014           return NULL;
1015         }
1016
1017         fseek(f, 0, SEEK_SET);
1018         fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
1019         
1020         i=0;
1021         sign='+';               
1022         while (signtmp[i]!='\0') {
1023                 if (signtmp[i]=='-') sign='-';
1024                 i++;
1025         }
1026         
1027         fgetc(f);
1028         if (endian1=='M' && endian2=='L') {
1029                 bigendian = 1;
1030         } else if (endian2=='M' && endian1=='L') {
1031                 bigendian = 0;
1032         } else {
1033                 fprintf(stderr, "Bad pgx header, please check input file\n");
1034                 return NULL;
1035         }
1036
1037         /* initialize image component */
1038
1039         cmptparm.x0 = parameters->image_offset_x0;
1040         cmptparm.y0 = parameters->image_offset_y0;
1041         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1042         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1043         
1044         if (sign == '-') {
1045                 cmptparm.sgnd = 1;
1046         } else {
1047                 cmptparm.sgnd = 0;
1048         }
1049         cmptparm.prec = prec;
1050         cmptparm.bpp = prec;
1051         cmptparm.dx = parameters->subsampling_dx;
1052         cmptparm.dy = parameters->subsampling_dy;
1053         
1054         /* create the image */
1055         image = opj_image_create(numcomps, &cmptparm, color_space);
1056         if(!image) {
1057                 fclose(f);
1058                 return NULL;
1059         }
1060         /* set image offset and reference grid */
1061         image->x0 = cmptparm.x0;
1062         image->y0 = cmptparm.x0;
1063         image->x1 = cmptparm.w;
1064         image->y1 = cmptparm.h;
1065
1066         /* set image data */
1067
1068         comp = &image->comps[0];
1069
1070         for (i = 0; i < w * h; i++) {
1071                 int v;
1072                 if (comp->prec <= 8) {
1073                         if (!comp->sgnd) {
1074                                 v = readuchar(f);
1075                         } else {
1076                                 v = (char) readuchar(f);
1077                         }
1078                 } else if (comp->prec <= 16) {
1079                         if (!comp->sgnd) {
1080                                 v = readushort(f, bigendian);
1081                         } else {
1082                                 v = (short) readushort(f, bigendian);
1083                         }
1084                 } else {
1085                         if (!comp->sgnd) {
1086                                 v = readuint(f, bigendian);
1087                         } else {
1088                                 v = (int) readuint(f, bigendian);
1089                         }
1090                 }
1091                 if (v > max)
1092                         max = v;
1093                 comp->data[i] = v;
1094         }
1095         fclose(f);
1096         comp->bpp = int_floorlog2(max) + 1;
1097
1098         return image;
1099 }
1100
1101 int imagetopgx(opj_image_t * image, const char *outfile) {
1102         int w, h;
1103         int i, j, compno;
1104         FILE *fdest = NULL;
1105
1106         for (compno = 0; compno < image->numcomps; compno++) {
1107                 opj_image_comp_t *comp = &image->comps[compno];
1108                 char bname[256]; /* buffer for name */
1109     char *name = bname; /* pointer */
1110     int nbytes = 0;
1111     const size_t olen = strlen(outfile);
1112     const size_t dotpos = olen - 4;
1113     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1114     if( outfile[dotpos] != '.' ) {
1115       /* `pgx` was recognized but there is no dot at expected position */
1116       fprintf(stderr, "ERROR -> Impossible happen." );
1117       return 1;
1118       }
1119     if( total > 256 ) {
1120       name = (char*)malloc(total+1);
1121       }
1122     strncpy(name, outfile, dotpos);
1123                 if (image->numcomps > 1) {
1124                         sprintf(name+dotpos, "-%d.pgx", compno);
1125                 } else {
1126                         strcpy(name+dotpos, ".pgx");
1127                 }
1128                 fdest = fopen(name, "wb");
1129                 if (!fdest) {
1130                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1131                         return 1;
1132                 }
1133     /* dont need name anymore */
1134     if( total > 256 ) {
1135       free(name);
1136       }
1137
1138                 w = image->comps[compno].w;
1139                 h = image->comps[compno].h;
1140             
1141                 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
1142                 if (comp->prec <= 8) {
1143                         nbytes = 1;
1144                 } else if (comp->prec <= 16) {
1145                         nbytes = 2;
1146                 } else {
1147                         nbytes = 4;
1148                 }
1149                 for (i = 0; i < w * h; i++) {
1150                         int v = image->comps[compno].data[i];
1151                         for (j = nbytes - 1; j >= 0; j--) {
1152                                 char byte = (char) (v >> (j * 8));
1153                                 fwrite(&byte, 1, 1, fdest);
1154                         }
1155                 }
1156                 fclose(fdest);
1157         }
1158
1159         return 0;
1160 }
1161
1162 /* -->> -->> -->> -->>
1163
1164 PNM IMAGE FORMAT
1165
1166 <<-- <<-- <<-- <<-- */
1167
1168 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1169         int subsampling_dx = parameters->subsampling_dx;
1170         int subsampling_dy = parameters->subsampling_dy;
1171
1172         FILE *f = NULL;
1173         int i, compno, numcomps, w, h;
1174         OPJ_COLOR_SPACE color_space;
1175         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
1176         opj_image_t * image = NULL;
1177         char value;
1178         
1179         f = fopen(filename, "rb");
1180         if (!f) {
1181                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1182                 return 0;
1183         }
1184
1185         if (fgetc(f) != 'P')
1186                 return 0;
1187         value = fgetc(f);
1188
1189                 switch(value) {
1190                         case '2':       /* greyscale image type */
1191                         case '5':
1192                                 numcomps = 1;
1193                                 color_space = CLRSPC_GRAY;
1194                                 break;
1195                                 
1196                         case '3':       /* RGB image type */
1197                         case '6':
1198                                 numcomps = 3;
1199                                 color_space = CLRSPC_SRGB;
1200                                 break;
1201                                 
1202                         default:
1203                                 fclose(f);
1204                                 return NULL;
1205                 }
1206                 
1207                 fgetc(f);
1208                 
1209                 /* skip comments */
1210                 while(fgetc(f) == '#') while(fgetc(f) != '\n');
1211                 
1212                 fseek(f, -1, SEEK_CUR);
1213                 fscanf(f, "%d %d\n255", &w, &h);                        
1214                 fgetc(f);       /* <cr><lf> */
1215                 
1216         /* initialize image components */
1217         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1218         for(i = 0; i < numcomps; i++) {
1219                 cmptparm[i].prec = 8;
1220                 cmptparm[i].bpp = 8;
1221                 cmptparm[i].sgnd = 0;
1222                 cmptparm[i].dx = subsampling_dx;
1223                 cmptparm[i].dy = subsampling_dy;
1224                 cmptparm[i].w = w;
1225                 cmptparm[i].h = h;
1226         }
1227         /* create the image */
1228         image = opj_image_create(numcomps, &cmptparm[0], color_space);
1229         if(!image) {
1230                 fclose(f);
1231                 return NULL;
1232         }
1233
1234         /* set image offset and reference grid */
1235         image->x0 = parameters->image_offset_x0;
1236         image->y0 = parameters->image_offset_y0;
1237         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1238         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1239
1240         /* set image data */
1241
1242         if ((value == '2') || (value == '3')) { /* ASCII */
1243                 for (i = 0; i < w * h; i++) {
1244                         for(compno = 0; compno < numcomps; compno++) {
1245                                 unsigned int index = 0;
1246                                 fscanf(f, "%u", &index);
1247                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1248                                 image->comps[compno].data[i] = index;
1249                         }
1250                 }
1251         } else if ((value == '5') || (value == '6')) {  /* BINARY */
1252                 for (i = 0; i < w * h; i++) {
1253                         for(compno = 0; compno < numcomps; compno++) {
1254                                 unsigned char index = 0;
1255                                 fread(&index, 1, 1, f);
1256                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1257                                 image->comps[compno].data[i] = index;
1258                         }
1259                 }
1260         }
1261
1262         fclose(f);
1263
1264         return image;
1265 }
1266
1267 int imagetopnm(opj_image_t * image, const char *outfile) {
1268         int w, wr, h, hr, max;
1269         int i, compno;
1270         int adjustR, adjustG, adjustB, adjustX;
1271         FILE *fdest = NULL;
1272         char S2;
1273         const char *tmp = outfile;
1274
1275         while (*tmp) {
1276                 tmp++;
1277         }
1278         tmp--;
1279         tmp--;
1280         S2 = *tmp;
1281
1282         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1283                 && image->comps[1].dx == image->comps[2].dx
1284                 && image->comps[0].dy == image->comps[1].dy
1285                 && image->comps[1].dy == image->comps[2].dy
1286                 && image->comps[0].prec == image->comps[1].prec
1287                 && image->comps[1].prec == image->comps[2].prec
1288                 && S2 !='g' && S2 !='G') {
1289
1290                 fdest = fopen(outfile, "wb");
1291                 if (!fdest) {
1292                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1293                         return 1;
1294                 }
1295
1296                 w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
1297                 wr = image->comps[0].w;
1298         
1299                 h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
1300                 hr = image->comps[0].h;
1301             
1302                 max = image->comps[0].prec > 8 ? 255 : (1 << image->comps[0].prec) - 1;
1303             
1304                 image->comps[0].x0 = int_ceildivpow2(image->comps[0].x0 - int_ceildiv(image->x0, image->comps[0].dx), image->comps[0].factor);
1305                 image->comps[0].y0 = int_ceildivpow2(image->comps[0].y0 -       int_ceildiv(image->y0, image->comps[0].dy), image->comps[0].factor);
1306
1307                 fprintf(fdest, "P6\n%d %d\n%d\n", wr, hr, max);
1308
1309                 if (image->comps[0].prec > 8) {
1310                         adjustR = image->comps[0].prec - 8;
1311                         printf("PNM CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1312                 }
1313                 else 
1314                         adjustR = 0;
1315                 if (image->comps[1].prec > 8) {
1316                         adjustG = image->comps[1].prec - 8;
1317                         printf("PNM CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1318                 }
1319                 else 
1320                         adjustG = 0;
1321                 if (image->comps[2].prec > 8) {
1322                         adjustB = image->comps[2].prec - 8;
1323                         printf("PNM CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1324                 }
1325                 else 
1326                         adjustB = 0;
1327
1328
1329                 for (i = 0; i < wr * hr; i++) {
1330                         int r, g, b;
1331                         unsigned char rc,gc,bc;
1332                         r = image->comps[0].data[i];
1333                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1334                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
1335
1336                         g = image->comps[1].data[i];
1337                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1338                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
1339                         
1340                         b = image->comps[2].data[i];
1341                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1342                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
1343                         
1344                         fprintf(fdest, "%c%c%c", rc, gc, bc);
1345                 }
1346                 fclose(fdest);
1347
1348         } else {
1349                 int ncomp=(S2=='g' || S2=='G')?1:image->numcomps;
1350                 if (image->numcomps > ncomp) {
1351                         fprintf(stderr,"WARNING -> [PGM files] Only the first component\n");
1352                         fprintf(stderr,"           is written to the file\n");
1353                 }
1354                 for (compno = 0; compno < ncomp; compno++) {
1355                         char name[256];
1356                         if (ncomp > 1) {
1357                                 sprintf(name, "%d.%s", compno, outfile);
1358                         } else {
1359                                 sprintf(name, "%s", outfile);
1360                         }
1361                         
1362                         fdest = fopen(name, "wb");
1363                         if (!fdest) {
1364                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1365                                 return 1;
1366                         }
1367             
1368                         w = int_ceildiv(image->x1 - image->x0, image->comps[compno].dx);
1369                         wr = image->comps[compno].w;
1370                         
1371                         h = int_ceildiv(image->y1 - image->y0, image->comps[compno].dy);
1372                         hr = image->comps[compno].h;
1373                         
1374                         max = image->comps[compno].prec > 8 ? 255 : (1 << image->comps[compno].prec) - 1;
1375                         
1376                         image->comps[compno].x0 = int_ceildivpow2(image->comps[compno].x0 - int_ceildiv(image->x0, image->comps[compno].dx), image->comps[compno].factor);
1377                         image->comps[compno].y0 = int_ceildivpow2(image->comps[compno].y0 - int_ceildiv(image->y0, image->comps[compno].dy), image->comps[compno].factor);
1378                         
1379                         fprintf(fdest, "P5\n%d %d\n%d\n", wr, hr, max);
1380                         
1381                         if (image->comps[compno].prec > 8) {
1382                                 adjustX = image->comps[0].prec - 8;
1383                                 printf("PNM CONVERSION: Truncating component %d from %d bits to 8 bits\n",compno, image->comps[compno].prec);
1384                         }
1385                         else 
1386                                 adjustX = 0;
1387                         
1388                         for (i = 0; i < wr * hr; i++) {
1389                                 int l;
1390                                 unsigned char lc;
1391                                 l = image->comps[compno].data[i];
1392                                 l += (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1393                                 lc = (unsigned char) ((l >> adjustX)+((l >> (adjustX-1))%2));
1394                                 fprintf(fdest, "%c", lc);
1395                         }
1396                         fclose(fdest);
1397                 }
1398         }
1399
1400         return 0;
1401 }
1402
1403 /* -->> -->> -->> -->>
1404
1405         TIFF IMAGE FORMAT
1406
1407  <<-- <<-- <<-- <<-- */
1408
1409 typedef struct tiff_infoheader{
1410         DWORD tiWidth;  // Width of Image in pixel
1411         DWORD tiHeight; // Height of Image in pixel
1412         DWORD tiPhoto;  // Photometric
1413         WORD  tiBps;    // Bits per sample
1414         WORD  tiSf;             // Sample Format
1415         WORD  tiSpp;    // Sample per pixel 1-bilevel,gray scale , 2- RGB
1416         WORD  tiPC;     // Planar config (1-Interleaved, 2-Planarcomp)
1417 }tiff_infoheader_t;
1418
1419 int imagetotif(opj_image_t * image, const char *outfile) {
1420         int width, height, imgsize;
1421         int bps,index,adjust = 0;
1422         int last_i=0;
1423         TIFF *tif;
1424         tdata_t buf;
1425         tstrip_t strip;
1426         tsize_t strip_size;
1427
1428         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1429                 && image->comps[1].dx == image->comps[2].dx
1430                 && image->comps[0].dy == image->comps[1].dy
1431                 && image->comps[1].dy == image->comps[2].dy
1432                 && image->comps[0].prec == image->comps[1].prec
1433                 && image->comps[1].prec == image->comps[2].prec) {
1434
1435                         /* -->> -->> -->>    
1436                         RGB color           
1437                         <<-- <<-- <<-- */
1438
1439                         tif = TIFFOpen(outfile, "wb"); 
1440                         if (!tif) {
1441                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1442                                 return 1;
1443                         }
1444
1445                         width   = image->comps[0].w;
1446                         height  = image->comps[0].h;
1447                         imgsize = width * height ;
1448                         bps             = image->comps[0].prec;
1449                         /* Set tags */
1450                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1451                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1452                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
1453                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1454                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1455                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1456                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1457                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1458
1459                         /* Get a buffer for the data */
1460                         strip_size=TIFFStripSize(tif);
1461                         buf = _TIFFmalloc(strip_size);
1462                         index=0;                
1463                         adjust = image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0;
1464                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1465                                 unsigned char *dat8;
1466                                 int i, ssize;
1467                                 ssize = TIFFStripSize(tif);
1468                                 dat8 = (unsigned char*)buf;
1469                                 if (image->comps[0].prec == 8){
1470                                         for (i=0; i<ssize-2; i+=3) {    // 8 bits per pixel 
1471                                                 int r = 0,g = 0,b = 0;
1472                                                 if(index < imgsize){
1473                                                         r = image->comps[0].data[index];
1474                                                         g = image->comps[1].data[index];
1475                                                         b = image->comps[2].data[index];
1476                                                         if (image->comps[0].sgnd){                      
1477                                                                 r += adjust;
1478                                                                 g += adjust;
1479                                                                 b += adjust;
1480                                                         }
1481                                                         dat8[i+0] = r ; // R 
1482                                                         dat8[i+1] = g ; // G 
1483                                                         dat8[i+2] = b ; // B 
1484                                                         index++;
1485                                                         last_i = i+3;
1486                                                 }else
1487                                                         break;
1488                                         }
1489                                         if(last_i < ssize){
1490                                                 for (i=last_i; i<ssize; i+=3) { // 8 bits per pixel 
1491                                                         int r = 0,g = 0,b = 0;
1492                                                         if(index < imgsize){
1493                                                                 r = image->comps[0].data[index];
1494                                                                 g = image->comps[1].data[index];
1495                                                                 b = image->comps[2].data[index];
1496                                                                 if (image->comps[0].sgnd){                      
1497                                                                         r += adjust;
1498                                                                         g += adjust;
1499                                                                         b += adjust;
1500                                                                 }
1501                                                                 dat8[i+0] = r ; // R 
1502                                                                 if(i+1 <ssize) dat8[i+1] = g ;  else break;// G 
1503                                                                 if(i+2 <ssize) dat8[i+2] = b ;  else break;// B 
1504                                                                 index++;
1505                                                         }else
1506                                                                 break;
1507                                                 }
1508                                         }
1509                                 }else if (image->comps[0].prec == 12){
1510                                         for (i=0; i<ssize-8; i+=9) {    // 12 bits per pixel 
1511                                                 int r = 0,g = 0,b = 0;
1512                                                 int r1 = 0,g1 = 0,b1 = 0;
1513                                                 if((index < imgsize)&(index+1 < imgsize)){
1514                                                         r  = image->comps[0].data[index];
1515                                                         g  = image->comps[1].data[index];
1516                                                         b  = image->comps[2].data[index];
1517                                                         r1 = image->comps[0].data[index+1];
1518                                                         g1 = image->comps[1].data[index+1];
1519                                                         b1 = image->comps[2].data[index+1];
1520                                                         if (image->comps[0].sgnd){                                                                                                              
1521                                                                 r  += adjust;
1522                                                                 g  += adjust;
1523                                                                 b  += adjust;
1524                                                                 r1 += adjust;
1525                                                                 g1 += adjust;
1526                                                                 b1 += adjust;
1527                                                         }
1528                                                         dat8[i+0] = (r >> 4);
1529                                                         dat8[i+1] = ((r & 0x0f) << 4 )|((g >> 8)& 0x0f);
1530                                                         dat8[i+2] = g ;         
1531                                                         dat8[i+3] = (b >> 4);
1532                                                         dat8[i+4] = ((b & 0x0f) << 4 )|((r1 >> 8)& 0x0f);
1533                                                         dat8[i+5] = r1;         
1534                                                         dat8[i+6] = (g1 >> 4);
1535                                                         dat8[i+7] = ((g1 & 0x0f)<< 4 )|((b1 >> 8)& 0x0f);
1536                                                         dat8[i+8] = b1;
1537                                                         index+=2;
1538                                                         last_i = i+9;
1539                                                 }else
1540                                                         break;
1541                                         }
1542                                         if(last_i < ssize){
1543                                                 for (i= last_i; i<ssize; i+=9) {        // 12 bits per pixel 
1544                                                         int r = 0,g = 0,b = 0;
1545                                                         int r1 = 0,g1 = 0,b1 = 0;
1546                                                         if((index < imgsize)&(index+1 < imgsize)){
1547                                                                 r  = image->comps[0].data[index];
1548                                                                 g  = image->comps[1].data[index];
1549                                                                 b  = image->comps[2].data[index];
1550                                                                 r1 = image->comps[0].data[index+1];
1551                                                                 g1 = image->comps[1].data[index+1];
1552                                                                 b1 = image->comps[2].data[index+1];
1553                                                                 if (image->comps[0].sgnd){                                                                                                              
1554                                                                         r  += adjust;
1555                                                                         g  += adjust;
1556                                                                         b  += adjust;
1557                                                                         r1 += adjust;
1558                                                                         g1 += adjust;
1559                                                                         b1 += adjust;
1560                                                                 }
1561                                                                 dat8[i+0] = (r >> 4);
1562                                                                 if(i+1 <ssize) dat8[i+1] = ((r & 0x0f) << 4 )|((g >> 8)& 0x0f); else break;
1563                                                                 if(i+2 <ssize) dat8[i+2] = g ;                  else break;
1564                                                                 if(i+3 <ssize) dat8[i+3] = (b >> 4);    else break;
1565                                                                 if(i+4 <ssize) dat8[i+4] = ((b & 0x0f) << 4 )|((r1 >> 8)& 0x0f);else break;
1566                                                                 if(i+5 <ssize) dat8[i+5] = r1;                  else break;
1567                                                                 if(i+6 <ssize) dat8[i+6] = (g1 >> 4);   else break;
1568                                                                 if(i+7 <ssize) dat8[i+7] = ((g1 & 0x0f)<< 4 )|((b1 >> 8)& 0x0f);else break;
1569                                                                 if(i+8 <ssize) dat8[i+8] = b1;                  else break;
1570                                                                 index+=2;
1571                                                         }else
1572                                                                 break;
1573                                                 }
1574                                         }
1575                                 }else if (image->comps[0].prec == 16){
1576                                         for (i=0 ; i<ssize-5 ; i+=6) {  // 16 bits per pixel 
1577                                                 int r = 0,g = 0,b = 0;
1578                                                 if(index < imgsize){
1579                                                         r = image->comps[0].data[index];
1580                                                         g = image->comps[1].data[index];
1581                                                         b = image->comps[2].data[index];
1582                                                         if (image->comps[0].sgnd){
1583                                                         r += adjust;
1584                                                         g += adjust;
1585                                                         b += adjust;
1586                                                         }
1587                                                         dat8[i+0] =  r;//LSB
1588                                                         dat8[i+1] = (r >> 8);//MSB       
1589                                                         dat8[i+2] =  g;         
1590                                                         dat8[i+3] = (g >> 8);
1591                                                         dat8[i+4] =  b; 
1592                                                         dat8[i+5] = (b >> 8);
1593                                                         index++;
1594                                                         last_i = i+6;
1595                                                 }else
1596                                                         break; 
1597                                         }
1598                                         if(last_i < ssize){
1599                                                 for (i=0 ; i<ssize ; i+=6) {    // 16 bits per pixel 
1600                                                         int r = 0,g = 0,b = 0;
1601                                                         if(index < imgsize){
1602                                                                 r = image->comps[0].data[index];
1603                                                                 g = image->comps[1].data[index];
1604                                                                 b = image->comps[2].data[index];
1605                                                                 if (image->comps[0].sgnd){
1606                                                                         r += adjust;
1607                                                                         g += adjust;
1608                                                                         b += adjust;
1609                                                                 }
1610                                                                 dat8[i+0] =  r;//LSB
1611                                                                 if(i+1 <ssize) dat8[i+1] = (r >> 8);else break;//MSB     
1612                                                                 if(i+2 <ssize) dat8[i+2] =  g;          else break;
1613                                                                 if(i+3 <ssize) dat8[i+3] = (g >> 8);else break;
1614                                                                 if(i+4 <ssize) dat8[i+4] =  b;          else break;
1615                                                                 if(i+5 <ssize) dat8[i+5] = (b >> 8);else break;
1616                                                                 index++;
1617                                                         }else
1618                                                                 break; 
1619                                                 }                                               
1620                                         }
1621                                 }else{
1622                                         fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1623                                         fprintf(stderr,"Aborting\n");
1624                                         return 1;
1625                                 }
1626                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1627                         }
1628                         _TIFFfree(buf);
1629                         TIFFClose(tif);
1630                 }else if (image->numcomps == 1){
1631                         /* -->> -->> -->>    
1632                         Black and White     
1633                         <<-- <<-- <<-- */
1634
1635                         tif = TIFFOpen(outfile, "wb"); 
1636                         if (!tif) {
1637                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1638                                 return 1;
1639                         }
1640
1641                         width   = image->comps[0].w;
1642                         height  = image->comps[0].h;
1643                         imgsize = width * height;
1644                         bps             = image->comps[0].prec;
1645
1646                         /* Set tags */
1647                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1648                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1649                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1650                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1651                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1652                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1653                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1654                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1655
1656                         /* Get a buffer for the data */
1657                         strip_size = TIFFStripSize(tif);
1658                         buf = _TIFFmalloc(strip_size);
1659                         index = 0;                      
1660                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1661                                 unsigned char *dat8;
1662                                 int i;
1663                                 dat8 = (unsigned char*)buf;
1664                                 if (image->comps[0].prec == 8){
1665                                         for (i=0; i<TIFFStripSize(tif); i+=1) { // 8 bits per pixel 
1666                                                 if(index < imgsize){
1667                                                         int r = 0;
1668                                                         r = image->comps[0].data[index];
1669                                                         if (image->comps[0].sgnd){
1670                                                                 r  += adjust;
1671                                                         }
1672                                                         dat8[i+0] = r;
1673                                                         index++;
1674                                                 }else
1675                                                         break; 
1676                                         }
1677                                 }else if (image->comps[0].prec == 12){
1678                                         for (i = 0; i<TIFFStripSize(tif); i+=3) {       // 12 bits per pixel 
1679                                                 if(index < imgsize){
1680                                                         int r = 0, r1 = 0;
1681                                                         r  = image->comps[0].data[index];
1682                                                         r1 = image->comps[0].data[index+1];
1683                                                         if (image->comps[0].sgnd){
1684                                                                 r  += adjust;
1685                                                                 r1 += adjust;
1686                                                         }
1687                                                         dat8[i+0] = (r >> 4);
1688                                                         dat8[i+1] = ((r & 0x0f) << 4 )|((r1 >> 8)& 0x0f);
1689                                                         dat8[i+2] = r1 ;
1690                                                         index+=2;
1691                                                 }else
1692                                                         break; 
1693                                         }
1694                                 }else if (image->comps[0].prec == 16){
1695                                         for (i=0; i<TIFFStripSize(tif); i+=2) { // 16 bits per pixel 
1696                                                 if(index < imgsize){
1697                                                         int r = 0;
1698                                                         r = image->comps[0].data[index];
1699                                                         if (image->comps[0].sgnd){
1700                                                                 r  += adjust;
1701                                                         }
1702                                                         dat8[i+0] = r;
1703                                                         dat8[i+1] = r >> 8;
1704                                                         index++;
1705                                                 }else
1706                                                         break; 
1707                                         }
1708                                 }else{
1709                                         fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1710                                         fprintf(stderr,"Aborting\n");
1711                                         return 1;
1712                                 }
1713                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1714                         }
1715                         _TIFFfree(buf);
1716                         TIFFClose(tif);
1717                 }else{
1718                         fprintf(stderr,"TIFF file creation. Bad color format. Only RGB & Grayscale has been implemented\n");
1719                         fprintf(stderr,"Aborting\n");
1720                         return 1;
1721                 }
1722                 return 0;
1723 }
1724
1725 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1726 {
1727         int subsampling_dx = parameters->subsampling_dx;
1728         int subsampling_dy = parameters->subsampling_dy;
1729         TIFF *tif;
1730         tiff_infoheader_t Info;
1731         tdata_t buf;
1732         tstrip_t strip;
1733         tsize_t strip_size;
1734         int j, numcomps, w, h,index;
1735         OPJ_COLOR_SPACE color_space;
1736         opj_image_cmptparm_t cmptparm[3];
1737         opj_image_t * image = NULL;
1738         int imgsize = 0;
1739
1740         tif = TIFFOpen(filename, "r");
1741
1742         if (!tif) {
1743                 fprintf(stderr, "Failed to open %s for reading\n", filename);
1744                 return 0;
1745         }
1746
1747         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
1748         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
1749         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
1750         TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
1751         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
1752         Info.tiPhoto = 0;
1753         TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
1754         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
1755         w= Info.tiWidth;
1756         h= Info.tiHeight;
1757         
1758         if (Info.tiPhoto == 2) { 
1759                 /* -->> -->> -->>    
1760                 RGB color           
1761                 <<-- <<-- <<-- */
1762
1763                 numcomps = 3;
1764                 color_space = CLRSPC_SRGB;
1765                 /* initialize image components*/ 
1766                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1767                 for(j = 0; j < numcomps; j++) {
1768                         if (parameters->cp_cinema) {
1769                                 cmptparm[j].prec = 12;
1770                                 cmptparm[j].bpp = 12;
1771                         }else{
1772                                 cmptparm[j].prec = Info.tiBps;
1773                                 cmptparm[j].bpp = Info.tiBps;
1774                         }
1775                         cmptparm[j].sgnd = 0;
1776                         cmptparm[j].dx = subsampling_dx;
1777                         cmptparm[j].dy = subsampling_dy;
1778                         cmptparm[j].w = w;
1779                         cmptparm[j].h = h;
1780                 }
1781                 /* create the image*/ 
1782                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1783                 if(!image) {
1784                         TIFFClose(tif);
1785                         return NULL;
1786                 }
1787
1788                 /* set image offset and reference grid */
1789                 image->x0 = parameters->image_offset_x0;
1790                 image->y0 = parameters->image_offset_y0;
1791                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1792                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1793
1794                 buf = _TIFFmalloc(TIFFStripSize(tif));
1795                 strip_size=0;
1796                 strip_size=TIFFStripSize(tif);
1797                 index = 0;
1798                 imgsize = image->comps[0].w * image->comps[0].h ;
1799                 /* Read the Image components*/
1800                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1801                         unsigned char *dat8;
1802                         int i, ssize;
1803                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1804                         dat8 = (unsigned char*)buf;
1805
1806                         if (Info.tiBps==12){
1807                                 for (i=0; i<ssize; i+=9) {      /*12 bits per pixel*/
1808                                         if((index < imgsize)&(index+1 < imgsize)){
1809                                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )                |(dat8[i+1]>>4);
1810                                                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
1811                                                 image->comps[2].data[index]   = ( dat8[i+3]<<4)                 |(dat8[i+4]>>4);
1812                                                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
1813                                                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)                |(dat8[i+7]>>4);
1814                                                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
1815                                                 index+=2;
1816                                         }else
1817                                                 break;
1818                                 }
1819                         }
1820                         else if( Info.tiBps==16){
1821                                 for (i=0; i<ssize; i+=6) {      /* 16 bits per pixel */
1822                                         if(index < imgsize){
1823                                                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; // R 
1824                                                 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; // G 
1825                                                 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; // B 
1826                                                 if(parameters->cp_cinema){/* Rounding to 12 bits*/
1827                                                         image->comps[0].data[index] = (image->comps[0].data[index] + 0x08) >> 4 ;
1828                                                         image->comps[1].data[index] = (image->comps[1].data[index] + 0x08) >> 4 ;
1829                                                         image->comps[2].data[index] = (image->comps[2].data[index] + 0x08) >> 4 ;
1830                                                 }
1831                                                 index++;
1832                                         }else
1833                                                 break;
1834                                 }
1835                         }
1836                         else if ( Info.tiBps==8){
1837                                 for (i=0; i<ssize; i+=3) {      /* 8 bits per pixel */
1838                                         if(index < imgsize){
1839                                                 image->comps[0].data[index] = dat8[i+0];// R 
1840                                                 image->comps[1].data[index] = dat8[i+1];// G 
1841                                                 image->comps[2].data[index] = dat8[i+2];// B 
1842                                                 if(parameters->cp_cinema){/* Rounding to 12 bits*/
1843                                                         image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
1844                                                         image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
1845                                                         image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
1846                                                 }
1847                                                 index++;
1848                                         }else
1849                                                 break;
1850                                 }
1851                         }
1852                         else{
1853                                 fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1854                                 fprintf(stderr,"Aborting\n");
1855                                 return NULL;
1856                         }
1857                 }
1858
1859                 _TIFFfree(buf);
1860                 TIFFClose(tif);
1861         }else if(Info.tiPhoto == 1) { 
1862                 /* -->> -->> -->>    
1863                 Black and White
1864                 <<-- <<-- <<-- */
1865
1866                 numcomps = 1;
1867                 color_space = CLRSPC_GRAY;
1868                 /* initialize image components*/ 
1869                 memset(&cmptparm[0], 0, sizeof(opj_image_cmptparm_t));
1870                 cmptparm[0].prec = Info.tiBps;
1871                 cmptparm[0].bpp = Info.tiBps;
1872                 cmptparm[0].sgnd = 0;
1873                 cmptparm[0].dx = subsampling_dx;
1874                 cmptparm[0].dy = subsampling_dy;
1875                 cmptparm[0].w = w;
1876                 cmptparm[0].h = h;
1877
1878                 /* create the image*/ 
1879                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1880                 if(!image) {
1881                         TIFFClose(tif);
1882                         return NULL;
1883                 }
1884                 /* set image offset and reference grid */
1885                 image->x0 = parameters->image_offset_x0;
1886                 image->y0 = parameters->image_offset_y0;
1887                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1888                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1889
1890                 buf = _TIFFmalloc(TIFFStripSize(tif));
1891                 strip_size = 0;
1892                 strip_size = TIFFStripSize(tif);
1893                 index = 0;
1894                 imgsize = image->comps[0].w * image->comps[0].h ;
1895                 /* Read the Image components*/
1896                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1897                         unsigned char *dat8;
1898                         int i, ssize;
1899                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1900                         dat8 = (unsigned char*)buf;
1901
1902                         if (Info.tiBps==12){
1903                                 for (i=0; i<ssize; i+=3) {      /* 12 bits per pixel*/
1904                                         if(index < imgsize){
1905                                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )                |(dat8[i+1]>>4) ;
1906                                                 image->comps[0].data[index+1] = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
1907                                                 index+=2;
1908                                         }else
1909                                                 break;
1910                                 }
1911                         }
1912                         else if( Info.tiBps==16){
1913                                 for (i=0; i<ssize; i+=2) {      /* 16 bits per pixel */
1914                                         if(index < imgsize){
1915                                                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
1916                                                 index++;
1917                                         }else
1918                                                 break;
1919                                 }
1920                         }
1921                         else if ( Info.tiBps==8){
1922                                 for (i=0; i<ssize; i+=1) {      /* 8 bits per pixel */
1923                                         if(index < imgsize){
1924                                                 image->comps[0].data[index] = dat8[i+0];
1925                                                 index++;
1926                                         }else
1927                                                 break;
1928                                 }
1929                         }
1930                         else{
1931                                 fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1932                                 fprintf(stderr,"Aborting\n");
1933                                 return NULL;
1934                         }
1935                 }
1936
1937                 _TIFFfree(buf);
1938                 TIFFClose(tif);
1939         }else{
1940                 fprintf(stderr,"TIFF file creation. Bad color format. Only RGB & Grayscale has been implemented\n");
1941                 fprintf(stderr,"Aborting\n");
1942                 return NULL;
1943         }
1944         return image;
1945 }
1946
1947 /* -->> -->> -->> -->>
1948
1949         RAW IMAGE FORMAT
1950
1951  <<-- <<-- <<-- <<-- */
1952
1953 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1954         int subsampling_dx = parameters->subsampling_dx;
1955         int subsampling_dy = parameters->subsampling_dy;
1956
1957         FILE *f = NULL;
1958         int i, compno, numcomps, w, h;
1959         OPJ_COLOR_SPACE color_space;
1960         opj_image_cmptparm_t *cmptparm; 
1961         opj_image_t * image = NULL;
1962         unsigned short ch;
1963         
1964         if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
1965         {
1966                 fprintf(stderr,"\nError: invalid raw image parameters\n");
1967                 fprintf(stderr,"Please use the Format option -F:\n");
1968                 fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1969                 fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1970                 fprintf(stderr,"Aborting\n");
1971                 return NULL;
1972         }
1973
1974         f = fopen(filename, "rb");
1975         if (!f) {
1976                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1977                 fprintf(stderr,"Aborting\n");
1978                 return NULL;
1979         }
1980         numcomps = raw_cp->rawComp;
1981         color_space = CLRSPC_SRGB;
1982         w = raw_cp->rawWidth;
1983         h = raw_cp->rawHeight;
1984         cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
1985         
1986         /* initialize image components */       
1987         memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1988         for(i = 0; i < numcomps; i++) {         
1989                 cmptparm[i].prec = raw_cp->rawBitDepth;
1990                 cmptparm[i].bpp = raw_cp->rawBitDepth;
1991                 cmptparm[i].sgnd = raw_cp->rawSigned;
1992                 cmptparm[i].dx = subsampling_dx;
1993                 cmptparm[i].dy = subsampling_dy;
1994                 cmptparm[i].w = w;
1995                 cmptparm[i].h = h;
1996         }
1997         /* create the image */
1998         image = opj_image_create(numcomps, &cmptparm[0], color_space);
1999         if(!image) {
2000                 fclose(f);
2001                 return NULL;
2002         }
2003         /* set image offset and reference grid */
2004         image->x0 = parameters->image_offset_x0;
2005         image->y0 = parameters->image_offset_y0;
2006         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
2007         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
2008
2009         if(raw_cp->rawBitDepth <= 8)
2010         {
2011                 unsigned char value = 0;
2012                 for(compno = 0; compno < numcomps; compno++) {
2013                         for (i = 0; i < w * h; i++) {
2014                                 if (!fread(&value, 1, 1, f)) {
2015                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2016                                         return NULL;
2017                                 }
2018                                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2019                         }
2020                 }
2021         }
2022         else if(raw_cp->rawBitDepth <= 16)
2023         {
2024                 unsigned short value;
2025                 for(compno = 0; compno < numcomps; compno++) {
2026                         for (i = 0; i < w * h; i++) {
2027                                 unsigned char temp;
2028                                 if (!fread(&temp, 1, 1, f)) {
2029                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2030                                         return NULL;
2031                                 }
2032                                 value = temp << 8;
2033                                 if (!fread(&temp, 1, 1, f)) {
2034                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2035                                         return NULL;
2036                                 }
2037                                 value += temp;
2038                                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2039                         }
2040                 }
2041         }
2042         else {
2043                 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2044                 return NULL;
2045         }
2046
2047         if (fread(&ch, 1, 1, f)) {
2048                 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2049         }
2050         fclose(f);
2051
2052         return image;
2053 }
2054
2055 int imagetoraw(opj_image_t * image, const char *outfile)
2056 {
2057         FILE *rawFile = NULL;
2058         int compno;
2059         int w, h;
2060         int line, row;
2061         int *ptr;
2062
2063         if((image->numcomps * image->x1 * image->y1) == 0)
2064         {
2065                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2066                 return 1;
2067         }
2068
2069         rawFile = fopen(outfile, "wb");
2070         if (!rawFile) {
2071                 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2072                 return 1;
2073         }
2074
2075         fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2076
2077         for(compno = 0; compno < image->numcomps; compno++)
2078         {
2079                 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2080                         image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2081
2082                 w = image->comps[compno].w;
2083                 h = image->comps[compno].h;
2084
2085                 if(image->comps[compno].prec <= 8)
2086                 {
2087                         if(image->comps[compno].sgnd == 1)
2088                         {
2089                                 signed char curr;
2090                                 int mask = (1 << image->comps[compno].prec) - 1;
2091                                 ptr = image->comps[compno].data;
2092                                 for (line = 0; line < h; line++) {
2093                                         for(row = 0; row < w; row++)    {                               
2094                                                 curr = (signed char) (*ptr & mask);
2095                                                 fwrite(&curr, sizeof(signed char), 1, rawFile);
2096                                                 ptr++;
2097                                         }
2098                                 }
2099                         }
2100                         else if(image->comps[compno].sgnd == 0)
2101                         {
2102                                 unsigned char curr;
2103                                 int mask = (1 << image->comps[compno].prec) - 1;
2104                                 ptr = image->comps[compno].data;
2105                                 for (line = 0; line < h; line++) {
2106                                         for(row = 0; row < w; row++)    {       
2107                                                 curr = (unsigned char) (*ptr & mask);
2108                                                 fwrite(&curr, sizeof(unsigned char), 1, rawFile);
2109                                                 ptr++;
2110                                         }
2111                                 }
2112                         }
2113                 }
2114                 else if(image->comps[compno].prec <= 16)
2115                 {
2116                         if(image->comps[compno].sgnd == 1)
2117                         {
2118                                 signed short int curr;
2119                                 int mask = (1 << image->comps[compno].prec) - 1;
2120                                 ptr = image->comps[compno].data;
2121                                 for (line = 0; line < h; line++) {
2122                                         for(row = 0; row < w; row++)    {                                       
2123                                                 unsigned char temp;
2124                                                 curr = (signed short int) (*ptr & mask);                                                
2125                                                 temp = (unsigned char) (curr >> 8);
2126                                                 fwrite(&temp, 1, 1, rawFile);
2127                                                 temp = (unsigned char) curr;
2128                                                 fwrite(&temp, 1, 1, rawFile);
2129                                                 ptr++;
2130                                         }
2131                                 }
2132                         }
2133                         else if(image->comps[compno].sgnd == 0)
2134                         {
2135                                 unsigned short int curr;
2136                                 int mask = (1 << image->comps[compno].prec) - 1;
2137                                 ptr = image->comps[compno].data;
2138                                 for (line = 0; line < h; line++) {
2139                                         for(row = 0; row < w; row++)    {                               
2140                                                 unsigned char temp;
2141                                                 curr = (unsigned short int) (*ptr & mask);                                              
2142                                                 temp = (unsigned char) (curr >> 8);
2143                                                 fwrite(&temp, 1, 1, rawFile);
2144                                                 temp = (unsigned char) curr;
2145                                                 fwrite(&temp, 1, 1, rawFile);
2146                                                 ptr++;
2147                                         }
2148                                 }
2149                         }
2150                 }
2151                 else if (image->comps[compno].prec <= 32)
2152                 {
2153                         fprintf(stderr,"More than 16 bits per component no handled yet\n");
2154                         return 1;
2155                 }
2156                 else
2157                 {
2158                         fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2159                         return 1;
2160                 }
2161         }
2162         fclose(rawFile);
2163         return 0;
2164 }
2165
2166 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
2167 #ifdef WIN32
2168 {
2169         printf("Error. PNG format is not yet handled under windows\n");
2170         return NULL;
2171 }
2172 #else
2173 {
2174     png_bytep row;
2175     png_structp png;
2176     png_infop info;
2177     double gamma, display_exponent;
2178     int bit_depth, interlace_type, compression_type, filter_type;
2179     int unit, pass, nr_passes;
2180     png_uint_32 resx, resy;
2181     unsigned int i, max, src_w;
2182     png_uint_32 width, height;
2183     int color_type, has_alpha;
2184     unsigned char *png_buf, *s;
2185     FILE *reader;
2186 /* j2k: */
2187     opj_image_t *image;
2188     opj_image_cmptparm_t cmptparm[4];
2189     int sub_dx, sub_dy;
2190     unsigned int nr_comp;
2191     int *r, *g, *b, *a;
2192
2193     if ((reader = fopen(read_idf, "rb")) == NULL) {
2194         fprintf(stderr, "pngtoimage: can not open %s\n", read_idf);
2195         return NULL;
2196     }
2197     nr_passes = 0;
2198     png_buf = NULL;
2199
2200 /* libpng-VERSION/example.c: 
2201  * PC : screen_gamma = 2.2;
2202  * Mac: screen_gamma = 1.7 or 1.0;
2203 */
2204     display_exponent = 2.2;
2205
2206     if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
2207                                       NULL, NULL, NULL)) == NULL)
2208         goto fin;
2209     if ((info = png_create_info_struct(png)) == NULL)
2210         goto fin;
2211
2212     if (setjmp(png_jmpbuf(png)))
2213         goto fin;
2214
2215     png_init_io(png, reader);
2216     png_read_info(png, info);
2217
2218     png_get_IHDR(png, info, &width, &height,
2219                  &bit_depth, &color_type, &interlace_type,
2220                  &compression_type, &filter_type);
2221
2222     if (color_type == PNG_COLOR_TYPE_PALETTE)
2223         png_set_expand(png);
2224     else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
2225         png_set_expand(png);
2226
2227     if (png_get_valid(png, info, PNG_INFO_tRNS))
2228         png_set_expand(png);
2229
2230     if (bit_depth == 16)
2231         png_set_strip_16(png);
2232
2233 /* GRAY => RGB; GRAY_ALPHA => RGBA
2234 */
2235     if (color_type == PNG_COLOR_TYPE_GRAY
2236         || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
2237         png_set_gray_to_rgb(png);
2238         color_type =
2239             (color_type == PNG_COLOR_TYPE_GRAY ? PNG_COLOR_TYPE_RGB :
2240              PNG_COLOR_TYPE_RGB_ALPHA);
2241     }
2242     if (!png_get_gAMA(png, info, &gamma))
2243         gamma = 0.45455;
2244
2245     png_set_gamma(png, display_exponent, gamma);
2246
2247     nr_passes = png_set_interlace_handling(png);
2248
2249     png_read_update_info(png, info);
2250
2251     png_get_pHYs(png, info, &resx, &resy, &unit);
2252
2253     color_type = png_get_color_type(png, info);
2254
2255     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
2256
2257     if (has_alpha)
2258         nr_comp = 4;
2259     else
2260         nr_comp = 3;
2261
2262     src_w = width * nr_comp;
2263     png_buf = (unsigned char *) malloc(src_w * height);
2264
2265     if (nr_passes == 0)
2266         nr_passes = 1;
2267
2268     for (pass = 0; pass < nr_passes; pass++) {
2269         s = png_buf;
2270
2271         for (i = 0; i < height; i++) {
2272 /* libpng.3:
2273  * If you want the "sparkle" effect, just call png_read_rows() as
2274  * normal, with the third parameter NULL.
2275 */
2276             png_read_rows(png, &s, NULL, 1);
2277
2278             s += src_w;
2279         }
2280     }
2281     memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
2282
2283     sub_dx = params->subsampling_dx;
2284     sub_dy = params->subsampling_dy;
2285
2286     for (i = 0; i < nr_comp; ++i) {
2287         cmptparm[i].prec = 8;
2288         cmptparm[i].bpp = 8;
2289         cmptparm[i].sgnd = 0;
2290         cmptparm[i].dx = sub_dx;
2291         cmptparm[i].dy = sub_dy;
2292         cmptparm[i].w = width;
2293         cmptparm[i].h = height;
2294     }
2295
2296     image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
2297
2298     if (image == NULL)
2299         goto fin;
2300
2301     image->x0 = params->image_offset_x0;
2302     image->y0 = params->image_offset_y0;
2303     image->x1 =
2304         params->image_offset_x0 + (width - 1) * sub_dx + 1 + image->x0;
2305     image->y1 =
2306         params->image_offset_y0 + (height - 1) * sub_dy + 1 + image->y0;
2307
2308     r = image->comps[0].data;
2309     g = image->comps[1].data;
2310     b = image->comps[2].data;
2311     a = image->comps[3].data;
2312     s = png_buf;
2313
2314     max = width * height;
2315
2316     for (i = 0; i < max; ++i) {
2317         *r++ = *s++;
2318         *g++ = *s++;
2319         *b++ = *s++;
2320
2321         if (has_alpha)
2322             *a++ = *s++;
2323     }
2324
2325   fin:
2326     if (png)
2327         png_destroy_read_struct(&png, &info, NULL);
2328     if (png_buf)
2329         free(png_buf);
2330
2331     fclose(reader);
2332
2333     return image;
2334
2335 }                               /* pngtoimage() */
2336 #endif
2337
2338 int imagetopng(opj_image_t * image, const char *write_idf)
2339 #ifdef WIN32
2340 {
2341         printf("Error. PNG format is not yet handled under windows\n");
2342         return -1;
2343 }
2344 #else
2345 {
2346     FILE *writer;
2347     png_structp png_ptr;
2348     png_infop info_ptr;
2349     int *rs, *gs, *bs, *as;
2350     unsigned char *row_buf, *d;
2351     int fails, mono, graya, rgb, rgba;
2352     int width, height, nr_colors, color_type;
2353     int bit_depth, adjust, x, y;
2354     png_color_8 sig_bit;
2355
2356     writer = fopen(write_idf, "wb");
2357
2358     if (writer == NULL)
2359         return 1;
2360
2361     info_ptr = NULL;
2362     fails = 1;
2363
2364 /* Create and initialize the png_struct with the desired error handler
2365  * functions.  If you want to use the default stderr and longjump method,
2366  * you can supply NULL for the last three parameters.  We also check that
2367  * the library version is compatible with the one used at compile time,
2368  * in case we are using dynamically linked libraries.  REQUIRED.
2369 */
2370     png_ptr =
2371         png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2372 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2373
2374     if (png_ptr == NULL)
2375         goto fin;
2376
2377 /* Allocate/initialize the image information data.  REQUIRED 
2378 */
2379     info_ptr = png_create_info_struct(png_ptr);
2380
2381     if (info_ptr == NULL)
2382         goto fin;
2383
2384 /* Set error handling.  REQUIRED if you are not supplying your own
2385  * error handling functions in the png_create_write_struct() call.
2386 */
2387     if (setjmp(png_jmpbuf(png_ptr)))
2388         goto fin;
2389
2390 /* I/O initialization functions is REQUIRED 
2391 */
2392     png_init_io(png_ptr, writer);
2393
2394 /* Set the image information here.  Width and height are up to 2^31,
2395  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2396  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2397  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2398  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
2399  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2400  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
2401  * REQUIRED
2402 */
2403     png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
2404
2405     mono = graya = rgb = rgba = adjust = 0;
2406
2407     nr_colors = image->numcomps;
2408     width = image->comps[0].w;
2409     height = image->comps[0].h;
2410     rs = image->comps[0].data;
2411
2412     if (nr_colors == 2) {
2413         graya = 1;
2414         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
2415         sig_bit.gray = image->comps[0].prec;
2416         bit_depth = image->comps[0].prec;
2417         as = image->comps[1].data;
2418     } else if (nr_colors == 3) {
2419         rgb = 1;
2420         color_type = PNG_COLOR_TYPE_RGB;
2421         sig_bit.red = image->comps[0].prec;
2422         sig_bit.green = image->comps[1].prec;
2423         sig_bit.blue = image->comps[2].prec;
2424         bit_depth = image->comps[0].prec;
2425         gs = image->comps[1].data;
2426         bs = image->comps[2].data;
2427         if (image->comps[0].sgnd)
2428             adjust = 1 << (image->comps[0].prec - 1);
2429     } else if (nr_colors == 4) {
2430         rgb = rgba = 1;
2431         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2432         sig_bit.red = image->comps[0].prec;
2433         sig_bit.green = image->comps[1].prec;
2434         sig_bit.blue = image->comps[2].prec;
2435         sig_bit.alpha = image->comps[3].prec;
2436         bit_depth = image->comps[0].prec;
2437         gs = image->comps[1].data;
2438         bs = image->comps[2].data;
2439         as = image->comps[3].data;
2440         if (image->comps[0].sgnd)
2441             adjust = 1 << (image->comps[0].prec - 1);
2442     } else {
2443         mono = 1;
2444         color_type = PNG_COLOR_TYPE_GRAY;
2445         sig_bit.gray = image->comps[0].prec;
2446         bit_depth = image->comps[0].prec;
2447     }
2448     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2449
2450     png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
2451                  color_type,
2452                  PNG_INTERLACE_NONE,
2453                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2454
2455 #ifdef HIDDEN_CODE
2456 /* Optional gamma chunk is strongly suggested if you have any guess
2457  * as to the correct gamma of the image.
2458 */
2459
2460     if (gamma > 0.0) {
2461         png_set_gAMA(png_ptr, info_ptr, gamma);
2462     }
2463 #endif                          /* HIDDEN_CODE */
2464 #ifdef HIDDEN_CODE
2465     if (have_bg) {
2466         png_color_16 background;
2467
2468         background.red = bg_red;
2469         background.green = bg_green;
2470         background.blue = bg_blue;
2471
2472         png_set_bKGD(png_ptr, info_ptr, &background);
2473     }
2474 #endif                          /* HIDDEN_CODE */
2475     png_write_info(png_ptr, info_ptr);
2476
2477     png_set_packing(png_ptr);
2478
2479     row_buf = (unsigned char *) malloc(width * nr_colors);
2480
2481     for (y = 0; y < height; ++y) {
2482         d = row_buf;
2483
2484         for (x = 0; x < width; ++x) {
2485             if (mono) {
2486                 *d++ = (unsigned char) *rs++;
2487             }
2488             if (graya) {
2489                 *d++ = (unsigned char) *rs++;
2490                 *d++ = (unsigned char) *as++;
2491             } else if (rgb) {
2492                 *d++ = (unsigned char) (*rs++ + adjust);
2493                 *d++ = (unsigned char) (*gs++ + adjust);
2494                 *d++ = (unsigned char) (*bs++ + adjust);
2495
2496                 if (rgba)
2497                     *d++ = (unsigned char) (*as++ + adjust);
2498             }
2499         }                       /* for(x) */
2500
2501         png_write_row(png_ptr, row_buf);
2502
2503     }                           /* for(y) */
2504
2505     png_write_end(png_ptr, info_ptr);
2506
2507     fails = 0;
2508
2509   fin:
2510
2511     if (png_ptr) {
2512         png_destroy_write_struct(&png_ptr, &info_ptr);
2513     }
2514     fclose(writer);
2515
2516     return fails;
2517 }
2518 #endif