Start merging change from svn trunk
[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         unsigned 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                 }
924
925                 for (i = 0; i < 256; i++) {
926                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
927                 }
928
929                 for (i = 0; i < w * h; i++) {
930                         unsigned char rc;
931                         int r;
932                         
933                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
934                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
935                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
936                         
937                         fprintf(fdest, "%c", rc);
938
939                         if ((i + 1) % w == 0) {
940                                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
941                                         fprintf(fdest, "%c", 0);
942                         }
943                 }
944                 fclose(fdest);
945         }
946
947         return 0;
948 }
949
950 /* -->> -->> -->> -->>
951
952 PGX IMAGE FORMAT
953
954 <<-- <<-- <<-- <<-- */
955
956
957 unsigned char readuchar(FILE * f)
958 {
959   unsigned char c1;
960   fread(&c1, 1, 1, f);
961   return c1;
962 }
963
964 unsigned short readushort(FILE * f, int bigendian)
965 {
966   unsigned char c1, c2;
967   fread(&c1, 1, 1, f);
968   fread(&c2, 1, 1, f);
969   if (bigendian)
970     return (c1 << 8) + c2;
971   else
972     return (c2 << 8) + c1;
973 }
974
975 unsigned int readuint(FILE * f, int bigendian)
976 {
977   unsigned char c1, c2, c3, c4;
978   fread(&c1, 1, 1, f);
979   fread(&c2, 1, 1, f);
980   fread(&c3, 1, 1, f);
981   fread(&c4, 1, 1, f);
982   if (bigendian)
983     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
984   else
985     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
986 }
987
988 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
989         FILE *f = NULL;
990         int w, h, prec;
991         int i, numcomps, max;
992         OPJ_COLOR_SPACE color_space;
993         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
994         opj_image_t * image = NULL;
995
996         char endian1,endian2,sign;
997         char signtmp[32];
998
999         char temp[32];
1000         int bigendian;
1001         opj_image_comp_t *comp = NULL;
1002
1003         numcomps = 1;
1004         color_space = CLRSPC_GRAY;
1005
1006         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1007
1008         max = 0;
1009
1010         f = fopen(filename, "rb");
1011         if (!f) {
1012           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1013           return NULL;
1014         }
1015
1016         fseek(f, 0, SEEK_SET);
1017         fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
1018         
1019         i=0;
1020         sign='+';               
1021         while (signtmp[i]!='\0') {
1022                 if (signtmp[i]=='-') sign='-';
1023                 i++;
1024         }
1025         
1026         fgetc(f);
1027         if (endian1=='M' && endian2=='L') {
1028                 bigendian = 1;
1029         } else if (endian2=='M' && endian1=='L') {
1030                 bigendian = 0;
1031         } else {
1032                 fprintf(stderr, "Bad pgx header, please check input file\n");
1033                 return NULL;
1034         }
1035
1036         /* initialize image component */
1037
1038         cmptparm.x0 = parameters->image_offset_x0;
1039         cmptparm.y0 = parameters->image_offset_y0;
1040         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1041         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1042         
1043         if (sign == '-') {
1044                 cmptparm.sgnd = 1;
1045         } else {
1046                 cmptparm.sgnd = 0;
1047         }
1048         cmptparm.prec = prec;
1049         cmptparm.bpp = prec;
1050         cmptparm.dx = parameters->subsampling_dx;
1051         cmptparm.dy = parameters->subsampling_dy;
1052         
1053         /* create the image */
1054         image = opj_image_create(numcomps, &cmptparm, color_space);
1055         if(!image) {
1056                 fclose(f);
1057                 return NULL;
1058         }
1059         /* set image offset and reference grid */
1060         image->x0 = cmptparm.x0;
1061         image->y0 = cmptparm.x0;
1062         image->x1 = cmptparm.w;
1063         image->y1 = cmptparm.h;
1064
1065         /* set image data */
1066
1067         comp = &image->comps[0];
1068
1069         for (i = 0; i < w * h; i++) {
1070                 int v;
1071                 if (comp->prec <= 8) {
1072                         if (!comp->sgnd) {
1073                                 v = readuchar(f);
1074                         } else {
1075                                 v = (char) readuchar(f);
1076                         }
1077                 } else if (comp->prec <= 16) {
1078                         if (!comp->sgnd) {
1079                                 v = readushort(f, bigendian);
1080                         } else {
1081                                 v = (short) readushort(f, bigendian);
1082                         }
1083                 } else {
1084                         if (!comp->sgnd) {
1085                                 v = readuint(f, bigendian);
1086                         } else {
1087                                 v = (int) readuint(f, bigendian);
1088                         }
1089                 }
1090                 if (v > max)
1091                         max = v;
1092                 comp->data[i] = v;
1093         }
1094         fclose(f);
1095         //comp->bpp = int_floorlog2(max) + 1;
1096
1097         return image;
1098 }
1099
1100 int imagetopgx(opj_image_t * image, const char *outfile) {
1101         int w, h;
1102         int i, j;
1103   unsigned int 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;
1270   unsigned int compno;
1271         int adjustR, adjustG, adjustB, adjustX;
1272         FILE *fdest = NULL;
1273         char S2;
1274         const char *tmp = outfile;
1275
1276         while (*tmp) {
1277                 tmp++;
1278         }
1279         tmp--;
1280         tmp--;
1281         S2 = *tmp;
1282
1283         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1284                 && image->comps[1].dx == image->comps[2].dx
1285                 && image->comps[0].dy == image->comps[1].dy
1286                 && image->comps[1].dy == image->comps[2].dy
1287                 && image->comps[0].prec == image->comps[1].prec
1288                 && image->comps[1].prec == image->comps[2].prec
1289                 && S2 !='g' && S2 !='G') {
1290
1291                 fdest = fopen(outfile, "wb");
1292                 if (!fdest) {
1293                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1294                         return 1;
1295                 }
1296
1297                 w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
1298                 wr = image->comps[0].w;
1299         
1300                 h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
1301                 hr = image->comps[0].h;
1302             
1303                 max = image->comps[0].prec > 8 ? 255 : (1 << image->comps[0].prec) - 1;
1304             
1305                 image->comps[0].x0 = int_ceildivpow2(image->comps[0].x0 - int_ceildiv(image->x0, image->comps[0].dx), image->comps[0].factor);
1306                 image->comps[0].y0 = int_ceildivpow2(image->comps[0].y0 -       int_ceildiv(image->y0, image->comps[0].dy), image->comps[0].factor);
1307
1308                 fprintf(fdest, "P6\n%d %d\n%d\n", wr, hr, max);
1309
1310                 if (image->comps[0].prec > 8) {
1311                         adjustR = image->comps[0].prec - 8;
1312                         printf("PNM CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1313                 }
1314                 else 
1315                         adjustR = 0;
1316                 if (image->comps[1].prec > 8) {
1317                         adjustG = image->comps[1].prec - 8;
1318                         printf("PNM CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1319                 }
1320                 else 
1321                         adjustG = 0;
1322                 if (image->comps[2].prec > 8) {
1323                         adjustB = image->comps[2].prec - 8;
1324                         printf("PNM CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1325                 }
1326                 else 
1327                         adjustB = 0;
1328
1329
1330                 for (i = 0; i < wr * hr; i++) {
1331                         int r, g, b;
1332                         unsigned char rc,gc,bc;
1333                         r = image->comps[0].data[i];
1334                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1335                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
1336
1337                         g = image->comps[1].data[i];
1338                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1339                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
1340                         
1341                         b = image->comps[2].data[i];
1342                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1343                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
1344                         
1345                         fprintf(fdest, "%c%c%c", rc, gc, bc);
1346                 }
1347                 fclose(fdest);
1348
1349         } else {
1350                 unsigned int ncomp=(S2=='g' || S2=='G')?1:image->numcomps;
1351                 if (image->numcomps > ncomp) {
1352                         fprintf(stderr,"WARNING -> [PGM files] Only the first component\n");
1353                         fprintf(stderr,"           is written to the file\n");
1354                 }
1355                 for (compno = 0; compno < ncomp; compno++) {
1356                         char name[256];
1357                         if (ncomp > 1) {
1358                                 sprintf(name, "%d.%s", compno, outfile);
1359                         } else {
1360                                 sprintf(name, "%s", outfile);
1361                         }
1362                         
1363                         fdest = fopen(name, "wb");
1364                         if (!fdest) {
1365                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1366                                 return 1;
1367                         }
1368             
1369                         w = int_ceildiv(image->x1 - image->x0, image->comps[compno].dx);
1370                         wr = image->comps[compno].w;
1371                         
1372                         h = int_ceildiv(image->y1 - image->y0, image->comps[compno].dy);
1373                         hr = image->comps[compno].h;
1374                         
1375                         max = image->comps[compno].prec > 8 ? 255 : (1 << image->comps[compno].prec) - 1;
1376                         
1377                         image->comps[compno].x0 = int_ceildivpow2(image->comps[compno].x0 - int_ceildiv(image->x0, image->comps[compno].dx), image->comps[compno].factor);
1378                         image->comps[compno].y0 = int_ceildivpow2(image->comps[compno].y0 - int_ceildiv(image->y0, image->comps[compno].dy), image->comps[compno].factor);
1379                         
1380                         fprintf(fdest, "P5\n%d %d\n%d\n", wr, hr, max);
1381                         
1382                         if (image->comps[compno].prec > 8) {
1383                                 adjustX = image->comps[0].prec - 8;
1384                                 printf("PNM CONVERSION: Truncating component %d from %d bits to 8 bits\n",compno, image->comps[compno].prec);
1385                         }
1386                         else 
1387                                 adjustX = 0;
1388                         
1389                         for (i = 0; i < wr * hr; i++) {
1390                                 int l;
1391                                 unsigned char lc;
1392                                 l = image->comps[compno].data[i];
1393                                 l += (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1394                                 lc = (unsigned char) ((l >> adjustX)+((l >> (adjustX-1))%2));
1395                                 fprintf(fdest, "%c", lc);
1396                         }
1397                         fclose(fdest);
1398                 }
1399         }
1400
1401         return 0;
1402 }
1403
1404 /* -->> -->> -->> -->>
1405
1406         TIFF IMAGE FORMAT
1407
1408  <<-- <<-- <<-- <<-- */
1409
1410 typedef struct tiff_infoheader{
1411         DWORD tiWidth;  // Width of Image in pixel
1412         DWORD tiHeight; // Height of Image in pixel
1413         DWORD tiPhoto;  // Photometric
1414         WORD  tiBps;    // Bits per sample
1415         WORD  tiSf;             // Sample Format
1416         WORD  tiSpp;    // Sample per pixel 1-bilevel,gray scale , 2- RGB
1417         WORD  tiPC;     // Planar config (1-Interleaved, 2-Planarcomp)
1418 }tiff_infoheader_t;
1419
1420 int imagetotif(opj_image_t * image, const char *outfile) {
1421         int width, height, imgsize;
1422         int bps,index,adjust = 0;
1423         int last_i=0;
1424         TIFF *tif;
1425         tdata_t buf;
1426         tstrip_t strip;
1427         tsize_t strip_size;
1428
1429         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1430                 && image->comps[1].dx == image->comps[2].dx
1431                 && image->comps[0].dy == image->comps[1].dy
1432                 && image->comps[1].dy == image->comps[2].dy
1433                 && image->comps[0].prec == image->comps[1].prec
1434                 && image->comps[1].prec == image->comps[2].prec) {
1435
1436                         /* -->> -->> -->>    
1437                         RGB color           
1438                         <<-- <<-- <<-- */
1439
1440                         tif = TIFFOpen(outfile, "wb"); 
1441                         if (!tif) {
1442                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1443                                 return 1;
1444                         }
1445
1446                         width   = image->comps[0].w;
1447                         height  = image->comps[0].h;
1448                         imgsize = width * height ;
1449                         bps             = image->comps[0].prec;
1450                         /* Set tags */
1451                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1452                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1453                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
1454                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1455                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1456                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1457                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1458                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1459
1460                         /* Get a buffer for the data */
1461                         strip_size=TIFFStripSize(tif);
1462                         buf = _TIFFmalloc(strip_size);
1463                         index=0;                
1464                         adjust = image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0;
1465                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1466                                 unsigned char *dat8;
1467                                 int i, ssize;
1468                                 ssize = TIFFStripSize(tif);
1469                                 dat8 = (unsigned char*)buf;
1470                                 if (image->comps[0].prec == 8){
1471                                         for (i=0; i<ssize-2; i+=3) {    // 8 bits per pixel 
1472                                                 int r = 0,g = 0,b = 0;
1473                                                 if(index < imgsize){
1474                                                         r = image->comps[0].data[index];
1475                                                         g = image->comps[1].data[index];
1476                                                         b = image->comps[2].data[index];
1477                                                         if (image->comps[0].sgnd){                      
1478                                                                 r += adjust;
1479                                                                 g += adjust;
1480                                                                 b += adjust;
1481                                                         }
1482                                                         dat8[i+0] = r ; // R 
1483                                                         dat8[i+1] = g ; // G 
1484                                                         dat8[i+2] = b ; // B 
1485                                                         index++;
1486                                                         last_i = i+3;
1487                                                 }else
1488                                                         break;
1489                                         }
1490                                         if(last_i < ssize){
1491                                                 for (i=last_i; i<ssize; i+=3) { // 8 bits per pixel 
1492                                                         int r = 0,g = 0,b = 0;
1493                                                         if(index < imgsize){
1494                                                                 r = image->comps[0].data[index];
1495                                                                 g = image->comps[1].data[index];
1496                                                                 b = image->comps[2].data[index];
1497                                                                 if (image->comps[0].sgnd){                      
1498                                                                         r += adjust;
1499                                                                         g += adjust;
1500                                                                         b += adjust;
1501                                                                 }
1502                                                                 dat8[i+0] = r ; // R 
1503                                                                 if(i+1 <ssize) dat8[i+1] = g ;  else break;// G 
1504                                                                 if(i+2 <ssize) dat8[i+2] = b ;  else break;// B 
1505                                                                 index++;
1506                                                         }else
1507                                                                 break;
1508                                                 }
1509                                         }
1510                                 }else if (image->comps[0].prec == 12){
1511                                         for (i=0; i<ssize-8; i+=9) {    // 12 bits per pixel 
1512                                                 int r = 0,g = 0,b = 0;
1513                                                 int r1 = 0,g1 = 0,b1 = 0;
1514                                                 if((index < imgsize)&(index+1 < imgsize)){
1515                                                         r  = image->comps[0].data[index];
1516                                                         g  = image->comps[1].data[index];
1517                                                         b  = image->comps[2].data[index];
1518                                                         r1 = image->comps[0].data[index+1];
1519                                                         g1 = image->comps[1].data[index+1];
1520                                                         b1 = image->comps[2].data[index+1];
1521                                                         if (image->comps[0].sgnd){                                                                                                              
1522                                                                 r  += adjust;
1523                                                                 g  += adjust;
1524                                                                 b  += adjust;
1525                                                                 r1 += adjust;
1526                                                                 g1 += adjust;
1527                                                                 b1 += adjust;
1528                                                         }
1529                                                         dat8[i+0] = (r >> 4);
1530                                                         dat8[i+1] = ((r & 0x0f) << 4 )|((g >> 8)& 0x0f);
1531                                                         dat8[i+2] = g ;         
1532                                                         dat8[i+3] = (b >> 4);
1533                                                         dat8[i+4] = ((b & 0x0f) << 4 )|((r1 >> 8)& 0x0f);
1534                                                         dat8[i+5] = r1;         
1535                                                         dat8[i+6] = (g1 >> 4);
1536                                                         dat8[i+7] = ((g1 & 0x0f)<< 4 )|((b1 >> 8)& 0x0f);
1537                                                         dat8[i+8] = b1;
1538                                                         index+=2;
1539                                                         last_i = i+9;
1540                                                 }else
1541                                                         break;
1542                                         }
1543                                         if(last_i < ssize){
1544                                                 for (i= last_i; i<ssize; i+=9) {        // 12 bits per pixel 
1545                                                         int r = 0,g = 0,b = 0;
1546                                                         int r1 = 0,g1 = 0,b1 = 0;
1547                                                         if((index < imgsize)&(index+1 < imgsize)){
1548                                                                 r  = image->comps[0].data[index];
1549                                                                 g  = image->comps[1].data[index];
1550                                                                 b  = image->comps[2].data[index];
1551                                                                 r1 = image->comps[0].data[index+1];
1552                                                                 g1 = image->comps[1].data[index+1];
1553                                                                 b1 = image->comps[2].data[index+1];
1554                                                                 if (image->comps[0].sgnd){                                                                                                              
1555                                                                         r  += adjust;
1556                                                                         g  += adjust;
1557                                                                         b  += adjust;
1558                                                                         r1 += adjust;
1559                                                                         g1 += adjust;
1560                                                                         b1 += adjust;
1561                                                                 }
1562                                                                 dat8[i+0] = (r >> 4);
1563                                                                 if(i+1 <ssize) dat8[i+1] = ((r & 0x0f) << 4 )|((g >> 8)& 0x0f); else break;
1564                                                                 if(i+2 <ssize) dat8[i+2] = g ;                  else break;
1565                                                                 if(i+3 <ssize) dat8[i+3] = (b >> 4);    else break;
1566                                                                 if(i+4 <ssize) dat8[i+4] = ((b & 0x0f) << 4 )|((r1 >> 8)& 0x0f);else break;
1567                                                                 if(i+5 <ssize) dat8[i+5] = r1;                  else break;
1568                                                                 if(i+6 <ssize) dat8[i+6] = (g1 >> 4);   else break;
1569                                                                 if(i+7 <ssize) dat8[i+7] = ((g1 & 0x0f)<< 4 )|((b1 >> 8)& 0x0f);else break;
1570                                                                 if(i+8 <ssize) dat8[i+8] = b1;                  else break;
1571                                                                 index+=2;
1572                                                         }else
1573                                                                 break;
1574                                                 }
1575                                         }
1576                                 }else if (image->comps[0].prec == 16){
1577                                         for (i=0 ; i<ssize-5 ; i+=6) {  // 16 bits per pixel 
1578                                                 int r = 0,g = 0,b = 0;
1579                                                 if(index < imgsize){
1580                                                         r = image->comps[0].data[index];
1581                                                         g = image->comps[1].data[index];
1582                                                         b = image->comps[2].data[index];
1583                                                         if (image->comps[0].sgnd){
1584                                                         r += adjust;
1585                                                         g += adjust;
1586                                                         b += adjust;
1587                                                         }
1588                                                         dat8[i+0] =  r;//LSB
1589                                                         dat8[i+1] = (r >> 8);//MSB       
1590                                                         dat8[i+2] =  g;         
1591                                                         dat8[i+3] = (g >> 8);
1592                                                         dat8[i+4] =  b; 
1593                                                         dat8[i+5] = (b >> 8);
1594                                                         index++;
1595                                                         last_i = i+6;
1596                                                 }else
1597                                                         break; 
1598                                         }
1599                                         if(last_i < ssize){
1600                                                 for (i=0 ; i<ssize ; i+=6) {    // 16 bits per pixel 
1601                                                         int r = 0,g = 0,b = 0;
1602                                                         if(index < imgsize){
1603                                                                 r = image->comps[0].data[index];
1604                                                                 g = image->comps[1].data[index];
1605                                                                 b = image->comps[2].data[index];
1606                                                                 if (image->comps[0].sgnd){
1607                                                                         r += adjust;
1608                                                                         g += adjust;
1609                                                                         b += adjust;
1610                                                                 }
1611                                                                 dat8[i+0] =  r;//LSB
1612                                                                 if(i+1 <ssize) dat8[i+1] = (r >> 8);else break;//MSB     
1613                                                                 if(i+2 <ssize) dat8[i+2] =  g;          else break;
1614                                                                 if(i+3 <ssize) dat8[i+3] = (g >> 8);else break;
1615                                                                 if(i+4 <ssize) dat8[i+4] =  b;          else break;
1616                                                                 if(i+5 <ssize) dat8[i+5] = (b >> 8);else break;
1617                                                                 index++;
1618                                                         }else
1619                                                                 break; 
1620                                                 }                                               
1621                                         }
1622                                 }else{
1623                                         fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1624                                         fprintf(stderr,"Aborting\n");
1625                                         return 1;
1626                                 }
1627                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1628                         }
1629                         _TIFFfree(buf);
1630                         TIFFClose(tif);
1631                 }else if (image->numcomps == 1){
1632                         /* -->> -->> -->>    
1633                         Black and White     
1634                         <<-- <<-- <<-- */
1635
1636                         tif = TIFFOpen(outfile, "wb"); 
1637                         if (!tif) {
1638                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1639                                 return 1;
1640                         }
1641
1642                         width   = image->comps[0].w;
1643                         height  = image->comps[0].h;
1644                         imgsize = width * height;
1645                         bps             = image->comps[0].prec;
1646
1647                         /* Set tags */
1648                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1649                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1650                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1651                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1652                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1653                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1654                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1655                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1656
1657                         /* Get a buffer for the data */
1658                         strip_size = TIFFStripSize(tif);
1659                         buf = _TIFFmalloc(strip_size);
1660                         index = 0;                      
1661                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1662                                 unsigned char *dat8;
1663                                 int i;
1664                                 dat8 = (unsigned char*)buf;
1665                                 if (image->comps[0].prec == 8){
1666                                         for (i=0; i<TIFFStripSize(tif); i+=1) { // 8 bits per pixel 
1667                                                 if(index < imgsize){
1668                                                         int r = 0;
1669                                                         r = image->comps[0].data[index];
1670                                                         if (image->comps[0].sgnd){
1671                                                                 r  += adjust;
1672                                                         }
1673                                                         dat8[i+0] = r;
1674                                                         index++;
1675                                                 }else
1676                                                         break; 
1677                                         }
1678                                 }else if (image->comps[0].prec == 12){
1679                                         for (i = 0; i<TIFFStripSize(tif); i+=3) {       // 12 bits per pixel 
1680                                                 if(index < imgsize){
1681                                                         int r = 0, r1 = 0;
1682                                                         r  = image->comps[0].data[index];
1683                                                         r1 = image->comps[0].data[index+1];
1684                                                         if (image->comps[0].sgnd){
1685                                                                 r  += adjust;
1686                                                                 r1 += adjust;
1687                                                         }
1688                                                         dat8[i+0] = (r >> 4);
1689                                                         dat8[i+1] = ((r & 0x0f) << 4 )|((r1 >> 8)& 0x0f);
1690                                                         dat8[i+2] = r1 ;
1691                                                         index+=2;
1692                                                 }else
1693                                                         break; 
1694                                         }
1695                                 }else if (image->comps[0].prec == 16){
1696                                         for (i=0; i<TIFFStripSize(tif); i+=2) { // 16 bits per pixel 
1697                                                 if(index < imgsize){
1698                                                         int r = 0;
1699                                                         r = image->comps[0].data[index];
1700                                                         if (image->comps[0].sgnd){
1701                                                                 r  += adjust;
1702                                                         }
1703                                                         dat8[i+0] = r;
1704                                                         dat8[i+1] = r >> 8;
1705                                                         index++;
1706                                                 }else
1707                                                         break; 
1708                                         }
1709                                 }else{
1710                                         fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1711                                         fprintf(stderr,"Aborting\n");
1712                                         return 1;
1713                                 }
1714                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1715                         }
1716                         _TIFFfree(buf);
1717                         TIFFClose(tif);
1718                 }else{
1719                         fprintf(stderr,"TIFF file creation. Bad color format. Only RGB & Grayscale has been implemented\n");
1720                         fprintf(stderr,"Aborting\n");
1721                         return 1;
1722                 }
1723                 return 0;
1724 }
1725
1726 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1727 {
1728         int subsampling_dx = parameters->subsampling_dx;
1729         int subsampling_dy = parameters->subsampling_dy;
1730         TIFF *tif;
1731         tiff_infoheader_t Info;
1732         tdata_t buf;
1733         tstrip_t strip;
1734         tsize_t strip_size;
1735         int j, numcomps, w, h,index;
1736         OPJ_COLOR_SPACE color_space;
1737         opj_image_cmptparm_t cmptparm[3];
1738         opj_image_t * image = NULL;
1739         int imgsize = 0;
1740
1741         tif = TIFFOpen(filename, "r");
1742
1743         if (!tif) {
1744                 fprintf(stderr, "Failed to open %s for reading\n", filename);
1745                 return 0;
1746         }
1747
1748         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
1749         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
1750         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
1751         TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
1752         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
1753         Info.tiPhoto = 0;
1754         TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
1755         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
1756         w= Info.tiWidth;
1757         h= Info.tiHeight;
1758         
1759         if (Info.tiPhoto == 2) { 
1760                 /* -->> -->> -->>    
1761                 RGB color           
1762                 <<-- <<-- <<-- */
1763
1764                 numcomps = 3;
1765                 color_space = CLRSPC_SRGB;
1766                 /* initialize image components*/ 
1767                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1768                 for(j = 0; j < numcomps; j++) {
1769                         if (parameters->cp_cinema) {
1770                                 cmptparm[j].prec = 12;
1771                                 cmptparm[j].bpp = 12;
1772                         }else{
1773                                 cmptparm[j].prec = Info.tiBps;
1774                                 cmptparm[j].bpp = Info.tiBps;
1775                         }
1776                         cmptparm[j].sgnd = 0;
1777                         cmptparm[j].dx = subsampling_dx;
1778                         cmptparm[j].dy = subsampling_dy;
1779                         cmptparm[j].w = w;
1780                         cmptparm[j].h = h;
1781                 }
1782                 /* create the image*/ 
1783                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1784                 if(!image) {
1785                         TIFFClose(tif);
1786                         return NULL;
1787                 }
1788
1789                 /* set image offset and reference grid */
1790                 image->x0 = parameters->image_offset_x0;
1791                 image->y0 = parameters->image_offset_y0;
1792                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1793                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1794
1795                 buf = _TIFFmalloc(TIFFStripSize(tif));
1796                 strip_size=0;
1797                 strip_size=TIFFStripSize(tif);
1798                 index = 0;
1799                 imgsize = image->comps[0].w * image->comps[0].h ;
1800                 /* Read the Image components*/
1801                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1802                         unsigned char *dat8;
1803                         int i, ssize;
1804                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1805                         dat8 = (unsigned char*)buf;
1806
1807                         if (Info.tiBps==12){
1808                                 for (i=0; i<ssize; i+=9) {      /*12 bits per pixel*/
1809                                         if((index < imgsize)&(index+1 < imgsize)){
1810                                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )                |(dat8[i+1]>>4);
1811                                                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
1812                                                 image->comps[2].data[index]   = ( dat8[i+3]<<4)                 |(dat8[i+4]>>4);
1813                                                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
1814                                                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)                |(dat8[i+7]>>4);
1815                                                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
1816                                                 index+=2;
1817                                         }else
1818                                                 break;
1819                                 }
1820                         }
1821                         else if( Info.tiBps==16){
1822                                 for (i=0; i<ssize; i+=6) {      /* 16 bits per pixel */
1823                                         if(index < imgsize){
1824                                                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; // R 
1825                                                 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; // G 
1826                                                 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; // B 
1827                                                 if(parameters->cp_cinema){/* Rounding to 12 bits*/
1828                                                         image->comps[0].data[index] = (image->comps[0].data[index] + 0x08) >> 4 ;
1829                                                         image->comps[1].data[index] = (image->comps[1].data[index] + 0x08) >> 4 ;
1830                                                         image->comps[2].data[index] = (image->comps[2].data[index] + 0x08) >> 4 ;
1831                                                 }
1832                                                 index++;
1833                                         }else
1834                                                 break;
1835                                 }
1836                         }
1837                         else if ( Info.tiBps==8){
1838                                 for (i=0; i<ssize; i+=3) {      /* 8 bits per pixel */
1839                                         if(index < imgsize){
1840                                                 image->comps[0].data[index] = dat8[i+0];// R 
1841                                                 image->comps[1].data[index] = dat8[i+1];// G 
1842                                                 image->comps[2].data[index] = dat8[i+2];// B 
1843                                                 if(parameters->cp_cinema){/* Rounding to 12 bits*/
1844                                                         image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
1845                                                         image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
1846                                                         image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
1847                                                 }
1848                                                 index++;
1849                                         }else
1850                                                 break;
1851                                 }
1852                         }
1853                         else{
1854                                 fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1855                                 fprintf(stderr,"Aborting\n");
1856                                 return NULL;
1857                         }
1858                 }
1859
1860                 _TIFFfree(buf);
1861                 TIFFClose(tif);
1862         }else if(Info.tiPhoto == 1) { 
1863                 /* -->> -->> -->>    
1864                 Black and White
1865                 <<-- <<-- <<-- */
1866
1867                 numcomps = 1;
1868                 color_space = CLRSPC_GRAY;
1869                 /* initialize image components*/ 
1870                 memset(&cmptparm[0], 0, sizeof(opj_image_cmptparm_t));
1871                 cmptparm[0].prec = Info.tiBps;
1872                 cmptparm[0].bpp = Info.tiBps;
1873                 cmptparm[0].sgnd = 0;
1874                 cmptparm[0].dx = subsampling_dx;
1875                 cmptparm[0].dy = subsampling_dy;
1876                 cmptparm[0].w = w;
1877                 cmptparm[0].h = h;
1878
1879                 /* create the image*/ 
1880                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1881                 if(!image) {
1882                         TIFFClose(tif);
1883                         return NULL;
1884                 }
1885                 /* set image offset and reference grid */
1886                 image->x0 = parameters->image_offset_x0;
1887                 image->y0 = parameters->image_offset_y0;
1888                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1889                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1890
1891                 buf = _TIFFmalloc(TIFFStripSize(tif));
1892                 strip_size = 0;
1893                 strip_size = TIFFStripSize(tif);
1894                 index = 0;
1895                 imgsize = image->comps[0].w * image->comps[0].h ;
1896                 /* Read the Image components*/
1897                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1898                         unsigned char *dat8;
1899                         int i, ssize;
1900                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1901                         dat8 = (unsigned char*)buf;
1902
1903                         if (Info.tiBps==12){
1904                                 for (i=0; i<ssize; i+=3) {      /* 12 bits per pixel*/
1905                                         if(index < imgsize){
1906                                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )                |(dat8[i+1]>>4) ;
1907                                                 image->comps[0].data[index+1] = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
1908                                                 index+=2;
1909                                         }else
1910                                                 break;
1911                                 }
1912                         }
1913                         else if( Info.tiBps==16){
1914                                 for (i=0; i<ssize; i+=2) {      /* 16 bits per pixel */
1915                                         if(index < imgsize){
1916                                                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
1917                                                 index++;
1918                                         }else
1919                                                 break;
1920                                 }
1921                         }
1922                         else if ( Info.tiBps==8){
1923                                 for (i=0; i<ssize; i+=1) {      /* 8 bits per pixel */
1924                                         if(index < imgsize){
1925                                                 image->comps[0].data[index] = dat8[i+0];
1926                                                 index++;
1927                                         }else
1928                                                 break;
1929                                 }
1930                         }
1931                         else{
1932                                 fprintf(stderr,"TIFF file creation. Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1933                                 fprintf(stderr,"Aborting\n");
1934                                 return NULL;
1935                         }
1936                 }
1937
1938                 _TIFFfree(buf);
1939                 TIFFClose(tif);
1940         }else{
1941                 fprintf(stderr,"TIFF file creation. Bad color format. Only RGB & Grayscale has been implemented\n");
1942                 fprintf(stderr,"Aborting\n");
1943                 return NULL;
1944         }
1945         return image;
1946 }
1947
1948 /* -->> -->> -->> -->>
1949
1950         RAW IMAGE FORMAT
1951
1952  <<-- <<-- <<-- <<-- */
1953
1954 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1955         int subsampling_dx = parameters->subsampling_dx;
1956         int subsampling_dy = parameters->subsampling_dy;
1957
1958         FILE *f = NULL;
1959         int i, compno, numcomps, w, h;
1960         OPJ_COLOR_SPACE color_space;
1961         opj_image_cmptparm_t *cmptparm; 
1962         opj_image_t * image = NULL;
1963         unsigned short ch;
1964         
1965         if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
1966         {
1967                 fprintf(stderr,"\nError: invalid raw image parameters\n");
1968                 fprintf(stderr,"Please use the Format option -F:\n");
1969                 fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1970                 fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1971                 fprintf(stderr,"Aborting\n");
1972                 return NULL;
1973         }
1974
1975         f = fopen(filename, "rb");
1976         if (!f) {
1977                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1978                 fprintf(stderr,"Aborting\n");
1979                 return NULL;
1980         }
1981         numcomps = raw_cp->rawComp;
1982         color_space = CLRSPC_SRGB;
1983         w = raw_cp->rawWidth;
1984         h = raw_cp->rawHeight;
1985         cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
1986         
1987         /* initialize image components */       
1988         memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1989         for(i = 0; i < numcomps; i++) {         
1990                 cmptparm[i].prec = raw_cp->rawBitDepth;
1991                 cmptparm[i].bpp = raw_cp->rawBitDepth;
1992                 cmptparm[i].sgnd = raw_cp->rawSigned;
1993                 cmptparm[i].dx = subsampling_dx;
1994                 cmptparm[i].dy = subsampling_dy;
1995                 cmptparm[i].w = w;
1996                 cmptparm[i].h = h;
1997         }
1998         /* create the image */
1999         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2000         if(!image) {
2001                 fclose(f);
2002                 return NULL;
2003         }
2004         /* set image offset and reference grid */
2005         image->x0 = parameters->image_offset_x0;
2006         image->y0 = parameters->image_offset_y0;
2007         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
2008         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
2009
2010         if(raw_cp->rawBitDepth <= 8)
2011         {
2012                 unsigned char value = 0;
2013                 for(compno = 0; compno < numcomps; compno++) {
2014                         for (i = 0; i < w * h; i++) {
2015                                 if (!fread(&value, 1, 1, f)) {
2016                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2017                                         return NULL;
2018                                 }
2019                                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2020                         }
2021                 }
2022         }
2023         else if(raw_cp->rawBitDepth <= 16)
2024         {
2025                 unsigned short value;
2026                 for(compno = 0; compno < numcomps; compno++) {
2027                         for (i = 0; i < w * h; i++) {
2028                                 unsigned char temp;
2029                                 if (!fread(&temp, 1, 1, f)) {
2030                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2031                                         return NULL;
2032                                 }
2033                                 value = temp << 8;
2034                                 if (!fread(&temp, 1, 1, f)) {
2035                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2036                                         return NULL;
2037                                 }
2038                                 value += temp;
2039                                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2040                         }
2041                 }
2042         }
2043         else {
2044                 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2045                 return NULL;
2046         }
2047
2048         if (fread(&ch, 1, 1, f)) {
2049                 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2050         }
2051         fclose(f);
2052
2053         return image;
2054 }
2055
2056 int imagetoraw(opj_image_t * image, const char *outfile)
2057 {
2058         FILE *rawFile = NULL;
2059         unsigned int compno;
2060         int w, h;
2061         int line, row;
2062         int *ptr;
2063
2064         if((image->numcomps * image->x1 * image->y1) == 0)
2065         {
2066                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2067                 return 1;
2068         }
2069
2070         rawFile = fopen(outfile, "wb");
2071         if (!rawFile) {
2072                 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2073                 return 1;
2074         }
2075
2076         fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2077
2078         for(compno = 0; compno < image->numcomps; compno++)
2079         {
2080                 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2081                         image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2082
2083                 w = image->comps[compno].w;
2084                 h = image->comps[compno].h;
2085
2086                 if(image->comps[compno].prec <= 8)
2087                 {
2088                         if(image->comps[compno].sgnd == 1)
2089                         {
2090                                 signed char curr;
2091                                 int mask = (1 << image->comps[compno].prec) - 1;
2092                                 ptr = image->comps[compno].data;
2093                                 for (line = 0; line < h; line++) {
2094                                         for(row = 0; row < w; row++)    {                               
2095                                                 curr = (signed char) (*ptr & mask);
2096                                                 fwrite(&curr, sizeof(signed char), 1, rawFile);
2097                                                 ptr++;
2098                                         }
2099                                 }
2100                         }
2101                         else if(image->comps[compno].sgnd == 0)
2102                         {
2103                                 unsigned char curr;
2104                                 int mask = (1 << image->comps[compno].prec) - 1;
2105                                 ptr = image->comps[compno].data;
2106                                 for (line = 0; line < h; line++) {
2107                                         for(row = 0; row < w; row++)    {       
2108                                                 curr = (unsigned char) (*ptr & mask);
2109                                                 fwrite(&curr, sizeof(unsigned char), 1, rawFile);
2110                                                 ptr++;
2111                                         }
2112                                 }
2113                         }
2114                 }
2115                 else if(image->comps[compno].prec <= 16)
2116                 {
2117                         if(image->comps[compno].sgnd == 1)
2118                         {
2119                                 signed short int curr;
2120                                 int mask = (1 << image->comps[compno].prec) - 1;
2121                                 ptr = image->comps[compno].data;
2122                                 for (line = 0; line < h; line++) {
2123                                         for(row = 0; row < w; row++)    {                                       
2124                                                 unsigned char temp;
2125                                                 curr = (signed short int) (*ptr & mask);
2126                                                 temp = curr >> 8;
2127                                                 fwrite(&temp, 1, 1, rawFile);
2128                                                 temp = curr;
2129                                                 fwrite(&temp, 1, 1, rawFile);
2130                                                 ptr++;
2131                                         }
2132                                 }
2133                         }
2134                         else if(image->comps[compno].sgnd == 0)
2135                         {
2136                                 unsigned short int curr;
2137                                 int mask = (1 << image->comps[compno].prec) - 1;
2138                                 ptr = image->comps[compno].data;
2139                                 for (line = 0; line < h; line++) {
2140                                         for(row = 0; row < w; row++)    {                               
2141                                                 unsigned char temp;
2142                                                 curr = (unsigned short int) (*ptr & mask);
2143                                                 temp = curr >> 8;
2144                                                 fwrite(&temp, 1, 1, rawFile);
2145                                                 temp = curr;
2146                                                 fwrite(&temp, 1, 1, rawFile);
2147                                                 ptr++;
2148                                         }
2149                                 }
2150                         }
2151                 }
2152                 else if (image->comps[compno].prec <= 32)
2153                 {
2154                         fprintf(stderr,"More than 16 bits per component no handled yet\n");
2155                         return 1;
2156                 }
2157                 else
2158                 {
2159                         fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2160                         return 1;
2161                 }
2162         }
2163         fclose(rawFile);
2164         return 0;
2165 }
2166
2167 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
2168 #ifdef WIN32
2169 {
2170         printf("Error. PNG format is not yet handled under windows\n");
2171         return NULL;
2172 }
2173 #else
2174 {
2175     png_bytep row;
2176     png_structp png;
2177     png_infop info;
2178     double gamma, display_exponent;
2179     int bit_depth, interlace_type, compression_type, filter_type;
2180     int unit, pass, nr_passes;
2181     png_uint_32 resx, resy;
2182     unsigned int i, max, src_w;
2183     png_uint_32 width, height;
2184     int color_type, has_alpha;
2185     unsigned char *png_buf, *s;
2186     FILE *reader;
2187 /* j2k: */
2188     opj_image_t *image;
2189     opj_image_cmptparm_t cmptparm[4];
2190     int sub_dx, sub_dy;
2191     unsigned int nr_comp;
2192     int *r, *g, *b, *a;
2193
2194     if ((reader = fopen(read_idf, "rb")) == NULL) {
2195         fprintf(stderr, "pngtoimage: can not open %s\n", read_idf);
2196         return NULL;
2197     }
2198     nr_passes = 0;
2199     png_buf = NULL;
2200
2201 /* libpng-VERSION/example.c: 
2202  * PC : screen_gamma = 2.2;
2203  * Mac: screen_gamma = 1.7 or 1.0;
2204 */
2205     display_exponent = 2.2;
2206
2207     if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
2208                                       NULL, NULL, NULL)) == NULL)
2209         goto fin;
2210     if ((info = png_create_info_struct(png)) == NULL)
2211         goto fin;
2212
2213     if (setjmp(png_jmpbuf(png)))
2214         goto fin;
2215
2216     png_init_io(png, reader);
2217     png_read_info(png, info);
2218
2219     png_get_IHDR(png, info, &width, &height,
2220                  &bit_depth, &color_type, &interlace_type,
2221                  &compression_type, &filter_type);
2222
2223     if (color_type == PNG_COLOR_TYPE_PALETTE)
2224         png_set_expand(png);
2225     else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
2226         png_set_expand(png);
2227
2228     if (png_get_valid(png, info, PNG_INFO_tRNS))
2229         png_set_expand(png);
2230
2231     if (bit_depth == 16)
2232         png_set_strip_16(png);
2233
2234 /* GRAY => RGB; GRAY_ALPHA => RGBA
2235 */
2236     if (color_type == PNG_COLOR_TYPE_GRAY
2237         || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
2238         png_set_gray_to_rgb(png);
2239         color_type =
2240             (color_type == PNG_COLOR_TYPE_GRAY ? PNG_COLOR_TYPE_RGB :
2241              PNG_COLOR_TYPE_RGB_ALPHA);
2242     }
2243     if (!png_get_gAMA(png, info, &gamma))
2244         gamma = 0.45455;
2245
2246     png_set_gamma(png, display_exponent, gamma);
2247
2248     nr_passes = png_set_interlace_handling(png);
2249
2250     png_read_update_info(png, info);
2251
2252     png_get_pHYs(png, info, &resx, &resy, &unit);
2253
2254     color_type = png_get_color_type(png, info);
2255
2256     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
2257
2258     if (has_alpha)
2259         nr_comp = 4;
2260     else
2261         nr_comp = 3;
2262
2263     src_w = width * nr_comp;
2264     png_buf = (unsigned char *) malloc(src_w * height);
2265
2266     if (nr_passes == 0)
2267         nr_passes = 1;
2268
2269     for (pass = 0; pass < nr_passes; pass++) {
2270         s = png_buf;
2271
2272         for (i = 0; i < height; i++) {
2273 /* libpng.3:
2274  * If you want the "sparkle" effect, just call png_read_rows() as
2275  * normal, with the third parameter NULL.
2276 */
2277             png_read_rows(png, &s, NULL, 1);
2278
2279             s += src_w;
2280         }
2281     }
2282     memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
2283
2284     sub_dx = params->subsampling_dx;
2285     sub_dy = params->subsampling_dy;
2286
2287     for (i = 0; i < nr_comp; ++i) {
2288         cmptparm[i].prec = 8;
2289         cmptparm[i].bpp = 8;
2290         cmptparm[i].sgnd = 0;
2291         cmptparm[i].dx = sub_dx;
2292         cmptparm[i].dy = sub_dy;
2293         cmptparm[i].w = width;
2294         cmptparm[i].h = height;
2295     }
2296
2297     image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
2298
2299     if (image == NULL)
2300         goto fin;
2301
2302     image->x0 = params->image_offset_x0;
2303     image->y0 = params->image_offset_y0;
2304     image->x1 =
2305         params->image_offset_x0 + (width - 1) * sub_dx + 1 + image->x0;
2306     image->y1 =
2307         params->image_offset_y0 + (height - 1) * sub_dy + 1 + image->y0;
2308
2309     r = image->comps[0].data;
2310     g = image->comps[1].data;
2311     b = image->comps[2].data;
2312     a = image->comps[3].data;
2313     s = png_buf;
2314
2315     max = width * height;
2316
2317     for (i = 0; i < max; ++i) {
2318         *r++ = *s++;
2319         *g++ = *s++;
2320         *b++ = *s++;
2321
2322         if (has_alpha)
2323             *a++ = *s++;
2324     }
2325
2326   fin:
2327     if (png)
2328         png_destroy_read_struct(&png, &info, NULL);
2329     if (png_buf)
2330         free(png_buf);
2331
2332     fclose(reader);
2333
2334     return image;
2335
2336 }                               /* pngtoimage() */
2337 #endif
2338
2339 int imagetopng(opj_image_t * image, const char *write_idf)
2340 #ifdef WIN32
2341 {
2342         printf("Error. PNG format is not yet handled under windows\n");
2343         return -1;
2344 }
2345 #else
2346 {
2347     FILE *writer;
2348     png_structp png_ptr;
2349     png_infop info_ptr;
2350     int *rs, *gs, *bs, *as;
2351     unsigned char *row_buf, *d;
2352     int fails, mono, graya, rgb, rgba;
2353     int width, height, nr_colors, color_type;
2354     int bit_depth, adjust, x, y;
2355     png_color_8 sig_bit;
2356
2357     writer = fopen(write_idf, "wb");
2358
2359     if (writer == NULL)
2360         return 1;
2361
2362     info_ptr = NULL;
2363     fails = 1;
2364
2365 /* Create and initialize the png_struct with the desired error handler
2366  * functions.  If you want to use the default stderr and longjump method,
2367  * you can supply NULL for the last three parameters.  We also check that
2368  * the library version is compatible with the one used at compile time,
2369  * in case we are using dynamically linked libraries.  REQUIRED.
2370 */
2371     png_ptr =
2372         png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2373 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2374
2375     if (png_ptr == NULL)
2376         goto fin;
2377
2378 /* Allocate/initialize the image information data.  REQUIRED 
2379 */
2380     info_ptr = png_create_info_struct(png_ptr);
2381
2382     if (info_ptr == NULL)
2383         goto fin;
2384
2385 /* Set error handling.  REQUIRED if you are not supplying your own
2386  * error handling functions in the png_create_write_struct() call.
2387 */
2388     if (setjmp(png_jmpbuf(png_ptr)))
2389         goto fin;
2390
2391 /* I/O initialization functions is REQUIRED 
2392 */
2393     png_init_io(png_ptr, writer);
2394
2395 /* Set the image information here.  Width and height are up to 2^31,
2396  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2397  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2398  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2399  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
2400  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2401  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
2402  * REQUIRED
2403 */
2404     png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
2405
2406     mono = graya = rgb = rgba = adjust = 0;
2407
2408     nr_colors = image->numcomps;
2409     width = image->comps[0].w;
2410     height = image->comps[0].h;
2411     rs = image->comps[0].data;
2412
2413     if (nr_colors == 2) {
2414         graya = 1;
2415         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
2416         sig_bit.gray = image->comps[0].prec;
2417         bit_depth = image->comps[0].prec;
2418         as = image->comps[1].data;
2419     } else if (nr_colors == 3) {
2420         rgb = 1;
2421         color_type = PNG_COLOR_TYPE_RGB;
2422         sig_bit.red = image->comps[0].prec;
2423         sig_bit.green = image->comps[1].prec;
2424         sig_bit.blue = image->comps[2].prec;
2425         bit_depth = image->comps[0].prec;
2426         gs = image->comps[1].data;
2427         bs = image->comps[2].data;
2428         if (image->comps[0].sgnd)
2429             adjust = 1 << (image->comps[0].prec - 1);
2430     } else if (nr_colors == 4) {
2431         rgb = rgba = 1;
2432         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2433         sig_bit.red = image->comps[0].prec;
2434         sig_bit.green = image->comps[1].prec;
2435         sig_bit.blue = image->comps[2].prec;
2436         sig_bit.alpha = image->comps[3].prec;
2437         bit_depth = image->comps[0].prec;
2438         gs = image->comps[1].data;
2439         bs = image->comps[2].data;
2440         as = image->comps[3].data;
2441         if (image->comps[0].sgnd)
2442             adjust = 1 << (image->comps[0].prec - 1);
2443     } else {
2444         mono = 1;
2445         color_type = PNG_COLOR_TYPE_GRAY;
2446         sig_bit.gray = image->comps[0].prec;
2447         bit_depth = image->comps[0].prec;
2448     }
2449     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
2450
2451     png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
2452                  color_type,
2453                  PNG_INTERLACE_NONE,
2454                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2455
2456 #ifdef HIDDEN_CODE
2457 /* Optional gamma chunk is strongly suggested if you have any guess
2458  * as to the correct gamma of the image.
2459 */
2460
2461     if (gamma > 0.0) {
2462         png_set_gAMA(png_ptr, info_ptr, gamma);
2463     }
2464 #endif                          /* HIDDEN_CODE */
2465 #ifdef HIDDEN_CODE
2466     if (have_bg) {
2467         png_color_16 background;
2468
2469         background.red = bg_red;
2470         background.green = bg_green;
2471         background.blue = bg_blue;
2472
2473         png_set_bKGD(png_ptr, info_ptr, &background);
2474     }
2475 #endif                          /* HIDDEN_CODE */
2476     png_write_info(png_ptr, info_ptr);
2477
2478     png_set_packing(png_ptr);
2479
2480     row_buf = (unsigned char *) malloc(width * nr_colors);
2481
2482     for (y = 0; y < height; ++y) {
2483         d = row_buf;
2484
2485         for (x = 0; x < width; ++x) {
2486             if (mono) {
2487                 *d++ = (unsigned char) *rs++;
2488             }
2489             if (graya) {
2490                 *d++ = (unsigned char) *rs++;
2491                 *d++ = (unsigned char) *as++;
2492             } else if (rgb) {
2493                 *d++ = (unsigned char) (*rs++ + adjust);
2494                 *d++ = (unsigned char) (*gs++ + adjust);
2495                 *d++ = (unsigned char) (*bs++ + adjust);
2496
2497                 if (rgba)
2498                     *d++ = (unsigned char) (*as++ + adjust);
2499             }
2500         }                       /* for(x) */
2501
2502         png_write_row(png_ptr, row_buf);
2503
2504     }                           /* for(y) */
2505
2506     png_write_end(png_ptr, info_ptr);
2507
2508     fails = 0;
2509
2510   fin:
2511
2512     if (png_ptr) {
2513         png_destroy_write_struct(&png_ptr, &info_ptr);
2514     }
2515     fclose(writer);
2516
2517     return fails;
2518 }
2519 #endif