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