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