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