a6bf0f73ae3b151bf5f5a50d07bde4369f8c7b7e
[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 "tiffio.h"
37 #include "png.h"
38 #else
39 #include <tiffio.h>
40 #include <png.h>
41 #endif /* WIN32 */
42 #include "openjpegConfigure.h"
43 #include "openjpeg.h"
44 #include "convert.h"
45
46 /*
47  * Get logarithm of an integer and round downwards.
48  *
49  * log2(a)
50  */
51 static int int_floorlog2(int a) {
52         int l;
53         for (l = 0; a > 1; l++) {
54                 a >>= 1;
55         }
56         return l;
57 }
58
59 /*
60  * Divide an integer by a power of 2 and round upwards.
61  *
62  * a divided by 2^b
63  */
64 static int int_ceildivpow2(int a, int b) {
65         return (a + (1 << b) - 1) >> b;
66 }
67
68 /*
69  * Divide an integer and round upwards.
70  *
71  * a divided by b
72  */
73 static int int_ceildiv(int a, int b) {
74         return (a + b - 1) / b;
75 }
76
77
78 /* -->> -->> -->> -->>
79
80   TGA IMAGE FORMAT
81
82  <<-- <<-- <<-- <<-- */
83
84 // TGA header definition.
85 #pragma pack(push,1) // Pack structure byte aligned
86 typedef struct tga_header
87 {                           
88     uint8   id_length;              /* Image id field length    */
89     uint8   colour_map_type;        /* Colour map type          */
90     uint8   image_type;             /* Image type               */
91     /*
92     ** Colour map specification
93     */
94     uint16  colour_map_index;       /* First entry index        */
95     uint16  colour_map_length;      /* Colour map length        */
96     uint8   colour_map_entry_size;  /* Colour map entry size    */
97     /*
98     ** Image specification
99     */
100     uint16  x_origin;               /* x origin of image        */
101     uint16  y_origin;               /* u origin of image        */
102     uint16  image_width;            /* Image width              */
103     uint16  image_height;           /* Image height             */
104     uint8   pixel_depth;            /* Pixel depth              */
105     uint8   image_desc;             /* Image descriptor         */
106 } tga_header;
107 #pragma pack(pop) // Return to normal structure packing alignment.
108
109 int tga_readheader(FILE *fp, uint32 *bits_per_pixel, uint32 *width, uint32 *height, int *flip_image)
110 {
111         int palette_size;
112         tga_header tga ;
113
114         if (!bits_per_pixel || !width || !height || !flip_image)
115                 return 0;
116         
117         // Read TGA header
118         fread((uint8*)&tga, sizeof(tga_header), 1, fp);
119
120         *bits_per_pixel = tga.pixel_depth;
121         
122         *width  = tga.image_width;
123         *height = tga.image_height ;
124
125         // Ignore tga identifier, if present ...
126         if (tga.id_length)
127         {
128                 uint8 *id = (uint8 *) malloc(tga.id_length);
129                 fread(id, tga.id_length, 1, fp);
130                 free(id);  
131         }
132
133         // Test for compressed formats ... not yet supported ...
134         // Note :-  9 - RLE encoded palettized.
135         //                 10 - RLE encoded RGB.
136         if (tga.image_type > 8)
137         {
138                 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
139                 return 0 ;
140         }
141
142         *flip_image = !(tga.image_desc & 32);
143
144         // Palettized formats are not yet supported, skip over the palette, if present ... 
145         palette_size = tga.colour_map_length * (tga.colour_map_entry_size/8);
146         
147         if (palette_size>0)
148         {
149                 fprintf(stderr, "File contains a palette - not yet supported.");
150                 fseek(fp, palette_size, SEEK_CUR);
151         }
152         return 1;
153 }
154
155 int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, bool flip_image)
156 {
157         tga_header tga;
158
159         if (!bits_per_pixel || !width || !height)
160                 return 0;
161
162         memset(&tga, 0, sizeof(tga_header));
163
164         tga.pixel_depth = bits_per_pixel;
165         tga.image_width  = width;
166         tga.image_height = height;
167         tga.image_type = 2; // Uncompressed.
168         tga.image_desc = 8; // 8 bits per component.
169
170         if (flip_image)
171                 tga.image_desc |= 32;
172
173         // Write TGA header
174         fwrite((uint8*)&tga, sizeof(tga_header), 1, fp);
175
176         return 1;
177 }
178
179 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
180         FILE *f;
181         opj_image_t *image;
182         uint32 image_width, image_height, pixel_bit_depth;
183         uint32 x, y;
184         int flip_image=0;
185         opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
186         int numcomps;
187         OPJ_COLOR_SPACE color_space;
188         bool mono ;
189         bool save_alpha;
190         int subsampling_dx, subsampling_dy;
191         int i;  
192
193         f = fopen(filename, "rb");
194         if (!f) {
195                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
196                 return 0;
197         }
198
199         if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
200                 return NULL;
201
202         // We currently only support 24 & 32 bit tga's ...
203         if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
204                 return NULL;
205
206         /* initialize image components */   
207         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
208
209         mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  // Mono with & without alpha.
210         save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); // Mono with alpha, or RGB with alpha
211
212         if (mono) {
213                 color_space = CLRSPC_GRAY;
214                 numcomps = save_alpha ? 2 : 1;
215         }       
216         else {
217                 numcomps = save_alpha ? 4 : 3;
218                 color_space = CLRSPC_SRGB;
219         }
220
221         subsampling_dx = parameters->subsampling_dx;
222         subsampling_dy = parameters->subsampling_dy;
223
224         for (i = 0; i < numcomps; i++) {
225                 cmptparm[i].prec = 8;
226                 cmptparm[i].bpp = 8;
227                 cmptparm[i].sgnd = 0;
228                 cmptparm[i].dx = subsampling_dx;
229                 cmptparm[i].dy = subsampling_dy;
230                 cmptparm[i].w = image_width;
231                 cmptparm[i].h = image_height;
232         }
233
234         /* create the image */
235         image = opj_image_create(numcomps, &cmptparm[0], color_space);
236
237         if (!image)
238                 return NULL;
239
240         /* set image offset and reference grid */
241         image->x0 = parameters->image_offset_x0;
242         image->y0 = parameters->image_offset_y0;
243         image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
244         image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
245
246         /* set image data */
247         for (y=0; y < image_height; y++) 
248         {
249                 int index;
250
251                 if (flip_image)
252                         index = (image_height-y-1)*image_width;
253                 else
254                         index = y*image_width;
255
256                 if (numcomps==3)
257                 {
258                         for (x=0;x<image_width;x++) 
259                         {
260                                 uint8 r,g,b;
261                                 fread(&b, 1, 1, f);
262                                 fread(&g, 1, 1, f);
263                                 fread(&r, 1, 1, f);
264
265                                 image->comps[0].data[index]=r;
266                                 image->comps[1].data[index]=g;
267                                 image->comps[2].data[index]=b;
268                                 index++;
269                         }
270                 }
271                 else if (numcomps==4)
272                 {
273                         for (x=0;x<image_width;x++) 
274                         {
275                                 uint8 r,g,b,a;
276                                 fread(&b, 1, 1, f);
277                                 fread(&g, 1, 1, f);
278                                 fread(&r, 1, 1, f);
279                                 fread(&a, 1, 1, f);
280
281                                 image->comps[0].data[index]=r;
282                                 image->comps[1].data[index]=g;
283                                 image->comps[2].data[index]=b;
284                                 image->comps[3].data[index]=a;
285                                 index++;
286                         }
287                 }
288                 else {
289                         fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
290                 }
291         }       
292         return image;
293 }
294
295 int imagetotga(opj_image_t * image, const char *outfile) {
296         int width, height, bpp, x, y;
297         bool write_alpha;
298         int i;
299         uint32 alpha_channel;
300         float r,g,b,a;
301         uint8 value;
302         float scale;
303         FILE *fdest;
304
305         fdest = fopen(outfile, "wb");
306         if (!fdest) {
307                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
308                 return 1;
309         }
310
311         for (i = 0; i < image->numcomps-1; i++) {
312                 if ((image->comps[0].dx != image->comps[i+1].dx) 
313                         ||(image->comps[0].dy != image->comps[i+1].dy) 
314                         ||(image->comps[0].prec != image->comps[i+1].prec))     {
315       fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
316       return 1;
317    }
318         }
319
320         width = image->comps[0].w;
321         height = image->comps[0].h; 
322
323         // Mono with alpha, or RGB with alpha.
324         write_alpha = (image->numcomps==2) || (image->numcomps==4);   
325
326         // Write TGA header 
327         bpp = write_alpha ? 32 : 24;
328         if (!tga_writeheader(fdest, bpp, width , height, true))
329                 return 1;
330
331         alpha_channel = image->numcomps-1; 
332
333         scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
334
335         for (y=0; y < height; y++) {
336                 uint32 index=y*width;
337
338                 for (x=0; x < width; x++, index++)      {
339                         r = (float)(image->comps[0].data[index]);
340
341                         if (image->numcomps>2) {
342                                 g = (float)(image->comps[1].data[index]);
343                                 b = (float)(image->comps[2].data[index]);
344                         }
345                         else  {// Greyscale ...
346                                 g = r;
347                                 b = r;
348                         }
349
350                         // TGA format writes BGR ...
351                         value = (uint8)(b*scale);
352                         fwrite(&value,1,1,fdest);
353
354                         value = (uint8)(g*scale);
355                         fwrite(&value,1,1,fdest);
356
357                         value = (uint8)(r*scale);
358                         fwrite(&value,1,1,fdest);
359
360                         if (write_alpha) {
361                                 a = (float)(image->comps[alpha_channel].data[index]);
362                                 value = (uint8)(a*scale);
363                                 fwrite(&value,1,1,fdest);
364                         }
365                 }
366         }
367
368         return 0;
369 }
370
371 /* -->> -->> -->> -->>
372
373   BMP IMAGE FORMAT
374
375  <<-- <<-- <<-- <<-- */
376
377 /* WORD defines a two byte word */
378 typedef unsigned short int WORD;
379
380 /* DWORD defines a four byte word */
381 typedef unsigned long int DWORD;
382
383 typedef struct {
384   WORD bfType;                  /* 'BM' for Bitmap (19776) */
385   DWORD bfSize;                 /* Size of the file        */
386   WORD bfReserved1;             /* Reserved : 0            */
387   WORD bfReserved2;             /* Reserved : 0            */
388   DWORD bfOffBits;              /* Offset                  */
389 } BITMAPFILEHEADER_t;
390
391 typedef struct {
392   DWORD biSize;                 /* Size of the structure in bytes */
393   DWORD biWidth;                /* Width of the image in pixels */
394   DWORD biHeight;               /* Heigth of the image in pixels */
395   WORD biPlanes;                /* 1 */
396   WORD biBitCount;              /* Number of color bits by pixels */
397   DWORD biCompression;          /* Type of encoding 0: none 1: RLE8 2: RLE4 */
398   DWORD biSizeImage;            /* Size of the image in bytes */
399   DWORD biXpelsPerMeter;        /* Horizontal (X) resolution in pixels/meter */
400   DWORD biYpelsPerMeter;        /* Vertical (Y) resolution in pixels/meter */
401   DWORD biClrUsed;              /* Number of color used in the image (0: ALL) */
402   DWORD biClrImportant;         /* Number of important color (0: ALL) */
403 } BITMAPINFOHEADER_t;
404
405 opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) {
406         int subsampling_dx = parameters->subsampling_dx;
407         int subsampling_dy = parameters->subsampling_dy;
408
409         int i, numcomps, w, h;
410         OPJ_COLOR_SPACE color_space;
411         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
412         opj_image_t * image = NULL;
413
414         FILE *IN;
415         BITMAPFILEHEADER_t File_h;
416         BITMAPINFOHEADER_t Info_h;
417         unsigned char *RGB;
418         unsigned char *table_R, *table_G, *table_B;
419         unsigned int j, PAD = 0;
420
421         int x, y, index;
422         int gray_scale = 1, not_end_file = 1; 
423
424         unsigned int line = 0, col = 0;
425         unsigned char v, v2;
426         DWORD W, H;
427   
428         IN = fopen(filename, "rb");
429         if (!IN) {
430                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
431                 return 0;
432         }
433         
434         File_h.bfType = getc(IN);
435         File_h.bfType = (getc(IN) << 8) + File_h.bfType;
436         
437         if (File_h.bfType != 19778) {
438                 fprintf(stderr,"Error, not a BMP file!\n");
439                 return 0;
440         } else {
441                 /* FILE HEADER */
442                 /* ------------- */
443                 File_h.bfSize = getc(IN);
444                 File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
445                 File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
446                 File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
447
448                 File_h.bfReserved1 = getc(IN);
449                 File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
450
451                 File_h.bfReserved2 = getc(IN);
452                 File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
453
454                 File_h.bfOffBits = getc(IN);
455                 File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
456                 File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
457                 File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
458
459                 /* INFO HEADER */
460                 /* ------------- */
461
462                 Info_h.biSize = getc(IN);
463                 Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
464                 Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
465                 Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
466
467                 Info_h.biWidth = getc(IN);
468                 Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
469                 Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
470                 Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
471                 w = Info_h.biWidth;
472
473                 Info_h.biHeight = getc(IN);
474                 Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
475                 Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
476                 Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
477                 h = Info_h.biHeight;
478
479                 Info_h.biPlanes = getc(IN);
480                 Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
481
482                 Info_h.biBitCount = getc(IN);
483                 Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
484
485                 Info_h.biCompression = getc(IN);
486                 Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
487                 Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
488                 Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
489
490                 Info_h.biSizeImage = getc(IN);
491                 Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
492                 Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
493                 Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
494
495                 Info_h.biXpelsPerMeter = getc(IN);
496                 Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
497                 Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
498                 Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
499
500                 Info_h.biYpelsPerMeter = getc(IN);
501                 Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
502                 Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
503                 Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
504
505                 Info_h.biClrUsed = getc(IN);
506                 Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
507                 Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
508                 Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
509
510                 Info_h.biClrImportant = getc(IN);
511                 Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
512                 Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
513                 Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
514
515                 /* Read the data and store them in the OUT file */
516     
517                 if (Info_h.biBitCount == 24) {
518                         numcomps = 3;
519                         color_space = CLRSPC_SRGB;
520                         /* initialize image components */
521                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
522                         for(i = 0; i < numcomps; i++) {
523                                 cmptparm[i].prec = 8;
524                                 cmptparm[i].bpp = 8;
525                                 cmptparm[i].sgnd = 0;
526                                 cmptparm[i].dx = subsampling_dx;
527                                 cmptparm[i].dy = subsampling_dy;
528                                 cmptparm[i].w = w;
529                                 cmptparm[i].h = h;
530                         }
531                         /* create the image */
532                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
533                         if(!image) {
534                                 fclose(IN);
535                                 return NULL;
536                         }
537
538                         /* set image offset and reference grid */
539                         image->x0 = parameters->image_offset_x0;
540                         image->y0 = parameters->image_offset_y0;
541                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
542                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
543
544                         /* set image data */
545
546                         /* Place the cursor at the beginning of the image information */
547                         fseek(IN, 0, SEEK_SET);
548                         fseek(IN, File_h.bfOffBits, SEEK_SET);
549                         
550                         W = Info_h.biWidth;
551                         H = Info_h.biHeight;
552
553                         /* PAD = 4 - (3 * W) % 4; */
554                         /* PAD = (PAD == 4) ? 0 : PAD; */
555                         PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
556                         
557                         RGB = (unsigned char *) malloc((3 * W + PAD) * H * sizeof(unsigned char));
558                         
559                         fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN);
560                         
561                         index = 0;
562
563                         for(y = 0; y < (int)H; y++) {
564                                 unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
565                                 for(x = 0; x < (int)W; x++) {
566                                         unsigned char *pixel = &scanline[3 * x];
567                                         image->comps[0].data[index] = pixel[2]; /* R */
568                                         image->comps[1].data[index] = pixel[1]; /* G */
569                                         image->comps[2].data[index] = pixel[0]; /* B */
570                                         index++;
571                                 }
572                         }
573
574                         free(RGB);
575
576                 } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) {
577                         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
578                         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
579                         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
580                         
581                         for (j = 0; j < Info_h.biClrUsed; j++) {
582                                 table_B[j] = getc(IN);
583                                 table_G[j] = getc(IN);
584                                 table_R[j] = getc(IN);
585                                 getc(IN);
586                                 if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
587                                         gray_scale = 0;
588                         }
589                         
590                         /* Place the cursor at the beginning of the image information */
591                         fseek(IN, 0, SEEK_SET);
592                         fseek(IN, File_h.bfOffBits, SEEK_SET);
593                         
594                         W = Info_h.biWidth;
595                         H = Info_h.biHeight;
596                         if (Info_h.biWidth % 2)
597                                 W++;
598                         
599                         numcomps = gray_scale ? 1 : 3;
600                         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
601                         /* initialize image components */
602                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
603                         for(i = 0; i < numcomps; i++) {
604                                 cmptparm[i].prec = 8;
605                                 cmptparm[i].bpp = 8;
606                                 cmptparm[i].sgnd = 0;
607                                 cmptparm[i].dx = subsampling_dx;
608                                 cmptparm[i].dy = subsampling_dy;
609                                 cmptparm[i].w = w;
610                                 cmptparm[i].h = h;
611                         }
612                         /* create the image */
613                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
614                         if(!image) {
615                                 fclose(IN);
616                                 return NULL;
617                         }
618
619                         /* set image offset and reference grid */
620                         image->x0 = parameters->image_offset_x0;
621                         image->y0 = parameters->image_offset_y0;
622                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
623                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
624
625                         /* set image data */
626
627                         RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
628                         
629                         fread(RGB, sizeof(unsigned char), W * H, IN);
630                         if (gray_scale) {
631                                 index = 0;
632                                 for (j = 0; j < W * H; j++) {
633                                         if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
634                                                 image->comps[0].data[index] = table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
635                                                 index++;
636                                         }
637                                 }
638
639                         } else {                
640                                 index = 0;
641                                 for (j = 0; j < W * H; j++) {
642                                         if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
643                                                 unsigned char pixel_index = RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
644                                                 image->comps[0].data[index] = table_R[pixel_index];
645                                                 image->comps[1].data[index] = table_G[pixel_index];
646                                                 image->comps[2].data[index] = table_B[pixel_index];
647                                                 index++;
648                                         }
649                                 }
650                         }
651                         free(RGB);
652       free(table_R);
653       free(table_G);
654       free(table_B);
655                 } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) {                               
656                         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
657                         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
658                         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
659                         
660                         for (j = 0; j < Info_h.biClrUsed; j++) {
661                                 table_B[j] = getc(IN);
662                                 table_G[j] = getc(IN);
663                                 table_R[j] = getc(IN);
664                                 getc(IN);
665                                 if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
666                                         gray_scale = 0;
667                         }
668
669                         numcomps = gray_scale ? 1 : 3;
670                         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
671                         /* initialize image components */
672                         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
673                         for(i = 0; i < numcomps; i++) {
674                                 cmptparm[i].prec = 8;
675                                 cmptparm[i].bpp = 8;
676                                 cmptparm[i].sgnd = 0;
677                                 cmptparm[i].dx = subsampling_dx;
678                                 cmptparm[i].dy = subsampling_dy;
679                                 cmptparm[i].w = w;
680                                 cmptparm[i].h = h;
681                         }
682                         /* create the image */
683                         image = opj_image_create(numcomps, &cmptparm[0], color_space);
684                         if(!image) {
685                                 fclose(IN);
686                                 return NULL;
687                         }
688
689                         /* set image offset and reference grid */
690                         image->x0 = parameters->image_offset_x0;
691                         image->y0 = parameters->image_offset_y0;
692                         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
693                         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
694
695                         /* set image data */
696                         
697                         /* Place the cursor at the beginning of the image information */
698                         fseek(IN, 0, SEEK_SET);
699                         fseek(IN, File_h.bfOffBits, SEEK_SET);
700                         
701                         RGB = (unsigned char *) malloc(Info_h.biWidth * Info_h.biHeight * sizeof(unsigned char));
702             
703                         while (not_end_file) {
704                                 v = getc(IN);
705                                 if (v) {
706                                         v2 = getc(IN);
707                                         for (i = 0; i < (int) v; i++) {
708                                                 RGB[line * Info_h.biWidth + col] = v2;
709                                                 col++;
710                                         }
711                                 } else {
712                                         v = getc(IN);
713                                         switch (v) {
714                                                 case 0:
715                                                         col = 0;
716                                                         line++;
717                                                         break;
718                                                 case 1:
719                                                         line++;
720                                                         not_end_file = 0;
721                                                         break;
722                                                 case 2:
723                                                         fprintf(stderr,"No Delta supported\n");
724                                                         opj_image_destroy(image);
725                                                         fclose(IN);
726                                                         return NULL;
727                                                 default:
728                                                         for (i = 0; i < v; i++) {
729                                                                 v2 = getc(IN);
730                                                                 RGB[line * Info_h.biWidth + col] = v2;
731                                                                 col++;
732                                                         }
733                                                         if (v % 2)
734                                                                 v2 = getc(IN);
735                                                         break;
736                                         }
737                                 }
738                         }
739                         if (gray_scale) {
740                                 index = 0;
741                                 for (line = 0; line < Info_h.biHeight; line++) {
742                                         for (col = 0; col < Info_h.biWidth; col++) {
743                                                 image->comps[0].data[index] = table_R[(int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col]];
744                                                 index++;
745                                         }
746                                 }
747                         } else {
748                                 index = 0;
749                                 for (line = 0; line < Info_h.biHeight; line++) {
750                                         for (col = 0; col < Info_h.biWidth; col++) {
751                                                 unsigned char pixel_index = (int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col];
752                                                 image->comps[0].data[index] = table_R[pixel_index];
753                                                 image->comps[1].data[index] = table_G[pixel_index];
754                                                 image->comps[2].data[index] = table_B[pixel_index];
755                                                 index++;
756                                         }
757                                 }
758                         }
759                         free(RGB);
760       free(table_R);
761       free(table_G);
762       free(table_B);
763         } else {
764                 fprintf(stderr, 
765                         "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
766         }
767         fclose(IN);
768  }
769  
770  return image;
771 }
772
773 int imagetobmp(opj_image_t * image, const char *outfile) {
774         int w, h;
775         int i, pad;
776         FILE *fdest = NULL;
777         int adjustR, adjustG, adjustB;
778
779         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
780                 && image->comps[1].dx == image->comps[2].dx
781                 && image->comps[0].dy == image->comps[1].dy
782                 && image->comps[1].dy == image->comps[2].dy
783                 && image->comps[0].prec == image->comps[1].prec
784                 && image->comps[1].prec == image->comps[2].prec) {
785                 
786                 /* -->> -->> -->> -->>    
787                 24 bits color       
788                 <<-- <<-- <<-- <<-- */
789             
790                 fdest = fopen(outfile, "wb");
791                 if (!fdest) {
792                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
793                         return 1;
794                 }
795             
796                 w = image->comps[0].w;      
797                 h = image->comps[0].h;
798             
799                 fprintf(fdest, "BM");
800             
801                 /* FILE HEADER */
802                 /* ------------- */
803                 fprintf(fdest, "%c%c%c%c",
804                         (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
805                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
806                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
807                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
808                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
809                 fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
810             
811                 /* INFO HEADER   */
812                 /* ------------- */
813                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
814                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
815                         (unsigned char) ((w) >> 8) & 0xff,
816                         (unsigned char) ((w) >> 16) & 0xff,
817                         (unsigned char) ((w) >> 24) & 0xff);
818                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
819                         (unsigned char) ((h) >> 8) & 0xff,
820                         (unsigned char) ((h) >> 16) & 0xff,
821                         (unsigned char) ((h) >> 24) & 0xff);
822                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
823                 fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
824                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
825                 fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
826                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
827                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
828                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 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", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
831                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
832                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
833             
834                 if (image->comps[0].prec > 8) {
835                         adjustR = image->comps[0].prec - 8;
836                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
837                 }
838                 else 
839                         adjustR = 0;
840                 if (image->comps[1].prec > 8) {
841                         adjustG = image->comps[1].prec - 8;
842                         printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
843                 }
844                 else 
845                         adjustG = 0;
846                 if (image->comps[2].prec > 8) {
847                         adjustB = image->comps[2].prec - 8;
848                         printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
849                 }
850                 else 
851                         adjustB = 0;
852
853                 for (i = 0; i < w * h; i++) {
854                         unsigned char rc, gc, bc;
855                         int r, g, b;
856                                                         
857                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
858                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
859                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
860                         g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
861                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
862                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
863                         b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
864                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
865                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
866
867                         fprintf(fdest, "%c%c%c", bc, gc, rc);
868                         
869                         if ((i + 1) % w == 0) {
870                                 for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
871                                         fprintf(fdest, "%c", 0);
872                         }
873                 }
874                 fclose(fdest);
875         } else {                        /* Gray-scale */
876
877                 /* -->> -->> -->> -->>
878                 8 bits non code (Gray scale)
879                 <<-- <<-- <<-- <<-- */
880
881                 fdest = fopen(outfile, "wb");
882                 w = image->comps[0].w;      
883                 h = image->comps[0].h;
884             
885                 fprintf(fdest, "BM");
886             
887                 /* FILE HEADER */
888                 /* ------------- */
889                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
890                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
891                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
892                         (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
893                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
894                 fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
895                         ((54 + 1024) >> 16) & 0xff,
896                         ((54 + 1024) >> 24) & 0xff);
897             
898                 /* INFO HEADER */
899                 /* ------------- */
900                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
901                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
902                         (unsigned char) ((w) >> 8) & 0xff,
903                         (unsigned char) ((w) >> 16) & 0xff,
904                         (unsigned char) ((w) >> 24) & 0xff);
905                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
906                         (unsigned char) ((h) >> 8) & 0xff,
907                         (unsigned char) ((h) >> 16) & 0xff,
908                         (unsigned char) ((h) >> 24) & 0xff);
909                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
910                 fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
911                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
912                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
913                         (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
914                         (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
915                         (unsigned char) ((h * w + h * (w % 2)) >> 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", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
918                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
919                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
920
921                 if (image->comps[0].prec > 8) {
922                         adjustR = image->comps[0].prec - 8;
923                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
924                 }else 
925                         adjustR = 0;
926
927                 for (i = 0; i < 256; i++) {
928                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
929                 }
930
931                 for (i = 0; i < w * h; i++) {
932                         unsigned char rc;
933                         int r;
934                         
935                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
936                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
937                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
938                         
939                         fprintf(fdest, "%c", rc);
940
941                         if ((i + 1) % w == 0) {
942                                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
943                                         fprintf(fdest, "%c", 0);
944                         }
945                 }
946                 fclose(fdest);
947         }
948
949         return 0;
950 }
951
952 /* -->> -->> -->> -->>
953
954 PGX IMAGE FORMAT
955
956 <<-- <<-- <<-- <<-- */
957
958
959 unsigned char readuchar(FILE * f)
960 {
961   unsigned char c1;
962   fread(&c1, 1, 1, f);
963   return c1;
964 }
965
966 unsigned short readushort(FILE * f, int bigendian)
967 {
968   unsigned char c1, c2;
969   fread(&c1, 1, 1, f);
970   fread(&c2, 1, 1, f);
971   if (bigendian)
972     return (c1 << 8) + c2;
973   else
974     return (c2 << 8) + c1;
975 }
976
977 unsigned int readuint(FILE * f, int bigendian)
978 {
979   unsigned char c1, c2, c3, c4;
980   fread(&c1, 1, 1, f);
981   fread(&c2, 1, 1, f);
982   fread(&c3, 1, 1, f);
983   fread(&c4, 1, 1, f);
984   if (bigendian)
985     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
986   else
987     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
988 }
989
990 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
991         FILE *f = NULL;
992         int w, h, prec;
993         int i, numcomps, max;
994         OPJ_COLOR_SPACE color_space;
995         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
996         opj_image_t * image = NULL;
997
998         char endian1,endian2,sign;
999         char signtmp[32];
1000
1001         char temp[32];
1002         int bigendian;
1003         opj_image_comp_t *comp = NULL;
1004
1005         numcomps = 1;
1006         color_space = CLRSPC_GRAY;
1007
1008         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1009
1010         max = 0;
1011
1012         f = fopen(filename, "rb");
1013         if (!f) {
1014           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1015           return NULL;
1016         }
1017
1018         fseek(f, 0, SEEK_SET);
1019         fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
1020         
1021         i=0;
1022         sign='+';               
1023         while (signtmp[i]!='\0') {
1024                 if (signtmp[i]=='-') sign='-';
1025                 i++;
1026         }
1027         
1028         fgetc(f);
1029         if (endian1=='M' && endian2=='L') {
1030                 bigendian = 1;
1031         } else if (endian2=='M' && endian1=='L') {
1032                 bigendian = 0;
1033         } else {
1034                 fprintf(stderr, "Bad pgx header, please check input file\n");
1035                 return NULL;
1036         }
1037
1038         /* initialize image component */
1039
1040         cmptparm.x0 = parameters->image_offset_x0;
1041         cmptparm.y0 = parameters->image_offset_y0;
1042         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1043         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1044         
1045         if (sign == '-') {
1046                 cmptparm.sgnd = 1;
1047         } else {
1048                 cmptparm.sgnd = 0;
1049         }
1050         cmptparm.prec = prec;
1051         cmptparm.bpp = prec;
1052         cmptparm.dx = parameters->subsampling_dx;
1053         cmptparm.dy = parameters->subsampling_dy;
1054         
1055         /* create the image */
1056         image = opj_image_create(numcomps, &cmptparm, color_space);
1057         if(!image) {
1058                 fclose(f);
1059                 return NULL;
1060         }
1061         /* set image offset and reference grid */
1062         image->x0 = cmptparm.x0;
1063         image->y0 = cmptparm.x0;
1064         image->x1 = cmptparm.w;
1065         image->y1 = cmptparm.h;
1066
1067         /* set image data */
1068
1069         comp = &image->comps[0];
1070
1071         for (i = 0; i < w * h; i++) {
1072                 int v;
1073                 if (comp->prec <= 8) {
1074                         if (!comp->sgnd) {
1075                                 v = readuchar(f);
1076                         } else {
1077                                 v = (char) readuchar(f);
1078                         }
1079                 } else if (comp->prec <= 16) {
1080                         if (!comp->sgnd) {
1081                                 v = readushort(f, bigendian);
1082                         } else {
1083                                 v = (short) readushort(f, bigendian);
1084                         }
1085                 } else {
1086                         if (!comp->sgnd) {
1087                                 v = readuint(f, bigendian);
1088                         } else {
1089                                 v = (int) readuint(f, bigendian);
1090                         }
1091                 }
1092                 if (v > max)
1093                         max = v;
1094                 comp->data[i] = v;
1095         }
1096         fclose(f);
1097         comp->bpp = int_floorlog2(max) + 1;
1098
1099         return image;
1100 }
1101
1102 int imagetopgx(opj_image_t * image, const char *outfile) {
1103         int w, h;
1104         int i, j, compno;
1105         FILE *fdest = NULL;
1106
1107         for (compno = 0; compno < image->numcomps; compno++) {
1108                 opj_image_comp_t *comp = &image->comps[compno];
1109                 char bname[256]; /* buffer for name */
1110     char *name = bname; /* pointer */
1111     int nbytes = 0;
1112     const size_t olen = strlen(outfile);
1113     const size_t dotpos = olen - 4;
1114     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1115     if( outfile[dotpos] != '.' ) {
1116       /* `pgx` was recognized but there is no dot at expected position */
1117       fprintf(stderr, "ERROR -> Impossible happen." );
1118       return 1;
1119       }
1120     if( total > 256 ) {
1121       name = (char*)malloc(total+1);
1122       }
1123     strncpy(name, outfile, dotpos);
1124                 if (image->numcomps > 1) {
1125                         sprintf(name+dotpos, "-%d.pgx", compno);
1126                 } else {
1127                         strcpy(name+dotpos, ".pgx");
1128                 }
1129                 fdest = fopen(name, "wb");
1130                 if (!fdest) {
1131                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1132                         return 1;
1133                 }
1134     /* dont need name anymore */
1135     if( total > 256 ) {
1136       free(name);
1137       }
1138
1139                 w = image->comps[compno].w;
1140                 h = image->comps[compno].h;
1141             
1142                 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
1143                 if (comp->prec <= 8) {
1144                         nbytes = 1;
1145                 } else if (comp->prec <= 16) {
1146                         nbytes = 2;
1147                 } else {
1148                         nbytes = 4;
1149                 }
1150                 for (i = 0; i < w * h; i++) {
1151                         int v = image->comps[compno].data[i];
1152                         for (j = nbytes - 1; j >= 0; j--) {
1153                                 char byte = (char) (v >> (j * 8));
1154                                 fwrite(&byte, 1, 1, fdest);
1155                         }
1156                 }
1157                 fclose(fdest);
1158         }
1159
1160         return 0;
1161 }
1162
1163 /* -->> -->> -->> -->>
1164
1165 PNM IMAGE FORMAT
1166
1167 <<-- <<-- <<-- <<-- */
1168
1169 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1170         int subsampling_dx = parameters->subsampling_dx;
1171         int subsampling_dy = parameters->subsampling_dy;
1172
1173         FILE *f = NULL;
1174         int i, compno, numcomps, w, h;
1175         OPJ_COLOR_SPACE color_space;
1176         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
1177         opj_image_t * image = NULL;
1178         char value;
1179         
1180         f = fopen(filename, "rb");
1181         if (!f) {
1182                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1183                 return 0;
1184         }
1185
1186         if (fgetc(f) != 'P')
1187                 return 0;
1188         value = fgetc(f);
1189
1190                 switch(value) {
1191                         case '2':       /* greyscale image type */
1192                         case '5':
1193                                 numcomps = 1;
1194                                 color_space = CLRSPC_GRAY;
1195                                 break;
1196                                 
1197                         case '3':       /* RGB image type */
1198                         case '6':
1199                                 numcomps = 3;
1200                                 color_space = CLRSPC_SRGB;
1201                                 break;
1202                                 
1203                         default:
1204                                 fclose(f);
1205                                 return NULL;
1206                 }
1207                 
1208                 fgetc(f);
1209                 
1210                 /* skip comments */
1211                 while(fgetc(f) == '#') while(fgetc(f) != '\n');
1212                 
1213                 fseek(f, -1, SEEK_CUR);
1214                 fscanf(f, "%d %d\n255", &w, &h);                        
1215                 fgetc(f);       /* <cr><lf> */
1216                 
1217         /* initialize image components */
1218         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1219         for(i = 0; i < numcomps; i++) {
1220                 cmptparm[i].prec = 8;
1221                 cmptparm[i].bpp = 8;
1222                 cmptparm[i].sgnd = 0;
1223                 cmptparm[i].dx = subsampling_dx;
1224                 cmptparm[i].dy = subsampling_dy;
1225                 cmptparm[i].w = w;
1226                 cmptparm[i].h = h;
1227         }
1228         /* create the image */
1229         image = opj_image_create(numcomps, &cmptparm[0], color_space);
1230         if(!image) {
1231                 fclose(f);
1232                 return NULL;
1233         }
1234
1235         /* set image offset and reference grid */
1236         image->x0 = parameters->image_offset_x0;
1237         image->y0 = parameters->image_offset_y0;
1238         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1239         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1240
1241         /* set image data */
1242
1243         if ((value == '2') || (value == '3')) { /* ASCII */
1244                 for (i = 0; i < w * h; i++) {
1245                         for(compno = 0; compno < numcomps; compno++) {
1246                                 unsigned int index = 0;
1247                                 fscanf(f, "%u", &index);
1248                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1249                                 image->comps[compno].data[i] = index;
1250                         }
1251                 }
1252         } else if ((value == '5') || (value == '6')) {  /* BINARY */
1253                 for (i = 0; i < w * h; i++) {
1254                         for(compno = 0; compno < numcomps; compno++) {
1255                                 unsigned char index = 0;
1256                                 fread(&index, 1, 1, f);
1257                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1258                                 image->comps[compno].data[i] = index;
1259                         }
1260                 }
1261         }
1262
1263         fclose(f);
1264
1265         return image;
1266 }
1267
1268 int imagetopnm(opj_image_t * image, const char *outfile) {
1269         int w, wr, h, hr, max;
1270         int i, 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                 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         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 = (unsigned char) (curr >> 8);
2127                                                 fwrite(&temp, 1, 1, rawFile);
2128                                                 temp = (unsigned char) 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 = (unsigned char) (curr >> 8);
2144                                                 fwrite(&temp, 1, 1, rawFile);
2145                                                 temp = (unsigned char) 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