Added support for the TGA file format in the codec
[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  = int_ceildiv(image->x1-image->x0, image->comps[0].dx);
314         height = int_ceildiv(image->y1-image->y0, image->comps[0].dy);
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, wr, h, hr;
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                 wr = int_ceildivpow2(image->comps[0].w, image->comps[0].factor);
791             
792                 h = image->comps[0].h;
793                 hr = int_ceildivpow2(image->comps[0].h, image->comps[0].factor);
794             
795                 fprintf(fdest, "BM");
796             
797                 /* FILE HEADER */
798                 /* ------------- */
799                 fprintf(fdest, "%c%c%c%c",
800                         (unsigned char) (hr * wr * 3 + 3 * hr * (wr % 2) + 54) & 0xff,
801                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54) >> 8) & 0xff,
802                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54) >> 16) & 0xff,
803                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54) >> 24) & 0xff);
804                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
805                 fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
806             
807                 /* INFO HEADER   */
808                 /* ------------- */
809                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
810                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((wr) & 0xff),
811                         (unsigned char) ((wr) >> 8) & 0xff,
812                         (unsigned char) ((wr) >> 16) & 0xff,
813                         (unsigned char) ((wr) >> 24) & 0xff);
814                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((hr) & 0xff),
815                         (unsigned char) ((hr) >> 8) & 0xff,
816                         (unsigned char) ((hr) >> 16) & 0xff,
817                         (unsigned char) ((hr) >> 24) & 0xff);
818                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
819                 fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
820                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
821                 fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * hr * wr + 3 * hr * (wr % 2)) & 0xff,
822                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >> 8) & 0xff,
823                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >> 16) & 0xff,
824                         (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >> 24) & 0xff);
825                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
826                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
827                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
828                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
829             
830                 if (image->comps[0].prec > 8) {
831                         adjustR = image->comps[0].prec - 8;
832                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
833                 }
834                 else 
835                         adjustR = 0;
836                 if (image->comps[1].prec > 8) {
837                         adjustG = image->comps[1].prec - 8;
838                         printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
839                 }
840                 else 
841                         adjustG = 0;
842                 if (image->comps[2].prec > 8) {
843                         adjustB = image->comps[2].prec - 8;
844                         printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
845                 }
846                 else 
847                         adjustB = 0;
848
849                 for (i = 0; i < wr * hr; i++) {
850                         unsigned char rc, gc, bc;
851                         int r, g, b;
852                                                         
853                         r = image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
854                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
855                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
856                         g = image->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
857                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
858                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
859                         b = image->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
860                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
861                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
862
863                         fprintf(fdest, "%c%c%c", bc, gc, rc);
864                         
865                         if ((i + 1) % wr == 0) {
866                                 for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* ADD */
867                                         fprintf(fdest, "%c", 0);
868                         }
869                 }
870                 fclose(fdest);
871         } else {                        /* Gray-scale */
872
873                 /* -->> -->> -->> -->>
874                 8 bits non code (Gray scale)
875                 <<-- <<-- <<-- <<-- */
876
877                 fdest = fopen(outfile, "wb");
878                 w = image->comps[0].w;
879                 wr = int_ceildivpow2(image->comps[0].w, image->comps[0].factor);
880             
881                 h = image->comps[0].h;
882                 hr = int_ceildivpow2(image->comps[0].h, image->comps[0].factor);
883             
884                 fprintf(fdest, "BM");
885             
886                 /* FILE HEADER */
887                 /* ------------- */
888                 fprintf(fdest, "%c%c%c%c", (unsigned char) (hr * wr + 54 + 1024 + hr * (wr % 2)) & 0xff,
889                         (unsigned char) ((hr * wr + 54 + 1024 + hr * (wr % 2)) >> 8) & 0xff,
890                         (unsigned char) ((hr * wr + 54 + 1024 + hr * (wr % 2)) >> 16) & 0xff,
891                         (unsigned char) ((hr * wr + 54 + 1024 + wr * (wr % 2)) >> 24) & 0xff);
892                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
893                 fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
894                         ((54 + 1024) >> 16) & 0xff,
895                         ((54 + 1024) >> 24) & 0xff);
896             
897                 /* INFO HEADER */
898                 /* ------------- */
899                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
900                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((wr) & 0xff),
901                         (unsigned char) ((wr) >> 8) & 0xff,
902                         (unsigned char) ((wr) >> 16) & 0xff,
903                         (unsigned char) ((wr) >> 24) & 0xff);
904                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((hr) & 0xff),
905                         (unsigned char) ((hr) >> 8) & 0xff,
906                         (unsigned char) ((hr) >> 16) & 0xff,
907                         (unsigned char) ((hr) >> 24) & 0xff);
908                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
909                 fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
910                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
911                 fprintf(fdest, "%c%c%c%c", (unsigned char) (hr * wr + hr * (wr % 2)) & 0xff,
912                         (unsigned char) ((hr * wr + hr * (wr % 2)) >> 8) &      0xff,
913                         (unsigned char) ((hr * wr + hr * (wr % 2)) >> 16) &     0xff,
914                         (unsigned char) ((hr * wr + hr * (wr % 2)) >> 24) & 0xff);
915                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
916                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
917                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
918                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
919
920                 if (image->comps[0].prec > 8) {
921                         adjustR = image->comps[0].prec - 8;
922                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
923                 }
924
925                 for (i = 0; i < 256; i++) {
926                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
927                 }
928
929                 for (i = 0; i < wr * hr; i++) {
930                         unsigned char rc;
931                         int r;
932                         
933                         r = image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
934                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
935                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
936                         
937                         fprintf(fdest, "%c", rc);
938
939                         if ((i + 1) % wr == 0) {
940                                 for (pad = wr % 4 ? 4 - wr % 4 : 0; pad > 0; pad--)     /* ADD */
941                                         fprintf(fdest, "%c", 0);
942                         }
943                 }
944                 fclose(fdest);
945         }
946
947         return 0;
948 }
949
950 /* -->> -->> -->> -->>
951
952 PGX IMAGE FORMAT
953
954 <<-- <<-- <<-- <<-- */
955
956
957 unsigned char readuchar(FILE * f)
958 {
959   unsigned char c1;
960   fread(&c1, 1, 1, f);
961   return c1;
962 }
963
964 unsigned short readushort(FILE * f, int bigendian)
965 {
966   unsigned char c1, c2;
967   fread(&c1, 1, 1, f);
968   fread(&c2, 1, 1, f);
969   if (bigendian)
970     return (c1 << 8) + c2;
971   else
972     return (c2 << 8) + c1;
973 }
974
975 unsigned int readuint(FILE * f, int bigendian)
976 {
977   unsigned char c1, c2, c3, c4;
978   fread(&c1, 1, 1, f);
979   fread(&c2, 1, 1, f);
980   fread(&c3, 1, 1, f);
981   fread(&c4, 1, 1, f);
982   if (bigendian)
983     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
984   else
985     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
986 }
987
988 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
989         FILE *f = NULL;
990         int w, h, prec;
991         int i, numcomps, max;
992         OPJ_COLOR_SPACE color_space;
993         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
994         opj_image_t * image = NULL;
995
996         char endian1,endian2,sign;
997         char signtmp[32];
998
999         char temp[32];
1000         int bigendian;
1001         opj_image_comp_t *comp = NULL;
1002
1003         numcomps = 1;
1004         color_space = CLRSPC_GRAY;
1005
1006         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1007
1008         max = 0;
1009
1010         f = fopen(filename, "rb");
1011         if (!f) {
1012           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1013           return NULL;
1014         }
1015
1016         fseek(f, 0, SEEK_SET);
1017         fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
1018         
1019         i=0;
1020         sign='+';               
1021         while (signtmp[i]!='\0') {
1022                 if (signtmp[i]=='-') sign='-';
1023                 i++;
1024         }
1025         
1026         fgetc(f);
1027         if (endian1=='M' && endian2=='L') {
1028                 bigendian = 1;
1029         } else if (endian2=='M' && endian1=='L') {
1030                 bigendian = 0;
1031         } else {
1032                 fprintf(stderr, "Bad pgx header, please check input file\n");
1033                 return NULL;
1034         }
1035
1036         /* initialize image component */
1037
1038         cmptparm.x0 = parameters->image_offset_x0;
1039         cmptparm.y0 = parameters->image_offset_y0;
1040         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1041         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1042         
1043         if (sign == '-') {
1044                 cmptparm.sgnd = 1;
1045         } else {
1046                 cmptparm.sgnd = 0;
1047         }
1048         cmptparm.prec = prec;
1049         cmptparm.bpp = prec;
1050         cmptparm.dx = parameters->subsampling_dx;
1051         cmptparm.dy = parameters->subsampling_dy;
1052         
1053         /* create the image */
1054         image = opj_image_create(numcomps, &cmptparm, color_space);
1055         if(!image) {
1056                 fclose(f);
1057                 return NULL;
1058         }
1059         /* set image offset and reference grid */
1060         image->x0 = cmptparm.x0;
1061         image->y0 = cmptparm.x0;
1062         image->x1 = cmptparm.w;
1063         image->y1 = cmptparm.h;
1064
1065         /* set image data */
1066
1067         comp = &image->comps[0];
1068
1069         for (i = 0; i < w * h; i++) {
1070                 int v;
1071                 if (comp->prec <= 8) {
1072                         if (!comp->sgnd) {
1073                                 v = readuchar(f);
1074                         } else {
1075                                 v = (char) readuchar(f);
1076                         }
1077                 } else if (comp->prec <= 16) {
1078                         if (!comp->sgnd) {
1079                                 v = readushort(f, bigendian);
1080                         } else {
1081                                 v = (short) readushort(f, bigendian);
1082                         }
1083                 } else {
1084                         if (!comp->sgnd) {
1085                                 v = readuint(f, bigendian);
1086                         } else {
1087                                 v = (int) readuint(f, bigendian);
1088                         }
1089                 }
1090                 if (v > max)
1091                         max = v;
1092                 comp->data[i] = v;
1093         }
1094         fclose(f);
1095         comp->bpp = int_floorlog2(max) + 1;
1096
1097         return image;
1098 }
1099
1100 int imagetopgx(opj_image_t * image, const char *outfile) {
1101         int w, wr, h, hr;
1102         int i, j, compno;
1103         FILE *fdest = NULL;
1104
1105         for (compno = 0; compno < image->numcomps; compno++) {
1106                 opj_image_comp_t *comp = &image->comps[compno];
1107                 char bname[256]; /* buffer for name */
1108     char *name = bname; /* pointer */
1109     int nbytes = 0;
1110     const size_t olen = strlen(outfile);
1111     const size_t dotpos = olen - 4;
1112     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1113     if( outfile[dotpos] != '.' ) {
1114       /* `pgx` was recognized but there is no dot at expected position */
1115       fprintf(stderr, "ERROR -> Impossible happen." );
1116       return 1;
1117       }
1118     if( total > 256 ) {
1119       name = (char*)malloc(total+1);
1120       }
1121     strncpy(name, outfile, dotpos);
1122                 if (image->numcomps > 1) {
1123                         sprintf(name+dotpos, "-%d.pgx", compno);
1124                 } else {
1125                         strcpy(name+dotpos, ".pgx");
1126                 }
1127                 fdest = fopen(name, "wb");
1128                 if (!fdest) {
1129                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1130                         return 1;
1131                 }
1132     /* dont need name anymore */
1133     if( total > 256 ) {
1134       free(name);
1135       }
1136
1137                 w = image->comps[compno].w;
1138                 wr = int_ceildivpow2(image->comps[compno].w, image->comps[compno].factor);
1139             
1140                 h = image->comps[compno].h;
1141                 hr = int_ceildivpow2(image->comps[compno].h, image->comps[compno].factor);
1142             
1143                 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, wr, hr);
1144                 if (comp->prec <= 8) {
1145                         nbytes = 1;
1146                 } else if (comp->prec <= 16) {
1147                         nbytes = 2;
1148                 } else {
1149                         nbytes = 4;
1150                 }
1151                 for (i = 0; i < wr * hr; i++) {
1152                         int v = image->comps[compno].data[i / wr * w + i % wr];
1153                         for (j = nbytes - 1; j >= 0; j--) {
1154                                 char byte = (char) (v >> (j * 8));
1155                                 fwrite(&byte, 1, 1, fdest);
1156                         }
1157                 }
1158                 fclose(fdest);
1159         }
1160
1161         return 0;
1162 }
1163
1164 /* -->> -->> -->> -->>
1165
1166 PNM IMAGE FORMAT
1167
1168 <<-- <<-- <<-- <<-- */
1169
1170 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1171         int subsampling_dx = parameters->subsampling_dx;
1172         int subsampling_dy = parameters->subsampling_dy;
1173
1174         FILE *f = NULL;
1175         int i, compno, numcomps, w, h;
1176         OPJ_COLOR_SPACE color_space;
1177         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
1178         opj_image_t * image = NULL;
1179         char value;
1180         
1181         f = fopen(filename, "rb");
1182         if (!f) {
1183                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1184                 return 0;
1185         }
1186
1187         if (fgetc(f) != 'P')
1188                 return 0;
1189         value = fgetc(f);
1190
1191                 switch(value) {
1192                         case '2':       /* greyscale image type */
1193                         case '5':
1194                                 numcomps = 1;
1195                                 color_space = CLRSPC_GRAY;
1196                                 break;
1197                                 
1198                         case '3':       /* RGB image type */
1199                         case '6':
1200                                 numcomps = 3;
1201                                 color_space = CLRSPC_SRGB;
1202                                 break;
1203                                 
1204                         default:
1205                                 fclose(f);
1206                                 return NULL;
1207                 }
1208                 
1209                 fgetc(f);
1210                 
1211                 /* skip comments */
1212                 while(fgetc(f) == '#') while(fgetc(f) != '\n');
1213                 
1214                 fseek(f, -1, SEEK_CUR);
1215                 fscanf(f, "%d %d\n255", &w, &h);                        
1216                 fgetc(f);       /* <cr><lf> */
1217                 
1218         /* initialize image components */
1219         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1220         for(i = 0; i < numcomps; i++) {
1221                 cmptparm[i].prec = 8;
1222                 cmptparm[i].bpp = 8;
1223                 cmptparm[i].sgnd = 0;
1224                 cmptparm[i].dx = subsampling_dx;
1225                 cmptparm[i].dy = subsampling_dy;
1226                 cmptparm[i].w = w;
1227                 cmptparm[i].h = h;
1228         }
1229         /* create the image */
1230         image = opj_image_create(numcomps, &cmptparm[0], color_space);
1231         if(!image) {
1232                 fclose(f);
1233                 return NULL;
1234         }
1235
1236         /* set image offset and reference grid */
1237         image->x0 = parameters->image_offset_x0;
1238         image->y0 = parameters->image_offset_y0;
1239         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1240         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1241
1242         /* set image data */
1243
1244         if ((value == '2') || (value == '3')) { /* ASCII */
1245                 for (i = 0; i < w * h; i++) {
1246                         for(compno = 0; compno < numcomps; compno++) {
1247                                 unsigned int index = 0;
1248                                 fscanf(f, "%u", &index);
1249                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1250                                 image->comps[compno].data[i] = index;
1251                         }
1252                 }
1253         } else if ((value == '5') || (value == '6')) {  /* BINARY */
1254                 for (i = 0; i < w * h; i++) {
1255                         for(compno = 0; compno < numcomps; compno++) {
1256                                 unsigned char index = 0;
1257                                 fread(&index, 1, 1, f);
1258                                 /* compno : 0 = GREY, (0, 1, 2) = (R, G, B) */
1259                                 image->comps[compno].data[i] = index;
1260                         }
1261                 }
1262         }
1263
1264         fclose(f);
1265
1266         return image;
1267 }
1268
1269 int imagetopnm(opj_image_t * image, const char *outfile) {
1270         int w, wr, wrr, h, hr, hrr, max;
1271         int i, compno;
1272         int adjustR, adjustG, adjustB, adjustX;
1273         FILE *fdest = NULL;
1274         char S2;
1275         const char *tmp = outfile;
1276
1277         while (*tmp) {
1278                 tmp++;
1279         }
1280         tmp--;
1281         tmp--;
1282         S2 = *tmp;
1283
1284         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1285                 && image->comps[1].dx == image->comps[2].dx
1286                 && image->comps[0].dy == image->comps[1].dy
1287                 && image->comps[1].dy == image->comps[2].dy
1288                 && image->comps[0].prec == image->comps[1].prec
1289                 && image->comps[1].prec == image->comps[2].prec
1290                 && S2 !='g' && S2 !='G') {
1291
1292                 fdest = fopen(outfile, "wb");
1293                 if (!fdest) {
1294                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1295                         return 1;
1296                 }
1297
1298                 w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
1299                 wr = image->comps[0].w;
1300                 wrr = int_ceildivpow2(image->comps[0].w, image->comps[0].factor);
1301         
1302                 h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
1303                 hr = image->comps[0].h;
1304                 hrr = int_ceildivpow2(image->comps[0].h, image->comps[0].factor);
1305             
1306                 max = image->comps[0].prec > 8 ? 255 : (1 << image->comps[0].prec) - 1;
1307             
1308                 image->comps[0].x0 = int_ceildivpow2(image->comps[0].x0 - int_ceildiv(image->x0, image->comps[0].dx), image->comps[0].factor);
1309                 image->comps[0].y0 = int_ceildivpow2(image->comps[0].y0 -       int_ceildiv(image->y0, image->comps[0].dy), image->comps[0].factor);
1310
1311                 fprintf(fdest, "P6\n%d %d\n%d\n", wrr, hrr, max);
1312
1313                 if (image->comps[0].prec > 8) {
1314                         adjustR = image->comps[0].prec - 8;
1315                         printf("PNM CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1316                 }
1317                 else 
1318                         adjustR = 0;
1319                 if (image->comps[1].prec > 8) {
1320                         adjustG = image->comps[1].prec - 8;
1321                         printf("PNM CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1322                 }
1323                 else 
1324                         adjustG = 0;
1325                 if (image->comps[2].prec > 8) {
1326                         adjustB = image->comps[2].prec - 8;
1327                         printf("PNM CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1328                 }
1329                 else 
1330                         adjustB = 0;
1331
1332
1333                 for (i = 0; i < wrr * hrr; i++) {
1334                         int r, g, b;
1335                         unsigned char rc,gc,bc;
1336                         r = image->comps[0].data[i / wrr * wr + i % wrr];
1337                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1338                         rc = (unsigned char) ((r >> adjustR)+((r >> (adjustR-1))%2));
1339
1340                         g = image->comps[1].data[i / wrr * wr + i % wrr];
1341                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1342                         gc = (unsigned char) ((g >> adjustG)+((g >> (adjustG-1))%2));
1343                         
1344                         b = image->comps[2].data[i / wrr * wr + i % wrr];
1345                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1346                         bc = (unsigned char) ((b >> adjustB)+((b >> (adjustB-1))%2));
1347                         
1348                         fprintf(fdest, "%c%c%c", rc, gc, bc);
1349                 }
1350                 fclose(fdest);
1351
1352         } else {
1353                 int ncomp=(S2=='g' || S2=='G')?1:image->numcomps;
1354                 if (image->numcomps > ncomp) {
1355                         fprintf(stderr,"WARNING -> [PGM files] Only the first component\n");
1356                         fprintf(stderr,"           is written to the file\n");
1357                 }
1358                 for (compno = 0; compno < ncomp; compno++) {
1359                         char name[256];
1360                         if (ncomp > 1) {
1361                                 sprintf(name, "%d.%s", compno, outfile);
1362                         } else {
1363                                 sprintf(name, "%s", outfile);
1364                         }
1365                         
1366                         fdest = fopen(name, "wb");
1367                         if (!fdest) {
1368                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1369                                 return 1;
1370                         }
1371             
1372                         w = int_ceildiv(image->x1 - image->x0, image->comps[compno].dx);
1373                         wr = image->comps[compno].w;
1374                         wrr = int_ceildivpow2(image->comps[compno].w, image->comps[compno].factor);
1375                         
1376                         h = int_ceildiv(image->y1 - image->y0, image->comps[compno].dy);
1377                         hr = image->comps[compno].h;
1378                         hrr = int_ceildivpow2(image->comps[compno].h, image->comps[compno].factor);
1379                         
1380                         max = image->comps[compno].prec > 8 ? 255 : (1 << image->comps[compno].prec) - 1;
1381                         
1382                         image->comps[compno].x0 = int_ceildivpow2(image->comps[compno].x0 - int_ceildiv(image->x0, image->comps[compno].dx), image->comps[compno].factor);
1383                         image->comps[compno].y0 = int_ceildivpow2(image->comps[compno].y0 - int_ceildiv(image->y0, image->comps[compno].dy), image->comps[compno].factor);
1384                         
1385                         fprintf(fdest, "P5\n%d %d\n%d\n", wrr, hrr, max);
1386                         
1387                         if (image->comps[compno].prec > 8) {
1388                                 adjustX = image->comps[0].prec - 8;
1389                                 printf("PNM CONVERSION: Truncating component %d from %d bits to 8 bits\n",compno, image->comps[compno].prec);
1390                         }
1391                         else 
1392                                 adjustX = 0;
1393                         
1394                         for (i = 0; i < wrr * hrr; i++) {
1395                                 int l;
1396                                 unsigned char lc;
1397                                 l = image->comps[compno].data[i / wrr * wr + i % wrr];
1398                                 l += (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1399                                 lc = (unsigned char) ((l >> adjustX)+((l >> (adjustX-1))%2));
1400                                 fprintf(fdest, "%c", lc);
1401                         }
1402                         fclose(fdest);
1403                 }
1404         }
1405
1406         return 0;
1407 }
1408
1409 /* -->> -->> -->> -->>
1410
1411         TIFF IMAGE FORMAT
1412
1413  <<-- <<-- <<-- <<-- */
1414
1415 typedef struct tiff_infoheader{
1416         DWORD tiWidth;  // Width of Image in pixel
1417         DWORD tiHeight; // Height of Image in pixel
1418         DWORD tiPhoto;  // Photometric
1419         WORD  tiBps;    // Bits per sample
1420         WORD  tiSf;             // Sample Format
1421         WORD  tiSpp;    // Sample per pixel 1-bilevel,gray scale , 2- RGB
1422         WORD  tiPC;     // Planar config (1-Interleaved, 2-Planarcomp)
1423 }tiff_infoheader_t;
1424
1425 int imagetotif(opj_image_t * image, const char *outfile) {
1426         int width, height;
1427         int bps,index;
1428         TIFF *tif;
1429         tdata_t buf;
1430         tstrip_t strip;
1431         tsize_t strip_size;
1432
1433         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1434                 && image->comps[1].dx == image->comps[2].dx
1435                 && image->comps[0].dy == image->comps[1].dy
1436                 && image->comps[1].dy == image->comps[2].dy
1437                 && image->comps[0].prec == image->comps[1].prec
1438                 && image->comps[1].prec == image->comps[2].prec) {
1439
1440                         /* -->> -->> -->>    
1441                         RGB color           
1442                         <<-- <<-- <<-- */
1443
1444                         tif = TIFFOpen(outfile, "wb"); 
1445                         if (!tif) {
1446                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1447                                 return 1;
1448                         }
1449
1450                         width   = image->comps[0].w;
1451                         height= image->comps[0].h;
1452                         bps             = image->comps[0].prec;
1453                         /* Set tags */
1454                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1455                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1456                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3);
1457                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1458                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1459                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1460                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1461                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1462
1463                         /* Get a buffer for the data */
1464                         buf = _TIFFmalloc(TIFFStripSize(tif));
1465                         index=0;
1466                         strip_size=0;
1467                         strip_size=TIFFStripSize(tif);
1468                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1469                                 unsigned char *dat8;
1470                                 int i;
1471                                 dat8 = buf;
1472                                 if (image->comps[0].prec == 8){
1473                                         for (i=0; i<TIFFStripSize(tif); i+=3) { // 8 bits per pixel 
1474                                                 dat8[i+0] = image->comps[0].data[index] ;       // R 
1475                                                 dat8[i+1] = image->comps[1].data[index] ;       // G 
1476                                                 dat8[i+2] = image->comps[2].data[index] ;       // B 
1477                                                 index++;
1478                                         }
1479                                 }else if (image->comps[0].prec == 12){
1480                                         for (i=0; i<TIFFStripSize(tif); i+=9) { // 12 bits per pixel 
1481                                                 dat8[i+0] = (image->comps[0].data[index]>>8)<<4 | (image->comps[0].data[index]>>4);
1482                                                 dat8[i+1] = (image->comps[0].data[index]<<4)|((image->comps[1].data[index]>>8)& 0x0f);
1483                                                 dat8[i+2] = (image->comps[1].data[index]);
1484                                                 dat8[i+3] = (image->comps[2].data[index]>>8)<<4 | (image->comps[2].data[index]>>4);
1485                                                 dat8[i+4] = (image->comps[2].data[index]<<4)|((image->comps[0].data[index+1]>>8)& 0x0f);
1486                                                 dat8[i+5] = (image->comps[0].data[index+1]);
1487                                                 dat8[i+6] = (image->comps[1].data[index+1]>>8)<<4 | (image->comps[1].data[index+1]>>4);
1488                                                 dat8[i+7] = (image->comps[1].data[index+1]<<4)|((image->comps[2].data[index+1]>>8)& 0x0f);
1489                                                 dat8[i+8] = (image->comps[2].data[index+1]);
1490                                                 index+=2;
1491                                         }
1492                                 }else if (image->comps[0].prec == 16){
1493                                         for (i=0; i<TIFFStripSize(tif); i+=6) { // 16 bits per pixel 
1494                                                 dat8[i+0] =  image->comps[0].data[index];//LSB
1495                                                 dat8[i+1] = (image->comps[0].data[index]>> 8);//MSB      
1496                                                 dat8[i+2] =  image->comps[1].data[index]; 
1497                                                 dat8[i+3] = (image->comps[1].data[index]>> 8);  
1498                                                 dat8[i+4] =  image->comps[2].data[index];        
1499                                                 dat8[i+5] = (image->comps[2].data[index]>> 8); 
1500                                                 index++;
1501                                         }
1502                                 }else{
1503                                         fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1504                                         fprintf(stderr,"Aborting\n");
1505                                         return 1;
1506                                 }
1507                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1508                         }
1509                         _TIFFfree(buf);
1510                         TIFFClose(tif);
1511                 }else if (image->numcomps == 1){
1512                         /* -->> -->> -->>    
1513                         Black and White     
1514                         <<-- <<-- <<-- */
1515
1516                         tif = TIFFOpen(outfile, "wb"); 
1517                         if (!tif) {
1518                                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1519                                 return 1;
1520                         }
1521
1522                         width   = image->comps[0].w;
1523                         height= image->comps[0].h;
1524                         bps             = image->comps[0].prec;
1525
1526                         /* Set tags */
1527                         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1528                         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1529                         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
1530                         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1531                         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1532                         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1533                         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1534                         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1535
1536                         /* Get a buffer for the data */
1537                         buf = _TIFFmalloc(TIFFStripSize(tif));
1538                         index = 0;
1539                         strip_size = 0;
1540                         strip_size = TIFFStripSize(tif);
1541                         for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1542                                 unsigned char *dat8;
1543                                 int i;
1544                                 dat8 = buf;
1545                                 if (image->comps[0].prec == 8){
1546                                         for (i=0; i<TIFFStripSize(tif); i+=1) { // 8 bits per pixel 
1547                                                 dat8[i+0] = image->comps[0].data[index] ;
1548                                                 index++;
1549                                         }
1550                                 }else if (image->comps[0].prec == 12){
1551                                         for (i = 0; i<TIFFStripSize(tif); i+=3) {       // 12 bits per pixel 
1552                                                 dat8[i+0] = (image->comps[0].data[index]>>8)<<4 | (image->comps[0].data[index]>>4);
1553                                                 dat8[i+1] = (image->comps[0].data[index]<<4)|((image->comps[0].data[index+1]>>8)& 0x0f);
1554                                                 dat8[i+2] = (image->comps[0].data[index+1]);
1555                                                 index+=2;
1556                                         }
1557                                 }else if (image->comps[0].prec == 16){
1558                                         for (i=0; i<TIFFStripSize(tif); i+=2) { // 16 bits per pixel 
1559                                                 dat8[i+0] =  image->comps[0].data[index];
1560                                                 dat8[i+1] = (image->comps[0].data[index]>> 8);
1561                                                 index++;
1562                                         }
1563                                 }else{
1564                                         fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",image->comps[0].prec);
1565                                         fprintf(stderr,"Aborting\n");
1566                                         return 1;
1567                                 }
1568                                 TIFFWriteEncodedStrip(tif, strip, buf, strip_size);
1569                         }
1570                         _TIFFfree(buf);
1571                         TIFFClose(tif);
1572                 }else{
1573                         fprintf(stderr,"False color format. Only RGB & Grayscale has been implemented\n");
1574                         fprintf(stderr,"Aborting\n");
1575                         return 1;
1576                 }
1577                 return 0;
1578 }
1579
1580 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1581 {
1582         int subsampling_dx = parameters->subsampling_dx;
1583         int subsampling_dy = parameters->subsampling_dy;
1584         TIFF *tif;
1585         tiff_infoheader_t Info;
1586         tdata_t buf;
1587         tstrip_t strip;
1588         tsize_t strip_size;
1589         int j, numcomps, w, h,index;
1590         OPJ_COLOR_SPACE color_space;
1591         opj_image_cmptparm_t cmptparm[3];
1592         opj_image_t * image = NULL;
1593
1594         tif = TIFFOpen(filename, "r");
1595
1596         if (!tif) {
1597                 fprintf(stderr, "Failed to open %s for reading\n", filename);
1598                 return 0;
1599         }
1600
1601         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
1602         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
1603         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
1604         TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
1605         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
1606         Info.tiPhoto = 0;
1607         TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
1608         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
1609         w= Info.tiWidth;
1610         h= Info.tiHeight;
1611         
1612         if (Info.tiPhoto == 2) { 
1613                 /* -->> -->> -->>    
1614                 RGB color           
1615                 <<-- <<-- <<-- */
1616
1617                 numcomps = 3;
1618                 color_space = CLRSPC_SRGB;
1619                 /* initialize image components*/ 
1620                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
1621                 for(j = 0; j < numcomps; j++) {
1622                         if (parameters->cp_cinema) {
1623                                 cmptparm[j].prec = 12;
1624                                 cmptparm[j].bpp = 12;
1625                         }else{
1626                                 cmptparm[j].prec = Info.tiBps;
1627                                 cmptparm[j].bpp = Info.tiBps;
1628                         }
1629                         cmptparm[j].sgnd = 0;
1630                         cmptparm[j].dx = subsampling_dx;
1631                         cmptparm[j].dy = subsampling_dy;
1632                         cmptparm[j].w = w;
1633                         cmptparm[j].h = h;
1634                 }
1635                 /* create the image*/ 
1636                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1637                 if(!image) {
1638                         TIFFClose(tif);
1639                         return NULL;
1640                 }
1641
1642                 /* set image offset and reference grid */
1643                 image->x0 = parameters->image_offset_x0;
1644                 image->y0 = parameters->image_offset_y0;
1645                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1646                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1647
1648                 buf = _TIFFmalloc(TIFFStripSize(tif));
1649                 strip_size=0;
1650                 strip_size=TIFFStripSize(tif);
1651                 index = 0;
1652                 /* Read the Image components*/
1653                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1654                         unsigned char *dat8;
1655                         int i, ssize;
1656                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1657                         dat8 = buf;
1658
1659                         if (Info.tiBps==12){
1660                                 for (i=0; i<ssize; i+=9) {      /*12 bits per pixel*/
1661                                         image->comps[0].data[index]   = ( dat8[i+0]<<4 )                |(dat8[i+1]>>4);
1662                                         image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
1663                                         image->comps[2].data[index]   = ( dat8[i+3]<<4)                 |(dat8[i+4]>>4);
1664                                         image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
1665                                         image->comps[1].data[index+1] = ( dat8[i+6] <<4)                |(dat8[i+7]>>4);
1666                                         image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
1667                                         index+=2;
1668                                 }
1669                         }
1670                         else if( Info.tiBps==16){
1671                                 for (i=0; i<ssize; i+=6) {      /* 16 bits per pixel */
1672                                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];   // R 
1673                                         image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];   // G 
1674                                         image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4];   // B 
1675                                         if(parameters->cp_cinema){/* Rounding to 12 bits*/
1676                                                 image->comps[0].data[index] = (image->comps[0].data[index] + 0x08) >> 4 ;
1677                                                 image->comps[1].data[index] = (image->comps[1].data[index] + 0x08) >> 4 ;
1678                                                 image->comps[2].data[index] = (image->comps[2].data[index] + 0x08) >> 4 ;
1679                                         }
1680                                         index++;
1681                                 }
1682                         }
1683                         else if ( Info.tiBps==8){
1684                                 for (i=0; i<ssize; i+=3) {      /* 8 bits per pixel */
1685                                         image->comps[0].data[index] = dat8[i+0];        // R 
1686                                         image->comps[1].data[index] = dat8[i+1];        // G 
1687                                         image->comps[2].data[index] = dat8[i+2];        // B 
1688                                         if(parameters->cp_cinema){/* Rounding to 12 bits*/
1689                                                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
1690                                                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
1691                                                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
1692                                         }
1693                                         index++;
1694                                 }
1695                         }
1696                         else{
1697                                 fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1698                                 fprintf(stderr,"Aborting\n");
1699                                 return NULL;
1700                         }
1701                 }
1702
1703                 _TIFFfree(buf);
1704                 TIFFClose(tif);
1705         }else if(Info.tiPhoto == 1) { 
1706                 /* -->> -->> -->>    
1707                 Black and White
1708                 <<-- <<-- <<-- */
1709
1710                 numcomps = 1;
1711                 color_space = CLRSPC_GRAY;
1712                 /* initialize image components*/ 
1713                 memset(&cmptparm[0], 0, sizeof(opj_image_cmptparm_t));
1714                 cmptparm[0].prec = Info.tiBps;
1715                 cmptparm[0].bpp = Info.tiBps;
1716                 cmptparm[0].sgnd = 0;
1717                 cmptparm[0].dx = subsampling_dx;
1718                 cmptparm[0].dy = subsampling_dy;
1719                 cmptparm[0].w = w;
1720                 cmptparm[0].h = h;
1721
1722                 /* create the image*/ 
1723                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
1724                 if(!image) {
1725                         TIFFClose(tif);
1726                         return NULL;
1727                 }
1728                 /* set image offset and reference grid */
1729                 image->x0 = parameters->image_offset_x0;
1730                 image->y0 = parameters->image_offset_y0;
1731                 image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
1732                 image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
1733
1734                 buf = _TIFFmalloc(TIFFStripSize(tif));
1735                 strip_size = 0;
1736                 strip_size = TIFFStripSize(tif);
1737                 index = 0;
1738                 /* Read the Image components*/
1739                 for (strip = 0; strip < TIFFNumberOfStrips(tif); strip++) {
1740                         unsigned char *dat8;
1741                         int i, ssize;
1742                         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
1743                         dat8 = buf;
1744
1745                         if (Info.tiBps==12){
1746                                 for (i=0; i<ssize; i+=3) {      /* 12 bits per pixel*/
1747                                         image->comps[0].data[index] = ( dat8[i+0]<<4 )                          |(dat8[i+1]>>4) ;
1748                                         image->comps[0].data[index] = ((dat8[i+1]& 0x0f)<< 8)   | dat8[i+2];
1749                                         index+=2;
1750                                 }
1751                         }
1752                         else if( Info.tiBps==16){
1753                                 for (i=0; i<ssize; i+=2) {      /* 16 bits per pixel */
1754                                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
1755                                         index++;
1756                                 }
1757                         }
1758                         else if ( Info.tiBps==8){
1759                                 for (i=0; i<ssize; i+=1) {      /* 8 bits per pixel */
1760                                         image->comps[0].data[index] = dat8[i+0];
1761                                         index++;
1762                                 }
1763                         }
1764                         else{
1765                                 fprintf(stderr,"Bits=%d, Only 8,12,16 bits implemented\n",Info.tiBps);
1766                                 fprintf(stderr,"Aborting\n");
1767                                 return NULL;
1768                         }
1769                 }
1770
1771                 _TIFFfree(buf);
1772                 TIFFClose(tif);
1773         }else{
1774                 fprintf(stderr,"False color format. Only RGB & Grayscale has been implemented\n");
1775                 fprintf(stderr,"Aborting\n");
1776                 return NULL;
1777         }
1778         return image;
1779 }
1780
1781 /* -->> -->> -->> -->>
1782
1783         RAW IMAGE FORMAT
1784
1785  <<-- <<-- <<-- <<-- */
1786
1787 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1788         int subsampling_dx = parameters->subsampling_dx;
1789         int subsampling_dy = parameters->subsampling_dy;
1790
1791         FILE *f = NULL;
1792         int i, compno, numcomps, w, h;
1793         OPJ_COLOR_SPACE color_space;
1794         opj_image_cmptparm_t *cmptparm; 
1795         opj_image_t * image = NULL;
1796         unsigned short ch;
1797         
1798         if((raw_cp->rawWidth * raw_cp->rawHeight * raw_cp->rawComp * raw_cp->rawBitDepth) == 0)
1799         {
1800                 fprintf(stderr,"\nError: invalid raw image parameters\n");
1801                 fprintf(stderr,"Please use the Format option -F:\n");
1802                 fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1803                 fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1804                 fprintf(stderr,"Aborting\n");
1805                 return NULL;
1806         }
1807
1808         f = fopen(filename, "rb");
1809         if (!f) {
1810                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1811                 fprintf(stderr,"Aborting\n");
1812                 return NULL;
1813         }
1814         numcomps = raw_cp->rawComp;
1815         color_space = CLRSPC_SRGB;
1816         w = raw_cp->rawWidth;
1817         h = raw_cp->rawHeight;
1818         cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
1819         
1820         /* initialize image components */       
1821         memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1822         for(i = 0; i < numcomps; i++) {         
1823                 cmptparm[i].prec = raw_cp->rawBitDepth;
1824                 cmptparm[i].bpp = raw_cp->rawBitDepth;
1825                 cmptparm[i].sgnd = raw_cp->rawSigned;
1826                 cmptparm[i].dx = subsampling_dx;
1827                 cmptparm[i].dy = subsampling_dy;
1828                 cmptparm[i].w = w;
1829                 cmptparm[i].h = h;
1830         }
1831         /* create the image */
1832         image = opj_image_create(numcomps, &cmptparm[0], color_space);
1833         if(!image) {
1834                 fclose(f);
1835                 return NULL;
1836         }
1837
1838         /* set image offset and reference grid */
1839         image->x0 = parameters->image_offset_x0;
1840         image->y0 = parameters->image_offset_y0;
1841         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1842         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1843
1844         if(raw_cp->rawBitDepth <= 8)
1845         {
1846                 unsigned char value = 0;
1847                 for(compno = 0; compno < numcomps; compno++) {
1848                         for (i = 0; i < w * h; i++) {
1849                                 if (!fread(&value, 1, 1, f)) {
1850                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1851                                         return NULL;
1852                                 }
1853                                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
1854                         }
1855                 }
1856         }
1857         else
1858         {
1859                 unsigned short value = 0;
1860                 for(compno = 0; compno < numcomps; compno++) {
1861                         for (i = 0; i < w * h; i++) {
1862                                 if (!fread(&value, 2, 1, f)) {
1863                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1864                                         return NULL;
1865                                 }
1866                                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
1867                         }
1868                 }
1869         }
1870
1871         if (fread(&ch, 1, 1, f)) {
1872                 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
1873         }
1874
1875         fclose(f);
1876
1877         return image;
1878 }
1879
1880 int imagetoraw(opj_image_t * image, const char *outfile)
1881 {
1882         FILE *rawFile = NULL;
1883         int compno, pixelsToWrite, offset, cont;
1884
1885         if((image->numcomps * image->x1 * image->y1) == 0)
1886         {
1887                 fprintf(stderr,"\nError: invalid raw image parameters\n");
1888                 return 1;
1889         }
1890
1891         rawFile = fopen(outfile, "wb");
1892         if (!rawFile) {
1893                 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
1894                 return 1;
1895         }
1896
1897         fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
1898
1899         for(compno = 0; compno < image->numcomps; compno++)
1900         {
1901                 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
1902                         image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
1903
1904                 pixelsToWrite = image->comps[compno].w * image->comps[compno].h;
1905                 offset = 0;
1906
1907                 if(image->comps[compno].prec <= 8)
1908                 {
1909                         if(image->comps[compno].sgnd == 1)
1910                         {
1911                                 signed char curr;
1912                                 int mask = (1 << image->comps[compno].prec) - 1;
1913                                 for(cont = 0; cont < pixelsToWrite; cont++)
1914                                 {                               
1915                                         curr = (signed char) (image->comps[compno].data[cont] & mask);
1916                                         fwrite(&curr, sizeof(signed char), 1, rawFile);
1917                                 }
1918                         }
1919                         else if(image->comps[compno].sgnd == 0)
1920                         {
1921                                 unsigned char curr;
1922                                 int mask = (1 << image->comps[compno].prec) - 1;
1923                                 for(cont = 0; cont < pixelsToWrite; cont++)
1924                                 {                               
1925                                         curr = (unsigned char) (image->comps[compno].data[cont] & mask);
1926                                         fwrite(&curr, sizeof(unsigned char), 1, rawFile);
1927                                 }
1928                         }
1929                 }
1930                 else if(image->comps[compno].prec <= 16)
1931                 {
1932                         if(image->comps[compno].sgnd == 1)
1933                         {
1934                                 signed short int curr;
1935                                 int mask = (1 << image->comps[compno].prec) - 1;
1936                                 for(cont = 0; cont < pixelsToWrite; cont++)
1937                                 {                               
1938                                         curr = (signed short int) (image->comps[compno].data[cont] & mask);
1939                                         fwrite(&curr, sizeof(signed short int), 1, rawFile);
1940                                 }
1941                         }
1942                         else if(image->comps[compno].sgnd == 0)
1943                         {
1944                                 unsigned short int curr;
1945                                 int mask = (1 << image->comps[compno].prec) - 1;
1946                                 for(cont = 0; cont < pixelsToWrite; cont++)
1947                                 {                               
1948                                         curr = (unsigned short int) (image->comps[compno].data[cont] & mask);
1949                                         fwrite(&curr, sizeof(unsigned short int), 1, rawFile);
1950                                 }
1951                         }
1952                 }
1953                 else if (image->comps[compno].prec <= 32)
1954                 {
1955
1956
1957                 }
1958                 else
1959                 {
1960                         fprintf(stderr,"\nError: invalid precision\n");
1961                         return 1;
1962                 }
1963         }
1964         fclose(rawFile);
1965         return 0;
1966 }