4189d83f8a7eb278d2b42c6bfd57e34772bbf24e
[openjpeg.git] / applications / 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 "opj_config.h"
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38
39 #ifdef HAVE_LIBTIFF
40 #include <tiffio.h>
41 #endif /* HAVE_LIBTIFF */
42
43 #ifdef HAVE_LIBPNG
44 #include <zlib.h>
45 #include <png.h>
46 #endif /* HAVE_LIBPNG */
47
48 #include "openjpeg.h"
49 #include "convert.h"
50
51 /*
52  * Get logarithm of an integer and round downwards.
53  *
54  * log2(a)
55  */
56 static int int_floorlog2(int a) {
57         int l;
58         for (l = 0; a > 1; l++) {
59                 a >>= 1;
60         }
61         return l;
62 }
63
64 /* -->> -->> -->> -->>
65
66   TGA IMAGE FORMAT
67
68  <<-- <<-- <<-- <<-- */
69
70 #ifdef INFORMATION_ONLY
71 /* TGA header definition. */
72 struct tga_header
73 {                           
74     unsigned char   id_length;              /* Image id field length    */
75     unsigned char   colour_map_type;        /* Colour map type          */
76     unsigned char   image_type;             /* Image type               */
77     /*
78     ** Colour map specification
79     */
80     unsigned short  colour_map_index;       /* First entry index        */
81     unsigned short  colour_map_length;      /* Colour map length        */
82     unsigned char   colour_map_entry_size;  /* Colour map entry size    */
83     /*
84     ** Image specification
85     */
86     unsigned short  x_origin;               /* x origin of image        */
87     unsigned short  y_origin;               /* u origin of image        */
88     unsigned short  image_width;            /* Image width              */
89     unsigned short  image_height;           /* Image height             */
90     unsigned char   pixel_depth;            /* Pixel depth              */
91     unsigned char   image_desc;             /* Image descriptor         */
92 };
93 #endif /* INFORMATION_ONLY */
94
95 static unsigned short get_ushort(unsigned short val) {
96
97 #ifdef ORDER_BIGENDIAN
98     return( ((val & 0xff) << 8) + (val >> 8) );
99 #else
100     return( val );
101 #endif
102
103 }
104
105 #define TGA_HEADER_SIZE 18
106
107 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
108         unsigned int *width, unsigned int *height, int *flip_image)
109 {
110         int palette_size;
111         unsigned char *tga ;
112         unsigned char id_len, cmap_type, image_type;
113         unsigned char pixel_depth, image_desc;
114         unsigned short cmap_index, cmap_len, cmap_entry_size;
115         unsigned short x_origin, y_origin, image_w, image_h;
116
117         if (!bits_per_pixel || !width || !height || !flip_image)
118                 return 0;
119         tga = (unsigned char*)malloc(18);
120
121         if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
122         {
123                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
124             return 0 ;
125         }
126         id_len = (unsigned char)tga[0];
127         cmap_type = (unsigned char)tga[1];
128         image_type = (unsigned char)tga[2];
129         cmap_index = get_ushort(*(unsigned short*)(&tga[3]));
130         cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
131         cmap_entry_size = (unsigned char)tga[7];
132
133
134         x_origin = get_ushort(*(unsigned short*)(&tga[8]));
135         y_origin = get_ushort(*(unsigned short*)(&tga[10]));
136         image_w = get_ushort(*(unsigned short*)(&tga[12]));
137         image_h = get_ushort(*(unsigned short*)(&tga[14]));
138         pixel_depth = (unsigned char)tga[16];
139         image_desc  = (unsigned char)tga[17];
140
141         free(tga);
142
143         *bits_per_pixel = (unsigned int)pixel_depth;
144         *width  = (unsigned int)image_w;
145         *height = (unsigned int)image_h;
146
147         /* Ignore tga identifier, if present ... */
148         if (id_len)
149         {
150                 unsigned char *id = (unsigned char *) malloc(id_len);
151                 if ( !fread(id, id_len, 1, fp) )
152                 {
153                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
154                         free(id);
155                     return 0 ;
156                 }
157                 free(id);  
158         }
159
160         /* Test for compressed formats ... not yet supported ...
161         // Note :-  9 - RLE encoded palettized.
162         //                 10 - RLE encoded RGB. */
163         if (image_type > 8)
164         {
165                 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
166                 return 0 ;
167         }
168
169         *flip_image = !(image_desc & 32);
170
171         /* Palettized formats are not yet supported, skip over the palette, if present ... */
172         palette_size = cmap_len * (cmap_entry_size/8);
173         
174         if (palette_size>0)
175         {
176                 fprintf(stderr, "File contains a palette - not yet supported.");
177                 fseek(fp, palette_size, SEEK_CUR);
178         }
179         return 1;
180 }
181
182 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
183         opj_bool flip_image)
184 {
185         unsigned short image_w, image_h, us0;
186         unsigned char uc0, image_type;
187         unsigned char pixel_depth, image_desc;
188
189         if (!bits_per_pixel || !width || !height)
190                 return 0;
191
192         pixel_depth = 0;
193
194         if ( bits_per_pixel < 256 )
195                 pixel_depth = (unsigned char)bits_per_pixel;
196         else{
197                 fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
198                 return 0;
199         }
200         uc0 = 0;
201
202         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
203         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
204
205         image_type = 2; /* Uncompressed. */
206         if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
207
208         us0 = 0;
209         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
210         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
211         if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
212
213         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
214         if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
215
216         image_w = (unsigned short)width;
217         image_h = (unsigned short) height;
218
219         if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
220         if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
221
222         if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
223
224         image_desc = 8; /* 8 bits per component. */
225
226         if (flip_image)
227                 image_desc |= 32;
228         if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
229
230         return 1;
231
232 fails:
233         fputs("\nwrite_tgaheader: write ERROR\n", stderr);
234         return 0;
235 }
236
237 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
238         FILE *f;
239         opj_image_t *image;
240         unsigned int image_width, image_height, pixel_bit_depth;
241         unsigned int x, y;
242         int flip_image=0;
243         opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
244         int numcomps;
245         OPJ_COLOR_SPACE color_space;
246         opj_bool mono ;
247         opj_bool save_alpha;
248         int subsampling_dx, subsampling_dy;
249         int i;  
250
251         f = fopen(filename, "rb");
252         if (!f) {
253                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
254                 return 0;
255         }
256
257         if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
258                 return NULL;
259
260         /* We currently only support 24 & 32 bit tga's ... */
261         if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
262                 return NULL;
263
264         /* initialize image components */   
265         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
266
267         mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
268         save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
269
270         if (mono) {
271                 color_space = CLRSPC_GRAY;
272                 numcomps = save_alpha ? 2 : 1;
273         }       
274         else {
275                 numcomps = save_alpha ? 4 : 3;
276                 color_space = CLRSPC_SRGB;
277         }
278
279         subsampling_dx = parameters->subsampling_dx;
280         subsampling_dy = parameters->subsampling_dy;
281
282         for (i = 0; i < numcomps; i++) {
283                 cmptparm[i].prec = 8;
284                 cmptparm[i].bpp = 8;
285                 cmptparm[i].sgnd = 0;
286                 cmptparm[i].dx = subsampling_dx;
287                 cmptparm[i].dy = subsampling_dy;
288                 cmptparm[i].w = image_width;
289                 cmptparm[i].h = image_height;
290         }
291
292         /* create the image */
293         image = opj_image_create(numcomps, &cmptparm[0], color_space);
294
295         if (!image)
296                 return NULL;
297
298         /* set image offset and reference grid */
299         image->x0 = parameters->image_offset_x0;
300         image->y0 = parameters->image_offset_y0;
301         image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
302         image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
303
304         /* set image data */
305         for (y=0; y < image_height; y++) 
306         {
307                 int index;
308
309                 if (flip_image)
310                         index = (image_height-y-1)*image_width;
311                 else
312                         index = y*image_width;
313
314                 if (numcomps==3)
315                 {
316                         for (x=0;x<image_width;x++) 
317                         {
318                                 unsigned char r,g,b;
319
320                                 if( !fread(&b, 1, 1, f) )
321                                 {
322                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
323                                         opj_image_destroy(image);
324                                     return NULL;
325                                 }
326                                 if ( !fread(&g, 1, 1, f) )
327                                 {
328                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
329                                         opj_image_destroy(image);
330                                     return NULL;
331                                 }
332                                 if ( !fread(&r, 1, 1, f) )
333                                 {
334                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
335                                         opj_image_destroy(image);
336                                     return NULL;
337                                 }
338
339                                 image->comps[0].data[index]=r;
340                                 image->comps[1].data[index]=g;
341                                 image->comps[2].data[index]=b;
342                                 index++;
343                         }
344                 }
345                 else if (numcomps==4)
346                 {
347                         for (x=0;x<image_width;x++) 
348                         {
349                                 unsigned char r,g,b,a;
350                                 if ( !fread(&b, 1, 1, f) )
351                                 {
352                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
353                                         opj_image_destroy(image);
354                                     return NULL;
355                                 }
356                                 if ( !fread(&g, 1, 1, f) )
357                                 {
358                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
359                                         opj_image_destroy(image);
360                                     return NULL;
361                                 }
362                                 if ( !fread(&r, 1, 1, f) )
363                                 {
364                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
365                                         opj_image_destroy(image);
366                                     return NULL;
367                                 }
368                                 if ( !fread(&a, 1, 1, f) )
369                                 {
370                                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
371                                         opj_image_destroy(image);
372                                     return NULL;
373                                 }
374
375                                 image->comps[0].data[index]=r;
376                                 image->comps[1].data[index]=g;
377                                 image->comps[2].data[index]=b;
378                                 image->comps[3].data[index]=a;
379                                 index++;
380                         }
381                 }
382                 else {
383                         fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
384                 }
385         }       
386         return image;
387 }
388
389 int imagetotga(opj_image_t * image, const char *outfile) {
390         int width, height, bpp, x, y;
391         opj_bool write_alpha;
392         int i, adjustR, adjustG, adjustB;
393         unsigned int alpha_channel;
394         float r,g,b,a;
395         unsigned char value;
396         float scale;
397         FILE *fdest;
398   size_t res;
399
400         fdest = fopen(outfile, "wb");
401         if (!fdest) {
402                 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
403                 return 1;
404         }
405
406         for (i = 0; i < image->numcomps-1; i++) {
407                 if ((image->comps[0].dx != image->comps[i+1].dx) 
408                         ||(image->comps[0].dy != image->comps[i+1].dy) 
409                         ||(image->comps[0].prec != image->comps[i+1].prec))     {
410       fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
411       return 1;
412    }
413         }
414
415         width = image->comps[0].w;
416         height = image->comps[0].h; 
417
418         /* Mono with alpha, or RGB with alpha. */
419         write_alpha = (image->numcomps==2) || (image->numcomps==4);   
420
421         /* Write TGA header  */
422         bpp = write_alpha ? 32 : 24;
423         if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
424                 return 1;
425
426         alpha_channel = image->numcomps-1; 
427
428         scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
429
430         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
431         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
432         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
433
434         for (y=0; y < height; y++) {
435                 unsigned int index=y*width;
436
437                 for (x=0; x < width; x++, index++)      {
438                         r = (float)(image->comps[0].data[index] + adjustR);
439
440                         if (image->numcomps>2) {
441                                 g = (float)(image->comps[1].data[index] + adjustG);
442                                 b = (float)(image->comps[2].data[index] + adjustB);
443                         }
444                         else  {/* Greyscale ... */
445                                 g = r;
446                                 b = r;
447                         }
448
449                         /* TGA format writes BGR ... */
450                         value = (unsigned char)(b*scale);
451                         res = fwrite(&value,1,1,fdest);
452       if( res < 1 ) {
453         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
454         return 1;
455       }
456
457                         value = (unsigned char)(g*scale);
458                         res = fwrite(&value,1,1,fdest);
459       if( res < 1 ) {
460         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
461         return 1;
462       }
463
464                         value = (unsigned char)(r*scale);
465                         res = fwrite(&value,1,1,fdest);
466       if( res < 1 ) {
467         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
468         return 1;
469       }
470
471                         if (write_alpha) {
472                                 a = (float)(image->comps[alpha_channel].data[index]);
473                                 value = (unsigned char)(a*scale);
474                                 res = fwrite(&value,1,1,fdest);
475         if( res < 1 ) {
476           fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
477           return 1;
478         }
479                         }
480                 }
481         }
482
483         return 0;
484 }
485
486 /* -->> -->> -->> -->>
487
488   BMP IMAGE FORMAT
489
490  <<-- <<-- <<-- <<-- */
491
492 /* WORD defines a two byte word */
493 typedef unsigned short int WORD;
494
495 /* DWORD defines a four byte word */
496 typedef unsigned long int DWORD;
497
498 typedef struct {
499   WORD bfType;                  /* 'BM' for Bitmap (19776) */
500   DWORD bfSize;                 /* Size of the file        */
501   WORD bfReserved1;             /* Reserved : 0            */
502   WORD bfReserved2;             /* Reserved : 0            */
503   DWORD bfOffBits;              /* Offset                  */
504 } BITMAPFILEHEADER_t;
505
506 typedef struct {
507   DWORD biSize;                 /* Size of the structure in bytes */
508   DWORD biWidth;                /* Width of the image in pixels */
509   DWORD biHeight;               /* Heigth of the image in pixels */
510   WORD biPlanes;                /* 1 */
511   WORD biBitCount;              /* Number of color bits by pixels */
512   DWORD biCompression;          /* Type of encoding 0: none 1: RLE8 2: RLE4 */
513   DWORD biSizeImage;            /* Size of the image in bytes */
514   DWORD biXpelsPerMeter;        /* Horizontal (X) resolution in pixels/meter */
515   DWORD biYpelsPerMeter;        /* Vertical (Y) resolution in pixels/meter */
516   DWORD biClrUsed;              /* Number of color used in the image (0: ALL) */
517   DWORD biClrImportant;         /* Number of important color (0: ALL) */
518 } BITMAPINFOHEADER_t;
519
520 opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) 
521 {
522         int subsampling_dx = parameters->subsampling_dx;
523         int subsampling_dy = parameters->subsampling_dy;
524
525         int i, numcomps, w, h;
526         OPJ_COLOR_SPACE color_space;
527         opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
528         opj_image_t * image = NULL;
529
530         FILE *IN;
531         BITMAPFILEHEADER_t File_h;
532         BITMAPINFOHEADER_t Info_h;
533         unsigned char *RGB;
534         unsigned char *table_R, *table_G, *table_B;
535         unsigned int j, PAD = 0;
536
537         int x, y, index;
538         int gray_scale = 1;
539         int has_color;
540         DWORD W, H;
541   
542         IN = fopen(filename, "rb");
543         if (!IN) 
544    {
545         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
546         return NULL;
547    }
548         
549         File_h.bfType = getc(IN);
550         File_h.bfType = (getc(IN) << 8) + File_h.bfType;
551         
552         if (File_h.bfType != 19778) 
553    {
554         fprintf(stderr,"Error, not a BMP file!\n");
555         fclose(IN);
556         return NULL;
557    }
558                 /* FILE HEADER */
559                 /* ------------- */
560         File_h.bfSize = getc(IN);
561         File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
562         File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
563         File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
564
565         File_h.bfReserved1 = getc(IN);
566         File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
567
568         File_h.bfReserved2 = getc(IN);
569         File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
570
571         File_h.bfOffBits = getc(IN);
572         File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
573         File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
574         File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
575
576                 /* INFO HEADER */
577                 /* ------------- */
578
579         Info_h.biSize = getc(IN);
580         Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
581         Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
582         Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
583
584         if(Info_h.biSize != 40)
585    {
586         fprintf(stderr,"Error, unknown BMP header size %ld\n", Info_h.biSize);
587         fclose(IN);
588         return NULL;
589    }
590         Info_h.biWidth = getc(IN);
591         Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
592         Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
593         Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
594         w = Info_h.biWidth;
595
596         Info_h.biHeight = getc(IN);
597         Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
598         Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
599         Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
600         h = Info_h.biHeight;
601
602         Info_h.biPlanes = getc(IN);
603         Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
604
605         Info_h.biBitCount = getc(IN);
606         Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
607
608         Info_h.biCompression = getc(IN);
609         Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
610         Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
611         Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
612
613         Info_h.biSizeImage = getc(IN);
614         Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
615         Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
616         Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
617
618         Info_h.biXpelsPerMeter = getc(IN);
619         Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
620         Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
621         Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
622
623         Info_h.biYpelsPerMeter = getc(IN);
624         Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
625         Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
626         Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
627
628         Info_h.biClrUsed = getc(IN);
629         Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
630         Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
631         Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
632
633         Info_h.biClrImportant = getc(IN);
634         Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
635         Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
636         Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
637
638                 /* Read the data and store them in the OUT file */
639
640         if (Info_h.biBitCount == 24) 
641    {
642         numcomps = 3;
643         color_space = CLRSPC_SRGB;
644         /* initialize image components */
645         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
646         for(i = 0; i < numcomps; i++) 
647   {
648         cmptparm[i].prec = 8;
649         cmptparm[i].bpp = 8;
650         cmptparm[i].sgnd = 0;
651         cmptparm[i].dx = subsampling_dx;
652         cmptparm[i].dy = subsampling_dy;
653         cmptparm[i].w = w;
654         cmptparm[i].h = h;
655   }
656         /* create the image */
657         image = opj_image_create(numcomps, &cmptparm[0], color_space);
658         if(!image) 
659   {
660         fclose(IN);
661         return NULL;
662   }
663
664         /* set image offset and reference grid */
665         image->x0 = parameters->image_offset_x0;
666         image->y0 = parameters->image_offset_y0;
667         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
668         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
669
670         /* set image data */
671
672         /* Place the cursor at the beginning of the image information */
673         fseek(IN, 0, SEEK_SET);
674         fseek(IN, File_h.bfOffBits, SEEK_SET);
675                         
676         W = Info_h.biWidth;
677         H = Info_h.biHeight;
678
679         /* PAD = 4 - (3 * W) % 4; */
680         /* PAD = (PAD == 4) ? 0 : PAD; */
681         PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
682                         
683         RGB = (unsigned char *) 
684          malloc((3 * W + PAD) * H * sizeof(unsigned char));
685                         
686         if ( fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN) != (3 * W + PAD) * H )
687         {
688                 free(RGB);
689                 opj_image_destroy(image);
690                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
691             return NULL;
692         }
693                         
694         index = 0;
695
696         for(y = 0; y < (int)H; y++) 
697   {
698         unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
699         for(x = 0; x < (int)W; x++) 
700  {
701         unsigned char *pixel = &scanline[3 * x];
702         image->comps[0].data[index] = pixel[2]; /* R */
703         image->comps[1].data[index] = pixel[1]; /* G */
704         image->comps[2].data[index] = pixel[0]; /* B */
705         index++;
706  }
707   }
708         free(RGB);
709    }/* if (Info_h.biBitCount == 24) */ 
710         else 
711         if (Info_h.biBitCount == 8 && Info_h.biCompression == 0)/*RGB */
712    {
713         if(Info_h.biClrUsed == 0) Info_h.biClrUsed = 256;
714         else
715         if(Info_h.biClrUsed > 256) Info_h.biClrUsed = 256;
716
717         table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
718         table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
719         table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
720                 
721         has_color = 0;  
722         for (j = 0; j < Info_h.biClrUsed; j++) 
723   {
724         table_B[j] = (unsigned char)getc(IN);
725         table_G[j] = (unsigned char)getc(IN);
726         table_R[j] = (unsigned char)getc(IN);
727         getc(IN);
728         has_color += 
729          !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
730   }
731         if(has_color) gray_scale = 0;
732                    
733         /* Place the cursor at the beginning of the image information */
734         fseek(IN, 0, SEEK_SET);
735         fseek(IN, File_h.bfOffBits, SEEK_SET);
736                         
737         W = Info_h.biWidth;
738         H = Info_h.biHeight;
739         if (Info_h.biWidth % 2)
740          W++;
741                         
742         numcomps = gray_scale ? 1 : 3;
743         color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
744                 /* initialize image components */
745         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
746         for(i = 0; i < numcomps; i++) 
747   {
748         cmptparm[i].prec = 8;
749         cmptparm[i].bpp = 8;
750         cmptparm[i].sgnd = 0;
751         cmptparm[i].dx = subsampling_dx;
752         cmptparm[i].dy = subsampling_dy;
753         cmptparm[i].w = w;
754         cmptparm[i].h = h;
755   }
756         /* create the image */
757         image = opj_image_create(numcomps, &cmptparm[0], color_space);
758         if(!image) 
759   {
760         fclose(IN);
761         free(table_R); free(table_G); free(table_B);
762         return NULL;
763   }
764
765         /* set image offset and reference grid */
766         image->x0 = parameters->image_offset_x0;
767         image->y0 = parameters->image_offset_y0;
768         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
769         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
770
771         /* set image data */
772
773         RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
774                         
775         if ( fread(RGB, sizeof(unsigned char), W * H, IN) != W * H )
776         {
777                 free(table_R);
778                 free(table_G);
779                 free(table_B);
780                 free(RGB);
781                 opj_image_destroy(image);
782                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
783             return NULL;
784         }
785         if (gray_scale) 
786   {
787         index = 0;
788         for (j = 0; j < W * H; j++) 
789  {
790                 if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) 
791            {
792                 image->comps[0].data[index] = 
793                  table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
794                 index++;
795            }
796  }
797
798   } 
799         else 
800   {
801         index = 0;
802         for (j = 0; j < W * H; j++) 
803  {
804                 if ((j % W < W - 1 && Info_h.biWidth % 2) 
805                 || !(Info_h.biWidth % 2)) 
806            {
807                 unsigned char pixel_index = 
808                  RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
809                 image->comps[0].data[index] = table_R[pixel_index];
810                 image->comps[1].data[index] = table_G[pixel_index];
811                 image->comps[2].data[index] = table_B[pixel_index];
812                 index++;
813            }
814  }
815   }
816         free(RGB);
817         free(table_R);
818         free(table_G);
819         free(table_B);
820    }/* RGB8 */ 
821         else 
822         if (Info_h.biBitCount == 8 && Info_h.biCompression == 1)/*RLE8*/
823         {
824                 unsigned char *pix, *beyond;
825                 int *gray, *red, *green, *blue;
826                 unsigned int x, y, max;
827                 int i, c, c1;
828                 unsigned char uc;
829
830                 if (Info_h.biClrUsed == 0)
831                         Info_h.biClrUsed = 256;
832                 else if (Info_h.biClrUsed > 256)
833                         Info_h.biClrUsed = 256;
834
835                 table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
836                 table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
837                 table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
838
839                 has_color = 0;
840                 for (j = 0; j < Info_h.biClrUsed; j++)
841                 {
842                         table_B[j] = (unsigned char)getc(IN);
843                         table_G[j] = (unsigned char)getc(IN);
844                         table_R[j] = (unsigned char)getc(IN);
845                         getc(IN);
846                         has_color += !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
847                 }
848
849                 if (has_color)
850                         gray_scale = 0;
851
852                 numcomps = gray_scale ? 1 : 3;
853                 color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
854                 /* initialize image components */
855                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
856                 for (i = 0; i < numcomps; i++)
857                 {
858                         cmptparm[i].prec = 8;
859                         cmptparm[i].bpp = 8;
860                         cmptparm[i].sgnd = 0;
861                         cmptparm[i].dx = subsampling_dx;
862                         cmptparm[i].dy = subsampling_dy;
863                         cmptparm[i].w = w;
864                         cmptparm[i].h = h;
865                 }
866                 /* create the image */
867                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
868                 if (!image)
869                 {
870                         fclose(IN);
871                         free(table_R);
872                         free(table_G);
873                         free(table_B);
874                         return NULL;
875                 }
876
877                 /* set image offset and reference grid */
878                 image->x0 = parameters->image_offset_x0;
879                 image->y0 = parameters->image_offset_y0;
880                 image->x1 = !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w
881                                 - 1) * subsampling_dx + 1;
882                 image->y1 = !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h
883                                 - 1) * subsampling_dy + 1;
884
885                 /* set image data */
886
887                 /* Place the cursor at the beginning of the image information */
888                 fseek(IN, 0, SEEK_SET);
889                 fseek(IN, File_h.bfOffBits, SEEK_SET);
890
891                 W = Info_h.biWidth;
892                 H = Info_h.biHeight;
893                 RGB = (unsigned char *) calloc(1, W * H * sizeof(unsigned char));
894                 beyond = RGB + W * H;
895                 pix = beyond - W;
896                 x = y = 0;
897
898                 while (y < H)
899                 {
900                         c = getc(IN);
901
902                         if (c)
903                         {
904                                 c1 = getc(IN);
905
906                                 for (i = 0; i < c && x < W && pix < beyond; i++, x++, pix++)
907                                         *pix = (unsigned char)c1;
908                         }
909                         else
910                         {
911                                 c = getc(IN);
912
913                                 if (c == 0x00) /* EOL */
914                                 {
915                                         x = 0;
916                                         ++y;
917                                         pix = RGB + x + (H - y - 1) * W;
918                                 }
919                                 else if (c == 0x01) /* EOP */
920                                         break;
921                                 else if (c == 0x02) /* MOVE by dxdy */
922                                 {
923                                         c = getc(IN);
924                                         x += c;
925                                         c = getc(IN);
926                                         y += c;
927                                         pix = RGB + (H - y - 1) * W + x;
928                                 }
929                                 else /* 03 .. 255 */
930                                 {
931                                         i = 0;
932                                         for (; i < c && x < W && pix < beyond; i++, x++, pix++)
933                                         {
934                                                 c1 = getc(IN);
935                                                 *pix = (unsigned char)c1;
936                                         }
937                                         if (c & 1) /* skip padding byte */
938                                                 getc(IN);
939                                 }
940                         }
941                 }/* while() */
942
943                 if (gray_scale)
944                 {
945                         gray = image->comps[0].data;
946                         pix = RGB;
947                         max = W * H;
948
949                         while (max--)
950                         {
951                                 uc = *pix++;
952
953                                 *gray++ = table_R[uc];
954                         }
955                 }
956                 else
957                 {
958                         /*int *red, *green, *blue;*/
959
960                         red = image->comps[0].data;
961                         green = image->comps[1].data;
962                         blue = image->comps[2].data;
963                         pix = RGB;
964                         max = W * H;
965
966                         while (max--)
967                         {
968                                 uc = *pix++;
969
970                                 *red++ = table_R[uc];
971                                 *green++ = table_G[uc];
972                                 *blue++ = table_B[uc];
973                         }
974                 }
975                 free(RGB);
976                 free(table_R);
977                 free(table_G);
978                 free(table_B);
979         }/* RLE8 */
980         else 
981    {
982         fprintf(stderr, 
983         "Other system than 24 bits/pixels or 8 bits (no RLE coding) "
984                 "is not yet implemented [%d]\n", Info_h.biBitCount);
985    }
986         fclose(IN);
987         return image;
988 }
989
990 int imagetobmp(opj_image_t * image, const char *outfile) {
991         int w, h;
992         int i, pad;
993         FILE *fdest = NULL;
994         int adjustR, adjustG, adjustB;
995
996   if (image->comps[0].prec < 8) {
997     fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec);
998     return 1;
999   }
1000         if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
1001                 && image->comps[1].dx == image->comps[2].dx
1002                 && image->comps[0].dy == image->comps[1].dy
1003                 && image->comps[1].dy == image->comps[2].dy
1004                 && image->comps[0].prec == image->comps[1].prec
1005                 && image->comps[1].prec == image->comps[2].prec) {
1006                 
1007                 /* -->> -->> -->> -->>    
1008                 24 bits color       
1009                 <<-- <<-- <<-- <<-- */
1010             
1011                 fdest = fopen(outfile, "wb");
1012                 if (!fdest) {
1013                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1014                         return 1;
1015                 }
1016             
1017                 w = image->comps[0].w;      
1018                 h = image->comps[0].h;
1019             
1020                 fprintf(fdest, "BM");
1021             
1022                 /* FILE HEADER */
1023                 /* ------------- */
1024                 fprintf(fdest, "%c%c%c%c",
1025                         (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
1026                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
1027                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
1028                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
1029                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1030                 fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
1031             
1032                 /* INFO HEADER   */
1033                 /* ------------- */
1034                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1035                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1036                         (unsigned char) ((w) >> 8) & 0xff,
1037                         (unsigned char) ((w) >> 16) & 0xff,
1038                         (unsigned char) ((w) >> 24) & 0xff);
1039                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1040                         (unsigned char) ((h) >> 8) & 0xff,
1041                         (unsigned char) ((h) >> 16) & 0xff,
1042                         (unsigned char) ((h) >> 24) & 0xff);
1043                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1044                 fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
1045                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1046                 fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
1047                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
1048                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
1049                         (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
1050                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1051                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1052                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1053                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1054             
1055                 if (image->comps[0].prec > 8) {
1056                         adjustR = image->comps[0].prec - 8;
1057                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1058                 }
1059                 else 
1060                         adjustR = 0;
1061                 if (image->comps[1].prec > 8) {
1062                         adjustG = image->comps[1].prec - 8;
1063                         printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1064                 }
1065                 else 
1066                         adjustG = 0;
1067                 if (image->comps[2].prec > 8) {
1068                         adjustB = image->comps[2].prec - 8;
1069                         printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1070                 }
1071                 else 
1072                         adjustB = 0;
1073
1074                 for (i = 0; i < w * h; i++) {
1075                         unsigned char rc, gc, bc;
1076                         int r, g, b;
1077                                                         
1078                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1079                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1080                         r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1081                         if(r > 255) r = 255; else if(r < 0) r = 0;
1082                         rc = (unsigned char)r;
1083
1084                         g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1085                         g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1086                         g = ((g >> adjustG)+((g >> (adjustG-1))%2));
1087                         if(g > 255) g = 255; else if(g < 0) g = 0;
1088                         gc = (unsigned char)g;
1089
1090                         b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1091                         b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1092                         b = ((b >> adjustB)+((b >> (adjustB-1))%2));
1093                         if(b > 255) b = 255; else if(b < 0) b = 0;
1094                         bc = (unsigned char)b;
1095
1096                         fprintf(fdest, "%c%c%c", bc, gc, rc);
1097                         
1098                         if ((i + 1) % w == 0) {
1099                                 for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
1100                                         fprintf(fdest, "%c", 0);
1101                         }
1102                 }
1103                 fclose(fdest);
1104         } else {                        /* Gray-scale */
1105
1106                 /* -->> -->> -->> -->>
1107                 8 bits non code (Gray scale)
1108                 <<-- <<-- <<-- <<-- */
1109
1110                 fdest = fopen(outfile, "wb");
1111                 w = image->comps[0].w;      
1112                 h = image->comps[0].h;
1113             
1114                 fprintf(fdest, "BM");
1115             
1116                 /* FILE HEADER */
1117                 /* ------------- */
1118                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
1119                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
1120                         (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
1121                         (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
1122                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1123                 fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
1124                         ((54 + 1024) >> 16) & 0xff,
1125                         ((54 + 1024) >> 24) & 0xff);
1126             
1127                 /* INFO HEADER */
1128                 /* ------------- */
1129                 fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1130                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1131                         (unsigned char) ((w) >> 8) & 0xff,
1132                         (unsigned char) ((w) >> 16) & 0xff,
1133                         (unsigned char) ((w) >> 24) & 0xff);
1134                 fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1135                         (unsigned char) ((h) >> 8) & 0xff,
1136                         (unsigned char) ((h) >> 16) & 0xff,
1137                         (unsigned char) ((h) >> 24) & 0xff);
1138                 fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1139                 fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
1140                 fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1141                 fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
1142                         (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
1143                         (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
1144                         (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
1145                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1146                 fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1147                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1148                 fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1149
1150                 if (image->comps[0].prec > 8) {
1151                         adjustR = image->comps[0].prec - 8;
1152                         printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1153                 }else 
1154                         adjustR = 0;
1155
1156                 for (i = 0; i < 256; i++) {
1157                         fprintf(fdest, "%c%c%c%c", i, i, i, 0);
1158                 }
1159
1160                 for (i = 0; i < w * h; i++) {
1161                         int r;
1162                         
1163                         r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1164                         r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1165                         r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1166                         if(r > 255) r = 255; else if(r < 0) r = 0;
1167
1168                         fprintf(fdest, "%c", (unsigned char)r);
1169
1170                         if ((i + 1) % w == 0) {
1171                                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
1172                                         fprintf(fdest, "%c", 0);
1173                         }
1174                 }
1175                 fclose(fdest);
1176         }
1177
1178         return 0;
1179 }
1180
1181 /* -->> -->> -->> -->>
1182
1183 PGX IMAGE FORMAT
1184
1185 <<-- <<-- <<-- <<-- */
1186
1187
1188 static unsigned char readuchar(FILE * f)
1189 {
1190   unsigned char c1;
1191   if ( !fread(&c1, 1, 1, f) )
1192   {
1193           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1194           return 0;
1195   }
1196   return c1;
1197 }
1198
1199 static unsigned short readushort(FILE * f, int bigendian)
1200 {
1201   unsigned char c1, c2;
1202   if ( !fread(&c1, 1, 1, f) )
1203   {
1204           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1205           return 0;
1206   }
1207   if ( !fread(&c2, 1, 1, f) )
1208   {
1209           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1210           return 0;
1211   }
1212   if (bigendian)
1213     return (c1 << 8) + c2;
1214   else
1215     return (c2 << 8) + c1;
1216 }
1217
1218 static unsigned int readuint(FILE * f, int bigendian)
1219 {
1220   unsigned char c1, c2, c3, c4;
1221   if ( !fread(&c1, 1, 1, f) )
1222   {
1223           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1224           return 0;
1225   }
1226   if ( !fread(&c2, 1, 1, f) )
1227   {
1228           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1229           return 0;
1230   }
1231   if ( !fread(&c3, 1, 1, f) )
1232   {
1233           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1234           return 0;
1235   }
1236   if ( !fread(&c4, 1, 1, f) )
1237   {
1238           fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1239           return 0;
1240   }
1241   if (bigendian)
1242     return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
1243   else
1244     return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
1245 }
1246
1247 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
1248         FILE *f = NULL;
1249         int w, h, prec;
1250         int i, numcomps, max;
1251         OPJ_COLOR_SPACE color_space;
1252         opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
1253         opj_image_t * image = NULL;
1254
1255         char endian1,endian2,sign;
1256         char signtmp[32];
1257
1258         char temp[32];
1259         int bigendian;
1260         opj_image_comp_t *comp = NULL;
1261
1262         numcomps = 1;
1263         color_space = CLRSPC_GRAY;
1264
1265         memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1266
1267         max = 0;
1268
1269         f = fopen(filename, "rb");
1270         if (!f) {
1271           fprintf(stderr, "Failed to open %s for reading !\n", filename);
1272           return NULL;
1273         }
1274
1275         fseek(f, 0, SEEK_SET);
1276         if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
1277                 fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1278                 return NULL;
1279         }
1280
1281         i=0;
1282         sign='+';               
1283         while (signtmp[i]!='\0') {
1284                 if (signtmp[i]=='-') sign='-';
1285                 i++;
1286         }
1287         
1288         fgetc(f);
1289         if (endian1=='M' && endian2=='L') {
1290                 bigendian = 1;
1291         } else if (endian2=='M' && endian1=='L') {
1292                 bigendian = 0;
1293         } else {
1294                 fprintf(stderr, "Bad pgx header, please check input file\n");
1295                 return NULL;
1296         }
1297
1298         /* initialize image component */
1299
1300         cmptparm.x0 = parameters->image_offset_x0;
1301         cmptparm.y0 = parameters->image_offset_y0;
1302         cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1303         cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1304         
1305         if (sign == '-') {
1306                 cmptparm.sgnd = 1;
1307         } else {
1308                 cmptparm.sgnd = 0;
1309         }
1310         cmptparm.prec = prec;
1311         cmptparm.bpp = prec;
1312         cmptparm.dx = parameters->subsampling_dx;
1313         cmptparm.dy = parameters->subsampling_dy;
1314         
1315         /* create the image */
1316         image = opj_image_create(numcomps, &cmptparm, color_space);
1317         if(!image) {
1318                 fclose(f);
1319                 return NULL;
1320         }
1321         /* set image offset and reference grid */
1322         image->x0 = cmptparm.x0;
1323         image->y0 = cmptparm.x0;
1324         image->x1 = cmptparm.w;
1325         image->y1 = cmptparm.h;
1326
1327         /* set image data */
1328
1329         comp = &image->comps[0];
1330
1331         for (i = 0; i < w * h; i++) {
1332                 int v;
1333                 if (comp->prec <= 8) {
1334                         if (!comp->sgnd) {
1335                                 v = readuchar(f);
1336                         } else {
1337                                 v = (char) readuchar(f);
1338                         }
1339                 } else if (comp->prec <= 16) {
1340                         if (!comp->sgnd) {
1341                                 v = readushort(f, bigendian);
1342                         } else {
1343                                 v = (short) readushort(f, bigendian);
1344                         }
1345                 } else {
1346                         if (!comp->sgnd) {
1347                                 v = readuint(f, bigendian);
1348                         } else {
1349                                 v = (int) readuint(f, bigendian);
1350                         }
1351                 }
1352                 if (v > max)
1353                         max = v;
1354                 comp->data[i] = v;
1355         }
1356         fclose(f);
1357         comp->bpp = int_floorlog2(max) + 1;
1358
1359         return image;
1360 }
1361
1362 int imagetopgx(opj_image_t * image, const char *outfile) {
1363         int w, h;
1364         int i, j, compno;
1365         FILE *fdest = NULL;
1366
1367         for (compno = 0; compno < image->numcomps; compno++) {
1368                 opj_image_comp_t *comp = &image->comps[compno];
1369                 char bname[256]; /* buffer for name */
1370     char *name = bname; /* pointer */
1371     int nbytes = 0;
1372     size_t res;
1373     const size_t olen = strlen(outfile);
1374     const size_t dotpos = olen - 4;
1375     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1376     if( outfile[dotpos] != '.' ) {
1377       /* `pgx` was recognized but there is no dot at expected position */
1378       fprintf(stderr, "ERROR -> Impossible happen." );
1379       return 1;
1380       }
1381     if( total > 256 ) {
1382       name = (char*)malloc(total+1);
1383       }
1384     strncpy(name, outfile, dotpos);
1385                 /*if (image->numcomps > 1) {*/
1386                         sprintf(name+dotpos, "_%d.pgx", compno);
1387                 /*} else {
1388                         strcpy(name+dotpos, ".pgx");
1389                 }*/
1390                 fdest = fopen(name, "wb");
1391                 if (!fdest) {
1392                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1393                         return 1;
1394                 }
1395     /* dont need name anymore */
1396     if( total > 256 ) {
1397       free(name);
1398       }
1399
1400                 w = image->comps[compno].w;
1401                 h = image->comps[compno].h;
1402             
1403                 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
1404                 if (comp->prec <= 8) {
1405                         nbytes = 1;
1406                 } else if (comp->prec <= 16) {
1407                         nbytes = 2;
1408                 } else {
1409                         nbytes = 4;
1410                 }
1411                 for (i = 0; i < w * h; i++) {
1412                         int v = image->comps[compno].data[i];
1413                         for (j = nbytes - 1; j >= 0; j--) {
1414                                 char byte = (char) (v >> (j * 8));
1415                                 res = fwrite(&byte, 1, 1, fdest);
1416         if( res < 1 ) {
1417           fprintf(stderr, "failed to write 1 byte for %s\n", name);
1418           return 1;
1419         }
1420                         }
1421                 }
1422                 fclose(fdest);
1423         }
1424
1425         return 0;
1426 }
1427
1428 /* -->> -->> -->> -->>
1429
1430 PNM IMAGE FORMAT
1431
1432 <<-- <<-- <<-- <<-- */
1433
1434 struct pnm_header
1435 {
1436     int width, height, maxval, depth, format;
1437     char rgb, rgba, gray, graya, bw;
1438     char ok;
1439 };
1440
1441 static char *skip_white(char *s)
1442 {
1443     while(*s)
1444    {
1445     if(*s == '\n' || *s == '\r') return NULL;
1446     if(isspace(*s)) { ++s; continue; }
1447     return s;
1448    }
1449     return NULL;
1450 }
1451
1452 static char *skip_int(char *start, int *out_n)
1453 {
1454     char *s;
1455     char c;
1456
1457     *out_n = 0; s = start;
1458
1459     s = skip_white(start);
1460     if(s == NULL) return NULL;
1461     start = s;
1462
1463     while(*s)
1464    {
1465     if( !isdigit(*s)) break;
1466     ++s;
1467    }
1468     c = *s; *s = 0; *out_n = atoi(start); *s = c;
1469     return s;
1470 }
1471
1472 static char *skip_idf(char *start, char out_idf[256])
1473 {
1474     char *s;
1475     char c;
1476
1477     s = skip_white(start);
1478     if(s == NULL) return NULL;
1479     start = s;
1480
1481     while(*s)
1482    {
1483     if(isalpha(*s) || *s == '_') { ++s; continue; }
1484     break;
1485    }
1486     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
1487     return s;
1488 }
1489
1490 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1491 {
1492     char *s;
1493     int format, have_wh, end, ttype;
1494     char idf[256], type[256];
1495     char line[256];
1496
1497     if (fgets(line, 250, reader) == NULL)
1498     {
1499         fprintf(stderr,"\nWARNING: fgets return a NULL value");
1500         return;
1501     }
1502
1503     if(line[0] != 'P')
1504    {
1505     fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
1506    }
1507     format = atoi(line + 1);
1508     if(format < 1 || format > 7)
1509    {
1510     fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1511     return;
1512    }
1513     ph->format = format;
1514     ttype = end = have_wh = 0;
1515
1516     while(fgets(line, 250, reader))
1517    {
1518     if(*line == '#') continue;
1519
1520     s = line;
1521
1522     if(format == 7)
1523   {
1524     s = skip_idf(s, idf);
1525
1526     if(s == NULL || *s == 0) return;
1527
1528     if(strcmp(idf, "ENDHDR") == 0)
1529  {
1530     end = 1; break;
1531  }
1532     if(strcmp(idf, "WIDTH") == 0)
1533  {
1534     s = skip_int(s, &ph->width);
1535     if(s == NULL || *s == 0) return;
1536
1537     continue;
1538  }
1539     if(strcmp(idf, "HEIGHT") == 0)
1540  {
1541     s = skip_int(s, &ph->height);
1542     if(s == NULL || *s == 0) return;
1543
1544     continue;
1545  }
1546     if(strcmp(idf, "DEPTH") == 0)
1547  {
1548     s = skip_int(s, &ph->depth);
1549     if(s == NULL || *s == 0) return;
1550
1551     continue;
1552  }
1553     if(strcmp(idf, "MAXVAL") == 0)
1554  {
1555     s = skip_int(s, &ph->maxval);
1556     if(s == NULL || *s == 0) return;
1557
1558     continue;
1559  }
1560     if(strcmp(idf, "TUPLTYPE") == 0)
1561  {
1562     s = skip_idf(s, type);
1563     if(s == NULL || *s == 0) return;
1564
1565         if(strcmp(type, "BLACKANDWHITE") == 0)
1566        {
1567         ph->bw = 1; ttype = 1; continue;
1568        }
1569         if(strcmp(type, "GRAYSCALE") == 0)
1570        {
1571         ph->gray = 1; ttype = 1; continue;
1572        }
1573         if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1574        {
1575         ph->graya = 1; ttype = 1; continue;
1576        }
1577         if(strcmp(type, "RGB") == 0)
1578        {
1579         ph->rgb = 1; ttype = 1; continue;
1580        }
1581         if(strcmp(type, "RGB_ALPHA") == 0)
1582        {
1583         ph->rgba = 1; ttype = 1; continue;
1584        }
1585     fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1586     return;
1587  }
1588     fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1589     return;
1590   } /* if(format == 7) */
1591
1592     if( !have_wh)
1593   {
1594     s = skip_int(s, &ph->width);
1595
1596     s = skip_int(s, &ph->height);
1597
1598     have_wh = 1;
1599
1600     if(format == 1 || format == 4) break;
1601
1602     continue;
1603   }
1604     if(format == 2 || format == 3 || format == 5 || format == 6)
1605   {
1606 /* P2, P3, P5, P6: */
1607     s = skip_int(s, &ph->maxval);
1608
1609     if(ph->maxval > 65535) return;
1610   }
1611     break;
1612    }/* while(fgets( ) */
1613     if(format == 2 || format == 3 || format > 4)
1614    {
1615     if(ph->maxval < 1 || ph->maxval > 65535) return;
1616    }
1617     if(ph->width < 1 || ph->height < 1) return;
1618
1619     if(format == 7)
1620    {
1621     if(!end)
1622   {
1623     fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1624   }
1625     if(ph->depth < 1 || ph->depth > 4) return;
1626
1627     if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
1628      ph->ok = 1;
1629    }
1630     else
1631    {
1632     if(format != 1 && format != 4)
1633   {
1634     if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1635   }
1636     else
1637   {
1638     if(ph->width && ph->height) ph->ok = 1;
1639     ph->maxval = 255;
1640   }
1641    }
1642 }
1643
1644 static int has_prec(int val)
1645 {
1646     if(val < 2) return 1;
1647     if(val < 4) return 2;
1648     if(val < 8) return 3;
1649     if(val < 16) return 4;
1650     if(val < 32) return 5;
1651     if(val < 64) return 6;
1652     if(val < 128) return 7;
1653     if(val < 256) return 8;
1654     if(val < 512) return 9;
1655     if(val < 1024) return 10;
1656     if(val < 2048) return 11;
1657     if(val < 4096) return 12;
1658     if(val < 8192) return 13;
1659     if(val < 16384) return 14;
1660     if(val < 32768) return 15;
1661     return 16;
1662 }
1663
1664 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1665         int subsampling_dx = parameters->subsampling_dx;
1666         int subsampling_dy = parameters->subsampling_dy;
1667
1668         FILE *fp = NULL;
1669         int i, compno, numcomps, w, h, prec, format;
1670         OPJ_COLOR_SPACE color_space;
1671         opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1672         opj_image_t * image = NULL;
1673         struct pnm_header header_info;
1674         
1675         if((fp = fopen(filename, "rb")) == NULL)
1676    {
1677         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1678         return NULL;
1679    }
1680         memset(&header_info, 0, sizeof(struct pnm_header));
1681
1682         read_pnm_header(fp, &header_info);
1683
1684         if(!header_info.ok) { fclose(fp); return NULL; }
1685
1686         format = header_info.format;
1687
1688     switch(format)
1689    {
1690     case 1: /* ascii bitmap */
1691     case 4: /* raw bitmap */
1692         numcomps = 1;
1693         break;
1694
1695     case 2: /* ascii greymap */
1696     case 5: /* raw greymap */
1697         numcomps = 1;
1698         break;
1699
1700     case 3: /* ascii pixmap */
1701     case 6: /* raw pixmap */
1702         numcomps = 3;
1703         break;
1704
1705     case 7: /* arbitrary map */
1706         numcomps = header_info.depth;
1707                 break;
1708
1709     default: fclose(fp); return NULL;
1710    }
1711     if(numcomps < 3)
1712      color_space = CLRSPC_GRAY;/* GRAY, GRAYA */
1713     else
1714      color_space = CLRSPC_SRGB;/* RGB, RGBA */
1715
1716     prec = has_prec(header_info.maxval);
1717
1718         if(prec < 8) prec = 8;
1719
1720     w = header_info.width;
1721     h = header_info.height;
1722     subsampling_dx = parameters->subsampling_dx;
1723     subsampling_dy = parameters->subsampling_dy;
1724
1725     memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1726
1727     for(i = 0; i < numcomps; i++)
1728    {
1729     cmptparm[i].prec = prec;
1730     cmptparm[i].bpp = prec;
1731     cmptparm[i].sgnd = 0;
1732     cmptparm[i].dx = subsampling_dx;
1733     cmptparm[i].dy = subsampling_dy;
1734     cmptparm[i].w = w;
1735     cmptparm[i].h = h;
1736    }
1737     image = opj_image_create(numcomps, &cmptparm[0], color_space);
1738
1739     if(!image) { fclose(fp); return NULL; }
1740
1741 /* set image offset and reference grid */
1742         image->x0 = parameters->image_offset_x0;
1743         image->y0 = parameters->image_offset_y0;
1744         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
1745         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
1746
1747     if((format == 2) || (format == 3)) /* ascii pixmap */
1748    {
1749     unsigned int index;
1750
1751     for (i = 0; i < w * h; i++)
1752   {
1753     for(compno = 0; compno < numcomps; compno++)
1754  {
1755         index = 0;
1756     if (fscanf(fp, "%u", &index) != 1)
1757         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1758
1759     image->comps[compno].data[i] = (index * 255)/header_info.maxval;
1760  }
1761   }
1762    }
1763     else
1764     if((format == 5)
1765     || (format == 6)
1766     ||((format == 7)
1767         && (   header_info.gray || header_info.graya
1768             || header_info.rgb || header_info.rgba)))/* binary pixmap */
1769    {
1770     unsigned char c0, c1, one;
1771
1772     one = (prec < 9); 
1773
1774     for (i = 0; i < w * h; i++)
1775   {
1776     for(compno = 0; compno < numcomps; compno++)
1777  {
1778           if ( !fread(&c0, 1, 1, fp) )
1779                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1780         if(one)
1781        {
1782         image->comps[compno].data[i] = c0;
1783        }
1784         else
1785        {
1786           if ( !fread(&c1, 1, 1, fp) )
1787                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1788 /* netpbm: */
1789                 image->comps[compno].data[i] = ((c0<<8) | c1);
1790        }
1791  }
1792   }
1793    }
1794     else
1795     if(format == 1) /* ascii bitmap */
1796    {
1797     for (i = 0; i < w * h; i++)
1798   {
1799     unsigned int index;
1800
1801     if ( fscanf(fp, "%u", &index) != 1)
1802         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1803
1804     image->comps[0].data[i] = (index?0:255);
1805   }
1806    }
1807     else
1808     if(format == 4)
1809    {
1810     int x, y, bit;
1811     unsigned char uc;
1812
1813     i = 0;
1814     for(y = 0; y < h; ++y)
1815   {
1816     bit = -1; uc = 0;
1817
1818     for(x = 0; x < w; ++x)
1819  {
1820         if(bit == -1)
1821        {
1822         bit = 7;
1823         uc = (unsigned char)getc(fp);
1824        }
1825     image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1826     --bit; ++i;
1827  }
1828   }
1829    }
1830         else
1831         if((format == 7 && header_info.bw)) /*MONO*/
1832    {
1833         unsigned char uc;
1834
1835         for(i = 0; i < w * h; ++i)
1836   {
1837           if ( !fread(&uc, 1, 1, fp) )
1838                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1839         image->comps[0].data[i] = (uc & 1)?0:255;
1840   }
1841    }
1842     fclose(fp);
1843
1844     return image;
1845 }/* pnmtoimage() */
1846
1847 int imagetopnm(opj_image_t * image, const char *outfile) 
1848 {
1849         int *red, *green, *blue, *alpha;
1850         int wr, hr, max;
1851         int i, compno, ncomp;
1852         int adjustR, adjustG, adjustB, adjustA;
1853         int fails, two, want_gray, has_alpha, triple;
1854         int prec, v;
1855         FILE *fdest = NULL;
1856         const char *tmp = outfile;
1857         char *destname;
1858   alpha = NULL;
1859     if((prec = image->comps[0].prec) > 16)
1860    {
1861         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1862         "\n\t: refused.\n",__FILE__,__LINE__,prec);
1863         return 1;
1864    }
1865     two = has_alpha = 0; fails = 1;
1866         ncomp = image->numcomps;
1867
1868         while (*tmp) ++tmp; tmp -= 2; 
1869         want_gray = (*tmp == 'g' || *tmp == 'G'); 
1870         ncomp = image->numcomps;
1871
1872         if(want_gray) ncomp = 1;
1873
1874         if (ncomp == 2 /* GRAYA */
1875         || (ncomp > 2 /* RGB, RGBA */
1876                 && image->comps[0].dx == image->comps[1].dx
1877                 && image->comps[1].dx == image->comps[2].dx
1878                 && image->comps[0].dy == image->comps[1].dy
1879                 && image->comps[1].dy == image->comps[2].dy
1880                 && image->comps[0].prec == image->comps[1].prec
1881                 && image->comps[1].prec == image->comps[2].prec
1882            ))
1883    {
1884         fdest = fopen(outfile, "wb");
1885
1886         if (!fdest) 
1887   {
1888         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1889         return fails;
1890   }
1891         two = (prec > 8);
1892         triple = (ncomp > 2);
1893         wr = image->comps[0].w; hr = image->comps[0].h;
1894         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1895
1896     red = image->comps[0].data;
1897
1898         if(triple)
1899   {
1900     green = image->comps[1].data;
1901     blue = image->comps[2].data;
1902   }
1903         else green = blue = NULL;
1904         
1905         if(has_alpha)
1906   {
1907         const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1908
1909         fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1910                 "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1911                 wr, hr, ncomp, max, tt);
1912         alpha = image->comps[ncomp - 1].data;
1913         adjustA = (image->comps[ncomp - 1].sgnd ?
1914          1 << (image->comps[ncomp - 1].prec - 1) : 0);
1915   }
1916         else
1917   {
1918         fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n", 
1919                 opj_version(), wr, hr, max);
1920         adjustA = 0;
1921   }
1922     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1923
1924         if(triple)
1925   {
1926     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1927     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1928   }
1929         else adjustG = adjustB = 0;
1930
1931     for(i = 0; i < wr * hr; ++i)
1932   {
1933         if(two)
1934  {
1935         v = *red + adjustR; ++red;
1936 /* netpbm: */
1937         fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1938
1939                 if(triple)
1940            {
1941                 v = *green + adjustG; ++green;
1942 /* netpbm: */
1943                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1944
1945                 v =  *blue + adjustB; ++blue;
1946 /* netpbm: */
1947                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1948
1949            }/* if(triple) */
1950
1951         if(has_alpha)
1952        {
1953         v = *alpha + adjustA; ++alpha;
1954 /* netpbm: */
1955                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1956        }
1957         continue;
1958
1959  }      /* if(two) */
1960
1961 /* prec <= 8: */
1962
1963         fprintf(fdest, "%c", (unsigned char)*red++);
1964         if(triple)
1965          fprintf(fdest, "%c%c",(unsigned char)*green++, (unsigned char)*blue++);
1966
1967         if(has_alpha)
1968          fprintf(fdest, "%c", (unsigned char)*alpha++);
1969
1970   }     /* for(i */
1971
1972         fclose(fdest); return 0;
1973    }
1974
1975 /* YUV or MONO: */
1976
1977         if (image->numcomps > ncomp) 
1978    {
1979         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1980         fprintf(stderr,"           is written to the file\n");
1981    }
1982         destname = (char*)malloc(strlen(outfile) + 8);
1983
1984         for (compno = 0; compno < ncomp; compno++) 
1985    {
1986         if (ncomp > 1) 
1987          sprintf(destname, "%d.%s", compno, outfile);
1988         else
1989          sprintf(destname, "%s", outfile);
1990
1991         fdest = fopen(destname, "wb");
1992         if (!fdest) 
1993   {
1994         fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1995         free(destname);
1996         return 1;
1997   }
1998         wr = image->comps[compno].w; hr = image->comps[compno].h;
1999         prec = image->comps[compno].prec;
2000         max = (1<<prec) - 1;
2001
2002         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n", 
2003                 opj_version(), wr, hr, max);
2004
2005         red = image->comps[compno].data;
2006         adjustR = 
2007         (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
2008
2009     if(prec > 8)
2010   {
2011         for (i = 0; i < wr * hr; i++) 
2012  {
2013         v = *red + adjustR; ++red;
2014 /* netpbm: */
2015         fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2016
2017         if(has_alpha)
2018       {
2019         v = *alpha++;
2020 /* netpbm: */
2021                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2022       }
2023  }/* for(i */
2024   }
2025         else /* prec <= 8 */
2026   {
2027         for(i = 0; i < wr * hr; ++i)
2028  {
2029          fprintf(fdest, "%c", (unsigned char)(*red + adjustR)); ++red;
2030  }
2031   }
2032         fclose(fdest);
2033    } /* for (compno */
2034         free(destname);
2035
2036         return 0;
2037 }/* imagetopnm() */
2038
2039 #ifdef HAVE_LIBTIFF
2040 /* -->> -->> -->> -->>
2041
2042         TIFF IMAGE FORMAT
2043
2044  <<-- <<-- <<-- <<-- */
2045
2046 typedef struct tiff_infoheader{
2047         DWORD tiWidth;  /* Width of Image in pixel*/
2048         DWORD tiHeight; /* Height of Image in pixel */
2049         DWORD tiPhoto;  /* Photometric */
2050         WORD  tiBps;      /* Bits per sample */
2051         WORD  tiSf;               /* Sample Format */
2052         WORD  tiSpp;      /* Sample per pixel 1-bilevel,gray scale , 2- RGB */
2053         WORD  tiPC;         /* Planar config (1-Interleaved, 2-Planarcomp) */
2054 }tiff_infoheader_t;
2055
2056 int imagetotif(opj_image_t * image, const char *outfile) 
2057 {
2058         int width, height, imgsize;
2059         int bps,index,adjust, sgnd;
2060         int ushift, dshift, has_alpha, force16;
2061         TIFF *tif;
2062         tdata_t buf;
2063         tstrip_t strip;
2064         tsize_t strip_size;
2065
2066         ushift = dshift = force16 = has_alpha = 0;
2067         bps = image->comps[0].prec;
2068
2069         if(bps > 8 && bps < 16)
2070    {
2071         ushift = 16 - bps; dshift = bps - ushift;
2072         bps = 16; force16 = 1;
2073    }
2074
2075         if(bps != 8 && bps != 16)
2076    {
2077         fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
2078          bps);
2079         fprintf(stderr,"\tAborting\n");
2080         return 1;
2081    }
2082         tif = TIFFOpen(outfile, "wb");
2083
2084         if (!tif) 
2085    {
2086         fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
2087         return 1;
2088    }
2089         sgnd = image->comps[0].sgnd;
2090         adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
2091
2092         if(image->numcomps >= 3 
2093         && image->comps[0].dx == image->comps[1].dx
2094         && image->comps[1].dx == image->comps[2].dx
2095         && image->comps[0].dy == image->comps[1].dy
2096         && image->comps[1].dy == image->comps[2].dy
2097         && image->comps[0].prec == image->comps[1].prec
2098         && image->comps[1].prec == image->comps[2].prec) 
2099    {
2100         has_alpha = (image->numcomps == 4);
2101
2102         width   = image->comps[0].w;
2103         height  = image->comps[0].h;
2104         imgsize = width * height ;
2105  
2106         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2107         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2108         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
2109         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2110         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2111         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2112         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
2113         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2114         strip_size = TIFFStripSize(tif);
2115         buf = _TIFFmalloc(strip_size);
2116         index=0;
2117
2118         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2119   {
2120         unsigned char *dat8;
2121         tsize_t i, ssize, last_i = 0;
2122   int step, restx;
2123         ssize = TIFFStripSize(tif);
2124         dat8 = (unsigned char*)buf;
2125
2126         if(bps == 8)
2127  {
2128         step = 3 + has_alpha;
2129         restx = step - 1;
2130
2131                 for(i=0; i < ssize - restx; i += step) 
2132            {    
2133                 int r, g, b, a = 0;
2134
2135                 if(index < imgsize)
2136           {
2137                 r = image->comps[0].data[index];
2138                 g = image->comps[1].data[index];
2139                 b = image->comps[2].data[index];
2140                 if(has_alpha) a = image->comps[3].data[index];
2141
2142                 if(sgnd)
2143          {
2144                 r += adjust;
2145                 g += adjust;
2146                 b += adjust;
2147                 if(has_alpha) a += adjust;
2148          }
2149                 dat8[i+0] = r ;
2150                 dat8[i+1] = g ;
2151                 dat8[i+2] = b ;
2152                 if(has_alpha) dat8[i+3] = a;
2153
2154                 index++;
2155                 last_i = i + step;
2156           }
2157                 else
2158                  break;
2159            }/*for(i = 0;)*/
2160
2161                 if(last_i < ssize)
2162            {
2163                 for(i = last_i; i < ssize; i += step) 
2164           { 
2165                 int r, g, b, a = 0;
2166
2167                 if(index < imgsize)
2168          {
2169                 r = image->comps[0].data[index];
2170                 g = image->comps[1].data[index];
2171                 b = image->comps[2].data[index];
2172                 if(has_alpha) a = image->comps[3].data[index];
2173
2174                 if(sgnd)
2175         {
2176                 r += adjust;
2177                 g += adjust;
2178                 b += adjust;
2179                 if(has_alpha) a += adjust;
2180         }
2181                 dat8[i+0] = r ;
2182                 if(i+1 < ssize) dat8[i+1] = g ;  else break;
2183                 if(i+2 < ssize) dat8[i+2] = b ;  else break;
2184                 if(has_alpha)
2185         {
2186                 if(i+3 < ssize) dat8[i+3] = a ;  else break;
2187         }
2188                 index++;
2189          }
2190                 else
2191                  break;
2192           }/*for(i)*/
2193            }/*if(last_i < ssize)*/
2194
2195  }      /*if(bps == 8)*/
2196         else 
2197         if(bps == 16)
2198  {
2199         step = 6 + has_alpha + has_alpha;
2200         restx = step - 1;
2201
2202                 for(i = 0; i < ssize - restx ; i += step) 
2203            {  
2204                 int r, g, b, a = 0;
2205
2206                 if(index < imgsize)
2207           {
2208                 r = image->comps[0].data[index];
2209                 g = image->comps[1].data[index];
2210                 b = image->comps[2].data[index];
2211                 if(has_alpha) a = image->comps[3].data[index];
2212
2213                 if(sgnd)
2214          {
2215                 r += adjust;
2216                 g += adjust;
2217                 b += adjust;
2218                 if(has_alpha) a += adjust;
2219          }
2220                 if(force16) 
2221          { 
2222                 r = (r<<ushift) + (r>>dshift); 
2223                 g = (g<<ushift) + (g>>dshift); 
2224                 b = (b<<ushift) + (b>>dshift); 
2225                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2226          }
2227                 dat8[i+0] =  r;/*LSB*/
2228                 dat8[i+1] = (r >> 8);/*MSB*/
2229                 dat8[i+2] =  g;
2230                 dat8[i+3] = (g >> 8);
2231                 dat8[i+4] =  b;
2232                 dat8[i+5] = (b >> 8);
2233                 if(has_alpha) 
2234          { 
2235                 dat8[i+6] =  a; 
2236                 dat8[i+7] = (a >> 8); 
2237          }
2238                 index++;
2239                 last_i = i + step;
2240           }
2241                 else
2242                  break;
2243            }/*for(i = 0;)*/
2244
2245                 if(last_i < ssize)
2246            {
2247                 for(i = last_i ; i < ssize ; i += step) 
2248           {    
2249                 int r, g, b, a = 0;
2250
2251                 if(index < imgsize)
2252          {
2253                 r = image->comps[0].data[index];
2254                 g = image->comps[1].data[index];
2255                 b = image->comps[2].data[index];
2256                 if(has_alpha) a = image->comps[3].data[index];
2257
2258                 if(sgnd)
2259         {
2260                 r += adjust;
2261                 g += adjust;
2262                 b += adjust;
2263                 if(has_alpha) a += adjust;
2264         }
2265             if(force16)
2266         {
2267             r = (r<<ushift) + (r>>dshift);
2268             g = (g<<ushift) + (g>>dshift);
2269             b = (b<<ushift) + (b>>dshift);
2270             if(has_alpha) a = (a<<ushift) + (a>>dshift);
2271         }
2272                 dat8[i+0] =  r;/*LSB*/
2273                 if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;/*MSB*/
2274                 if(i+2 < ssize) dat8[i+2] =  g;      else break;
2275                 if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
2276                 if(i+4 < ssize) dat8[i+4] =  b;      else break;
2277                 if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
2278
2279                 if(has_alpha)
2280         {
2281                 if(i+6 < ssize) dat8[i+6] = a; else break;
2282                 if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
2283         }
2284                 index++;
2285          }
2286                 else
2287                  break;
2288           }/*for(i)*/
2289            }/*if(last_i < ssize)*/
2290
2291  }/*if(bps == 16)*/
2292         (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2293   }/*for(strip = 0; )*/
2294
2295         _TIFFfree((void*)buf);
2296         TIFFClose(tif);
2297
2298         return 0;
2299    }/*RGB(A)*/
2300
2301         if(image->numcomps == 1 /* GRAY */
2302         || (   image->numcomps == 2 /* GRAY_ALPHA */
2303                 && image->comps[0].dx == image->comps[1].dx
2304                 && image->comps[0].dy == image->comps[1].dy
2305                 && image->comps[0].prec == image->comps[1].prec))
2306    {
2307         int step;
2308
2309         has_alpha = (image->numcomps == 2);
2310
2311         width   = image->comps[0].w;
2312         height  = image->comps[0].h;
2313         imgsize = width * height;
2314
2315 /* Set tags */
2316         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2317         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2318         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
2319         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2320         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2321         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2322         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
2323         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2324
2325 /* Get a buffer for the data */
2326         strip_size = TIFFStripSize(tif);
2327         buf = _TIFFmalloc(strip_size);
2328         index = 0;
2329
2330         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2331   {
2332         unsigned char *dat8;
2333         tsize_t i, ssize = TIFFStripSize(tif);
2334         dat8 = (unsigned char*)buf;
2335
2336         if(bps == 8)
2337  {
2338         step = 1 + has_alpha;
2339
2340                 for(i=0; i < ssize; i += step) 
2341            { 
2342                 if(index < imgsize)
2343           {
2344                 int r, a = 0;
2345
2346                 r = image->comps[0].data[index];
2347                 if(has_alpha) a = image->comps[1].data[index];
2348
2349                 if(sgnd)
2350          {
2351                 r += adjust;
2352                 if(has_alpha) a += adjust;
2353          }
2354                 dat8[i+0] = r;
2355                 if(has_alpha) dat8[i+1] = a;
2356                 index++;
2357          }
2358                 else
2359                  break;
2360           }/*for(i )*/
2361  }/*if(bps == 8*/
2362         else 
2363         if(bps == 16)
2364  {
2365         step = 2 + has_alpha + has_alpha;
2366
2367                 for(i=0; i < ssize; i += step) 
2368            {
2369                 if(index < imgsize)
2370           {
2371                 int r, a = 0;
2372
2373                 r = image->comps[0].data[index];
2374                 if(has_alpha) a = image->comps[1].data[index];
2375
2376                 if(sgnd)
2377          {
2378                 r += adjust;
2379                 if(has_alpha) a += adjust;
2380          }
2381                 if(force16)
2382          {
2383                 r = (r<<ushift) + (r>>dshift);
2384                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2385          }
2386                 dat8[i+0] = r;/*LSB*/
2387                 dat8[i+1] = r >> 8;/*MSB*/
2388                 if(has_alpha)
2389          {
2390                 dat8[i+2] = a;
2391                 dat8[i+3] = a >> 8;
2392          }
2393                 index++;
2394           }/*if(index < imgsize)*/
2395                 else
2396                  break;
2397            }/*for(i )*/
2398  }
2399         (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2400   }/*for(strip*/
2401
2402         _TIFFfree(buf);
2403         TIFFClose(tif);
2404
2405         return 0;
2406    }
2407
2408         TIFFClose(tif);
2409
2410         fprintf(stderr,"imagetotif: Bad color format.\n"
2411          "\tOnly RGB(A) and GRAY(A) has been implemented\n");
2412         fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
2413          image->numcomps);
2414
2415         return 1;
2416 }/* imagetotif() */
2417
2418 /*
2419  * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
2420  * CINEMA                 : 12 bit precision
2421 */
2422 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
2423 {
2424         int subsampling_dx = parameters->subsampling_dx;
2425         int subsampling_dy = parameters->subsampling_dy;
2426         TIFF *tif;
2427         tiff_infoheader_t Info;
2428         tdata_t buf;
2429         tstrip_t strip;
2430         tsize_t strip_size;
2431         int j, numcomps, w, h,index;
2432         OPJ_COLOR_SPACE color_space;
2433         opj_image_cmptparm_t cmptparm[4]; /* RGBA */
2434         opj_image_t *image = NULL;
2435         int imgsize = 0;
2436         int has_alpha = 0;
2437
2438         tif = TIFFOpen(filename, "r");
2439
2440         if(!tif) 
2441    {
2442         fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2443         return 0;
2444    }
2445         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
2446         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
2447         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
2448         TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
2449         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
2450         Info.tiPhoto = 0;
2451         TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
2452         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
2453         w= Info.tiWidth;
2454         h= Info.tiHeight;
2455
2456    {
2457         int b, p;
2458
2459         if((b = Info.tiBps) != 8 && b != 16 && b != 12) b = 0;
2460         if((p = Info.tiPhoto) != 1 && p != 2) p = 0;
2461
2462     if( !b || !p)
2463   {
2464         if( !b)
2465      fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits"
2466       " implemented\n",Info.tiBps);
2467         else
2468         if( !p)
2469      fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2470       " and GRAY(A) has been implemented\n",(int) Info.tiPhoto);
2471
2472     fprintf(stderr,"\tAborting\n");
2473         TIFFClose(tif);
2474
2475     return NULL;
2476   }
2477    }
2478
2479    {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2480         uint16* sampleinfo;
2481         uint16 extrasamples;
2482
2483         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2484          &extrasamples, &sampleinfo);
2485
2486         if(extrasamples >= 1)
2487   {
2488         switch(sampleinfo[0]) 
2489  {
2490         case EXTRASAMPLE_UNSPECIFIED: 
2491 /* Workaround for some images without correct info about alpha channel
2492 */
2493                 if(Info.tiSpp > 3)
2494                  has_alpha = 1;
2495                 break;
2496
2497         case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2498         case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2499                 has_alpha = 1;
2500                 break;
2501  }
2502   }
2503    }
2504 /* initialize image components
2505 */ 
2506         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2507
2508         if(Info.tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2509    {
2510         numcomps = 3 + has_alpha;
2511         color_space = CLRSPC_SRGB;
2512
2513         for(j = 0; j < numcomps; j++) 
2514   {
2515         if(parameters->cp_cinema) 
2516  {
2517         cmptparm[j].prec = 12;
2518         cmptparm[j].bpp = 12;
2519  }
2520         else
2521  {
2522         cmptparm[j].prec = Info.tiBps;
2523         cmptparm[j].bpp = Info.tiBps;
2524  }
2525         cmptparm[j].dx = subsampling_dx;
2526         cmptparm[j].dy = subsampling_dy;
2527         cmptparm[j].w = w;
2528         cmptparm[j].h = h;
2529   }
2530
2531         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2532
2533         if(!image) 
2534   {
2535         TIFFClose(tif);
2536         return NULL;
2537   }
2538 /* set image offset and reference grid 
2539 */
2540         image->x0 = parameters->image_offset_x0;
2541         image->y0 = parameters->image_offset_y0;
2542         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2543                 image->x0 + (w - 1) * subsampling_dx + 1;
2544         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2545                 image->y0 + (h - 1) * subsampling_dy + 1;
2546
2547         buf = _TIFFmalloc(TIFFStripSize(tif));
2548
2549         strip_size=TIFFStripSize(tif);
2550         index = 0;
2551         imgsize = image->comps[0].w * image->comps[0].h ;
2552 /* Read the Image components
2553 */
2554         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2555   {
2556         unsigned char *dat8;
2557         int step;
2558         tsize_t i, ssize;
2559         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2560         dat8 = (unsigned char*)buf;
2561
2562         if(Info.tiBps == 16)
2563  {
2564         step = 6 + has_alpha + has_alpha;
2565
2566                 for(i = 0; i < ssize; i += step) 
2567            {
2568                 if(index < imgsize)
2569           {
2570                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2571                 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2572                 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2573                 if(has_alpha)
2574                  image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2575
2576                 if(parameters->cp_cinema)
2577          {
2578 /* Rounding 16 to 12 bits
2579 */
2580                 image->comps[0].data[index] = 
2581                         (image->comps[0].data[index] + 0x08) >> 4 ;
2582                 image->comps[1].data[index] = 
2583                         (image->comps[1].data[index] + 0x08) >> 4 ;
2584                 image->comps[2].data[index] = 
2585                         (image->comps[2].data[index] + 0x08) >> 4 ;
2586                 if(has_alpha)
2587                  image->comps[3].data[index] =
2588                         (image->comps[3].data[index] + 0x08) >> 4 ;
2589          }
2590                 index++;
2591           }
2592                 else
2593                  break;
2594            }/*for(i = 0)*/
2595  }/*if(Info.tiBps == 16)*/
2596         else 
2597         if(Info.tiBps == 8)
2598  {
2599         step = 3 + has_alpha;
2600
2601                 for(i = 0; i < ssize; i += step) 
2602            {
2603                 if(index < imgsize)
2604           {
2605                 image->comps[0].data[index] = dat8[i+0];/* R */
2606                 image->comps[1].data[index] = dat8[i+1];/* G */
2607                 image->comps[2].data[index] = dat8[i+2];/* B */
2608                 if(has_alpha)
2609                  image->comps[3].data[index] = dat8[i+3];
2610
2611                 if(parameters->cp_cinema)
2612          {
2613 /* Rounding 8 to 12 bits
2614 */
2615                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2616                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2617                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2618                 if(has_alpha)
2619                  image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2620          }
2621                 index++;
2622           }/*if(index*/
2623                 else
2624                  break;
2625            }/*for(i )*/
2626  }/*if( Info.tiBps == 8)*/
2627         else
2628         if(Info.tiBps == 12)/* CINEMA file */
2629  {
2630         step = 9;
2631
2632                 for(i = 0; i < ssize; i += step) 
2633            {
2634                 if((index < imgsize)&(index+1 < imgsize))
2635           {
2636                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
2637                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2638
2639                 image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
2640                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2641
2642                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
2643                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2644
2645                 index += 2;
2646           }
2647                 else
2648                  break;
2649            }/*for(i )*/
2650  }
2651   }/*for(strip = 0; )*/
2652
2653         _TIFFfree(buf);
2654         TIFFClose(tif);
2655
2656         return image;
2657    }/*RGB(A)*/
2658
2659         if(Info.tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2660    {
2661         numcomps = 1 + has_alpha;
2662         color_space = CLRSPC_GRAY;
2663
2664         for(j = 0; j < numcomps; ++j)
2665   {
2666         cmptparm[j].prec = Info.tiBps;
2667         cmptparm[j].bpp = Info.tiBps;
2668         cmptparm[j].dx = subsampling_dx;
2669         cmptparm[j].dy = subsampling_dy;
2670         cmptparm[j].w = w;
2671         cmptparm[j].h = h;
2672   }
2673         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2674
2675         if(!image) 
2676   {
2677         TIFFClose(tif);
2678         return NULL;
2679   }
2680 /* set image offset and reference grid 
2681 */
2682         image->x0 = parameters->image_offset_x0;
2683         image->y0 = parameters->image_offset_y0;
2684         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2685                 image->x0 + (w - 1) * subsampling_dx + 1;
2686         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2687                 image->y0 + (h - 1) * subsampling_dy + 1;
2688
2689         buf = _TIFFmalloc(TIFFStripSize(tif));
2690
2691         strip_size = TIFFStripSize(tif);
2692         index = 0;
2693         imgsize = image->comps[0].w * image->comps[0].h ;
2694 /* Read the Image components
2695 */
2696         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
2697   {
2698         unsigned char *dat8;
2699         tsize_t i, ssize;
2700         int step;
2701
2702         ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2703         dat8 = (unsigned char*)buf;
2704
2705                 if(Info.tiBps == 16)
2706            {
2707                 step = 2 + has_alpha + has_alpha;
2708
2709                 for(i = 0; i < ssize; i += step) 
2710           {
2711                 if(index < imgsize)
2712          {
2713                 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2714                 if(has_alpha)
2715                  image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2716                 index++;
2717          }
2718                 else
2719                  break;
2720           }/*for(i )*/
2721            }
2722                 else 
2723                 if(Info.tiBps == 8)
2724            {
2725                 step = 1 + has_alpha;
2726
2727                 for(i = 0; i < ssize; i += step) 
2728           {
2729                 if(index < imgsize)
2730          {
2731                 image->comps[0].data[index] = dat8[i+0];
2732                 if(has_alpha)
2733                  image->comps[1].data[index] = dat8[i+1];
2734                 index++;
2735          }
2736                 else
2737                  break;
2738           }/*for(i )*/
2739            }
2740   }/*for(strip = 0;*/
2741
2742         _TIFFfree(buf);
2743         TIFFClose(tif);
2744
2745    }/*GRAY(A)*/
2746
2747         return image;
2748
2749 }/* tiftoimage() */
2750
2751 #endif /* HAVE_LIBTIFF */
2752
2753 /* -->> -->> -->> -->>
2754
2755         RAW IMAGE FORMAT
2756
2757  <<-- <<-- <<-- <<-- */
2758
2759 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2760         int subsampling_dx = parameters->subsampling_dx;
2761         int subsampling_dy = parameters->subsampling_dy;
2762
2763         FILE *f = NULL;
2764         int i, compno, numcomps, w, h;
2765         OPJ_COLOR_SPACE color_space;
2766         opj_image_cmptparm_t *cmptparm; 
2767         opj_image_t * image = NULL;
2768         unsigned short ch;
2769         
2770         if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2771         {
2772                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2773                 fprintf(stderr,"Please use the Format option -F:\n");
2774                 fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
2775                 fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
2776                 fprintf(stderr,"Aborting\n");
2777                 return NULL;
2778         }
2779
2780         f = fopen(filename, "rb");
2781         if (!f) {
2782                 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2783                 fprintf(stderr,"Aborting\n");
2784                 return NULL;
2785         }
2786         numcomps = raw_cp->rawComp;
2787         color_space = CLRSPC_SRGB;
2788         w = raw_cp->rawWidth;
2789         h = raw_cp->rawHeight;
2790         cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
2791         
2792         /* initialize image components */       
2793         memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
2794         for(i = 0; i < numcomps; i++) {         
2795                 cmptparm[i].prec = raw_cp->rawBitDepth;
2796                 cmptparm[i].bpp = raw_cp->rawBitDepth;
2797                 cmptparm[i].sgnd = raw_cp->rawSigned;
2798                 cmptparm[i].dx = subsampling_dx;
2799                 cmptparm[i].dy = subsampling_dy;
2800                 cmptparm[i].w = w;
2801                 cmptparm[i].h = h;
2802         }
2803         /* create the image */
2804         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2805         if(!image) {
2806                 fclose(f);
2807                 return NULL;
2808         }
2809         /* set image offset and reference grid */
2810         image->x0 = parameters->image_offset_x0;
2811         image->y0 = parameters->image_offset_y0;
2812         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
2813         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
2814
2815         if(raw_cp->rawBitDepth <= 8)
2816         {
2817                 unsigned char value = 0;
2818                 for(compno = 0; compno < numcomps; compno++) {
2819                         for (i = 0; i < w * h; i++) {
2820                                 if (!fread(&value, 1, 1, f)) {
2821                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2822                                         return NULL;
2823                                 }
2824                                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2825                         }
2826                 }
2827         }
2828         else if(raw_cp->rawBitDepth <= 16)
2829         {
2830                 unsigned short value;
2831                 for(compno = 0; compno < numcomps; compno++) {
2832                         for (i = 0; i < w * h; i++) {
2833                                 unsigned char temp;
2834                                 if (!fread(&temp, 1, 1, f)) {
2835                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2836                                         return NULL;
2837                                 }
2838                                 value = temp << 8;
2839                                 if (!fread(&temp, 1, 1, f)) {
2840                                         fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2841                                         return NULL;
2842                                 }
2843                                 value += temp;
2844                                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2845                         }
2846                 }
2847         }
2848         else {
2849                 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2850                 return NULL;
2851         }
2852
2853         if (fread(&ch, 1, 1, f)) {
2854                 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2855         }
2856         fclose(f);
2857
2858         return image;
2859 }
2860
2861 int imagetoraw(opj_image_t * image, const char *outfile)
2862 {
2863         FILE *rawFile = NULL;
2864   size_t res;
2865         int compno;
2866         int w, h;
2867         int line, row;
2868         int *ptr;
2869
2870         if((image->numcomps * image->x1 * image->y1) == 0)
2871         {
2872                 fprintf(stderr,"\nError: invalid raw image parameters\n");
2873                 return 1;
2874         }
2875
2876         rawFile = fopen(outfile, "wb");
2877         if (!rawFile) {
2878                 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2879                 return 1;
2880         }
2881
2882         fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2883
2884         for(compno = 0; compno < image->numcomps; compno++)
2885         {
2886                 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2887                         image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2888
2889                 w = image->comps[compno].w;
2890                 h = image->comps[compno].h;
2891
2892                 if(image->comps[compno].prec <= 8)
2893                 {
2894                         if(image->comps[compno].sgnd == 1)
2895                         {
2896                                 signed char curr;
2897                                 int mask = (1 << image->comps[compno].prec) - 1;
2898                                 ptr = image->comps[compno].data;
2899                                 for (line = 0; line < h; line++) {
2900                                         for(row = 0; row < w; row++)    {                               
2901                                                 curr = (signed char) (*ptr & mask);
2902                                                 res = fwrite(&curr, sizeof(signed char), 1, rawFile);
2903             if( res < 1 ) {
2904               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2905               return 1;
2906             }
2907                                                 ptr++;
2908                                         }
2909                                 }
2910                         }
2911                         else if(image->comps[compno].sgnd == 0)
2912                         {
2913                                 unsigned char curr;
2914                                 int mask = (1 << image->comps[compno].prec) - 1;
2915                                 ptr = image->comps[compno].data;
2916                                 for (line = 0; line < h; line++) {
2917                                         for(row = 0; row < w; row++)    {       
2918                                                 curr = (unsigned char) (*ptr & mask);
2919                                                 res = fwrite(&curr, sizeof(unsigned char), 1, rawFile);
2920             if( res < 1 ) {
2921               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2922               return 1;
2923             }
2924                                                 ptr++;
2925                                         }
2926                                 }
2927                         }
2928                 }
2929                 else if(image->comps[compno].prec <= 16)
2930                 {
2931                         if(image->comps[compno].sgnd == 1)
2932                         {
2933                                 signed short int curr;
2934                                 int mask = (1 << image->comps[compno].prec) - 1;
2935                                 ptr = image->comps[compno].data;
2936                                 for (line = 0; line < h; line++) {
2937                                         for(row = 0; row < w; row++)    {                                       
2938                                                 unsigned char temp;
2939                                                 curr = (signed short int) (*ptr & mask);
2940                                                 temp = (unsigned char) (curr >> 8);
2941                                                 res = fwrite(&temp, 1, 1, rawFile);
2942             if( res < 1 ) {
2943               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2944               return 1;
2945             }
2946                                                 temp = (unsigned char) curr;
2947                                                 res = fwrite(&temp, 1, 1, rawFile);
2948             if( res < 1 ) {
2949               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2950               return 1;
2951             }
2952                                                 ptr++;
2953                                         }
2954                                 }
2955                         }
2956                         else if(image->comps[compno].sgnd == 0)
2957                         {
2958                                 unsigned short int curr;
2959                                 int mask = (1 << image->comps[compno].prec) - 1;
2960                                 ptr = image->comps[compno].data;
2961                                 for (line = 0; line < h; line++) {
2962                                         for(row = 0; row < w; row++)    {                               
2963                                                 unsigned char temp;
2964                                                 curr = (unsigned short int) (*ptr & mask);
2965                                                 temp = (unsigned char) (curr >> 8);
2966                                                 res = fwrite(&temp, 1, 1, rawFile);
2967             if( res < 1 ) {
2968               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2969               return 1;
2970             }
2971                                                 temp = (unsigned char) curr;
2972                                                 res = fwrite(&temp, 1, 1, rawFile);
2973             if( res < 1 ) {
2974               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2975               return 1;
2976             }
2977                                                 ptr++;
2978                                         }
2979                                 }
2980                         }
2981                 }
2982                 else if (image->comps[compno].prec <= 32)
2983                 {
2984                         fprintf(stderr,"More than 16 bits per component no handled yet\n");
2985                         return 1;
2986                 }
2987                 else
2988                 {
2989                         fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2990                         return 1;
2991                 }
2992         }
2993         fclose(rawFile);
2994         return 0;
2995 }
2996
2997 #ifdef HAVE_LIBPNG
2998
2999 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
3000 #define MAGIC_SIZE 8
3001 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
3002
3003 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
3004 {
3005         png_structp  png;
3006         png_infop    info;
3007         double gamma, display_exponent;
3008         int bit_depth, interlace_type,compression_type, filter_type;
3009         int unit;
3010         png_uint_32 resx, resy;
3011         unsigned int i, j;
3012         png_uint_32  width, height;
3013         int color_type, has_alpha, is16;
3014         unsigned char *s;
3015         FILE *reader;
3016         unsigned char **rows;
3017 /* j2k: */
3018         opj_image_t *image;
3019         opj_image_cmptparm_t cmptparm[4];
3020         int sub_dx, sub_dy;
3021         unsigned int nr_comp;
3022         int *r, *g, *b, *a;
3023         unsigned char sigbuf[8];
3024
3025         if((reader = fopen(read_idf, "rb")) == NULL)
3026    {
3027         fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
3028         return NULL;
3029    }
3030         image = NULL; png = NULL; rows = NULL;
3031
3032         if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
3033         || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
3034    {
3035         fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
3036         goto fin;
3037    }
3038 /* libpng-VERSION/example.c: 
3039  * PC : screen_gamma = 2.2;
3040  * Mac: screen_gamma = 1.7 or 1.0;
3041 */
3042         display_exponent = 2.2;
3043
3044         if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
3045                                     NULL, NULL, NULL)) == NULL)
3046           goto fin;
3047         if((info = png_create_info_struct(png)) == NULL)
3048           goto fin;
3049
3050         if(setjmp(png_jmpbuf(png)))
3051           goto fin;
3052
3053         png_init_io(png, reader);
3054         png_set_sig_bytes(png, MAGIC_SIZE);
3055
3056         png_read_info(png, info);
3057
3058         if(png_get_IHDR(png, info, &width, &height,
3059                 &bit_depth, &color_type, &interlace_type, 
3060                 &compression_type, &filter_type) == 0)
3061          goto fin;
3062
3063 /* png_set_expand():
3064  * expand paletted images to RGB, expand grayscale images of
3065  * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
3066  * to alpha channels.
3067 */
3068         if(color_type == PNG_COLOR_TYPE_PALETTE)
3069           png_set_expand(png);
3070         else
3071         if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
3072           png_set_expand(png);
3073
3074         if(png_get_valid(png, info, PNG_INFO_tRNS))
3075           png_set_expand(png);
3076
3077         is16 = (bit_depth == 16);
3078
3079 /* GRAY => RGB; GRAY_ALPHA => RGBA
3080 */
3081         if(color_type == PNG_COLOR_TYPE_GRAY
3082         || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
3083    {
3084         png_set_gray_to_rgb(png);
3085         color_type = 
3086          (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
3087                 PNG_COLOR_TYPE_RGB_ALPHA);
3088    }
3089         if( !png_get_gAMA(png, info, &gamma))
3090           gamma = 0.45455;
3091
3092         png_set_gamma(png, display_exponent, gamma);
3093
3094         png_read_update_info(png, info);
3095
3096         png_get_pHYs(png, info, &resx, &resy, &unit);
3097
3098         color_type = png_get_color_type(png, info);
3099
3100         has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
3101
3102         nr_comp = 3 + has_alpha;
3103
3104         bit_depth = png_get_bit_depth(png, info);
3105
3106         rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
3107         for(i = 0; i < height; ++i)
3108          rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
3109
3110         png_read_image(png, rows);
3111
3112         memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
3113
3114         sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
3115
3116         for(i = 0; i < nr_comp; ++i)
3117    {
3118         cmptparm[i].prec = bit_depth;
3119 /* bits_per_pixel: 8 or 16 */
3120         cmptparm[i].bpp = bit_depth;
3121         cmptparm[i].sgnd = 0;
3122         cmptparm[i].dx = sub_dx;
3123         cmptparm[i].dy = sub_dy;
3124         cmptparm[i].w = width;
3125         cmptparm[i].h = height;
3126    }
3127
3128         image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
3129
3130         if(image == NULL) goto fin;
3131
3132     image->x0 = params->image_offset_x0;
3133     image->y0 = params->image_offset_y0;
3134     image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
3135     image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
3136
3137         r = image->comps[0].data;
3138         g = image->comps[1].data;
3139         b = image->comps[2].data;
3140         a = image->comps[3].data;
3141
3142         for(i = 0; i < height; ++i)
3143    {
3144         s = rows[i];
3145
3146         for(j = 0; j < width; ++j)
3147   {
3148         if(is16)
3149  {
3150         *r++ = s[0]<<8|s[1]; s += 2;
3151
3152         *g++ = s[0]<<8|s[1]; s += 2;
3153         
3154         *b++ = s[0]<<8|s[1]; s += 2;
3155         
3156         if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
3157
3158         continue;
3159  }
3160         *r++ = *s++; *g++ = *s++; *b++ = *s++;
3161
3162         if(has_alpha) *a++ = *s++;
3163   }
3164    }
3165 fin:
3166         if(rows)
3167    {
3168         for(i = 0; i < height; ++i)
3169          free(rows[i]);
3170         free(rows);
3171    }
3172         if(png)
3173           png_destroy_read_struct(&png, &info, NULL);
3174
3175         fclose(reader);
3176
3177         return image;
3178
3179 }/* pngtoimage() */
3180
3181 int imagetopng(opj_image_t * image, const char *write_idf)
3182 {
3183         FILE *writer;
3184         png_structp png;
3185         png_infop info;
3186         int *red, *green, *blue, *alpha;
3187         unsigned char *row_buf, *d;
3188         int has_alpha, width, height, nr_comp, color_type;
3189         int adjustR, adjustG, adjustB, x, y, fails, is16, force16;
3190   int opj_prec, prec, ushift, dshift;
3191         unsigned short mask = 0xffff;
3192         png_color_8 sig_bit;
3193
3194         is16 = force16 = ushift = dshift = 0; fails = 1;
3195         prec = opj_prec = image->comps[0].prec;
3196
3197         if(prec > 8 && prec < 16)
3198    {
3199          prec = 16; force16 = 1;
3200    }
3201         if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
3202    {
3203         fprintf(stderr,"imagetopng: can not create %s"
3204          "\n\twrong bit_depth %d\n", write_idf, prec);
3205         return fails;
3206    }
3207         writer = fopen(write_idf, "wb");
3208
3209         if(writer == NULL) return fails;
3210
3211         info = NULL; has_alpha = 0;
3212
3213 /* Create and initialize the png_struct with the desired error handler
3214  * functions.  If you want to use the default stderr and longjump method,
3215  * you can supply NULL for the last three parameters.  We also check that
3216  * the library version is compatible with the one used at compile time,
3217  * in case we are using dynamically linked libraries.  REQUIRED.
3218 */
3219         png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
3220                 NULL, NULL, NULL);
3221 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
3222
3223         if(png == NULL) goto fin;
3224
3225 /* Allocate/initialize the image information data.  REQUIRED 
3226 */
3227         info = png_create_info_struct(png);
3228
3229         if(info == NULL) goto fin;
3230
3231 /* Set error handling.  REQUIRED if you are not supplying your own
3232  * error handling functions in the png_create_write_struct() call.
3233 */
3234         if(setjmp(png_jmpbuf(png))) goto fin;
3235
3236 /* I/O initialization functions is REQUIRED 
3237 */
3238         png_init_io(png, writer);
3239
3240 /* Set the image information here.  Width and height are up to 2^31,
3241  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
3242  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
3243  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
3244  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
3245  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
3246  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
3247  * REQUIRED
3248 */
3249         png_set_compression_level(png, Z_BEST_COMPRESSION);
3250
3251         if(prec == 16) mask = 0xffff;
3252         else
3253         if(prec == 8) mask = 0x00ff;
3254         else
3255         if(prec == 4) mask = 0x000f;
3256         else
3257         if(prec == 2) mask = 0x0003;
3258         else
3259         if(prec == 1) mask = 0x0001;
3260
3261         nr_comp = image->numcomps;
3262
3263         if(nr_comp >= 3
3264     && image->comps[0].dx == image->comps[1].dx
3265     && image->comps[1].dx == image->comps[2].dx
3266     && image->comps[0].dy == image->comps[1].dy
3267     && image->comps[1].dy == image->comps[2].dy
3268     && image->comps[0].prec == image->comps[1].prec
3269     && image->comps[1].prec == image->comps[2].prec)
3270    {
3271         int v;
3272
3273     has_alpha = (nr_comp > 3); 
3274
3275         is16 = (prec == 16);
3276         
3277     width = image->comps[0].w;
3278     height = image->comps[0].h;
3279
3280         red = image->comps[0].data;
3281         green = image->comps[1].data;
3282         blue = image->comps[2].data;
3283
3284     sig_bit.red = sig_bit.green = sig_bit.blue = prec;
3285
3286         if(has_alpha) 
3287   {
3288         sig_bit.alpha = prec;
3289         alpha = image->comps[3].data; 
3290         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
3291   }
3292         else 
3293   {
3294         sig_bit.alpha = 0; alpha = NULL;
3295         color_type = PNG_COLOR_TYPE_RGB;
3296   }
3297         png_set_sBIT(png, info, &sig_bit);
3298
3299         png_set_IHDR(png, info, width, height, prec, 
3300          color_type,
3301          PNG_INTERLACE_NONE,
3302          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3303
3304 /*=============================*/
3305         png_write_info(png, info);
3306 /*=============================*/
3307         if(opj_prec < 8)
3308   {
3309         png_set_packing(png);
3310   }
3311         if(force16)
3312   {
3313         ushift = 16 - opj_prec; dshift = opj_prec - ushift;     
3314   }
3315     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3316     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3317     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
3318
3319         row_buf = (unsigned char*)malloc(width * nr_comp * 2);
3320
3321         for(y = 0; y < height; ++y)
3322   {
3323         d = row_buf;
3324
3325         for(x = 0; x < width; ++x)
3326  {
3327                 if(is16)
3328            {
3329                 v = *red + adjustR; ++red;
3330                 
3331                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3332
3333                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3334
3335                 v = *green + adjustG; ++green;
3336                 
3337                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3338
3339                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3340
3341                 v =  *blue + adjustB; ++blue;
3342                 
3343                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3344
3345                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3346
3347                 if(has_alpha)
3348           {
3349                 v = *alpha++;
3350                 
3351                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3352
3353                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3354           }
3355                 continue;
3356            }
3357                 *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
3358                 *d++ = (unsigned char)((*green + adjustG) & mask); ++green;
3359                 *d++ = (unsigned char)((*blue + adjustB) & mask); ++blue;
3360
3361                 if(has_alpha)
3362            {
3363                 *d++ = (unsigned char)(*alpha & mask); ++alpha;
3364            }
3365  }      /* for(x) */
3366
3367         png_write_row(png, row_buf);
3368
3369   }     /* for(y) */
3370         free(row_buf);
3371
3372    }/* nr_comp >= 3 */
3373         else
3374         if(nr_comp == 1 /* GRAY */
3375         || (   nr_comp == 2 /* GRAY_ALPHA */
3376                 && image->comps[0].dx == image->comps[1].dx
3377                 && image->comps[0].dy == image->comps[1].dy
3378                 && image->comps[0].prec == image->comps[1].prec))
3379    {
3380         int v;
3381
3382         red = image->comps[0].data;
3383
3384     if(force16)
3385   {
3386     ushift = 16 - opj_prec; dshift = opj_prec - ushift;
3387   }
3388     sig_bit.gray = prec;
3389     sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3390         alpha = NULL;
3391         color_type = PNG_COLOR_TYPE_GRAY;
3392
3393     if(nr_comp == 2) 
3394   { 
3395         has_alpha = 1; sig_bit.alpha = prec;
3396         alpha = image->comps[1].data;
3397         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3398   }
3399     width = image->comps[0].w;
3400     height = image->comps[0].h;
3401
3402         png_set_IHDR(png, info, width, height, sig_bit.gray,
3403      color_type,
3404      PNG_INTERLACE_NONE,
3405      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3406
3407         png_set_sBIT(png, info, &sig_bit);
3408 /*=============================*/
3409         png_write_info(png, info);
3410 /*=============================*/
3411         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3412
3413         if(opj_prec < 8)
3414   {
3415         png_set_packing(png);
3416   }
3417
3418         if(prec > 8)
3419   {
3420         row_buf = (unsigned char*)
3421          malloc(width * nr_comp * sizeof(unsigned short));
3422
3423         for(y = 0; y < height; ++y)
3424  {
3425         d = row_buf;
3426
3427                 for(x = 0; x < width; ++x)
3428            {
3429                 v = *red + adjustR; ++red;
3430
3431                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3432
3433                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3434
3435                 if(has_alpha)
3436           {
3437                 v = *alpha++;
3438
3439                 if(force16) { v = (v<<ushift) + (v>>dshift); }
3440
3441                 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3442           }
3443            }/* for(x) */
3444         png_write_row(png, row_buf);
3445
3446  }      /* for(y) */
3447         free(row_buf);
3448   }
3449         else /* prec <= 8 */
3450   {
3451         row_buf = (unsigned char*)calloc(width, nr_comp * 2);
3452
3453         for(y = 0; y < height; ++y)
3454  {
3455         d = row_buf;
3456
3457                 for(x = 0; x < width; ++x)
3458            {
3459                 *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
3460
3461                 if(has_alpha)
3462           {
3463                 *d++ = (unsigned char)(*alpha & mask); ++alpha;
3464           }
3465            }/* for(x) */
3466
3467         png_write_row(png, row_buf);
3468
3469  }      /* for(y) */
3470         free(row_buf);
3471   }
3472    }
3473         else
3474    {
3475         fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3476         goto fin;
3477    }
3478         png_write_end(png, info);
3479
3480         fails = 0;
3481
3482 fin:
3483
3484         if(png)
3485    {
3486     png_destroy_write_struct(&png, &info);
3487    }
3488         fclose(writer);
3489
3490         if(fails) remove(write_idf);
3491
3492         return fails;
3493 }/* imagetopng() */
3494 #endif /* HAVE_LIBPNG */