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