b41618c7ee1cea77f5cc0b91081ae0f4261472eb
[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
2601     tif = TIFFOpen(filename, "r");
2602
2603     if(!tif)
2604     {
2605         fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2606         return 0;
2607     }
2608     tiBps = tiPhoto = tiSf = tiSpp = tiPC = 0;
2609     tiWidth = tiHeight = 0;
2610
2611     TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiWidth);
2612     TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiHeight);
2613     TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiBps);
2614     TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &tiSf);
2615     TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
2616     TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
2617     TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
2618     w= (int)tiWidth;
2619     h= (int)tiHeight;
2620
2621     if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
2622     if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
2623
2624     if( !tiBps || !tiPhoto)
2625     {
2626         if( !tiBps)
2627      fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
2628                     " implemented\n",tiBps);
2629         else
2630             if( !tiPhoto)
2631                 fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2632                         " and GRAY(A) has been implemented\n",(int) tiPhoto);
2633
2634         fprintf(stderr,"\tAborting\n");
2635         TIFFClose(tif);
2636
2637         return NULL;
2638     }
2639
2640     {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2641         uint16* sampleinfo;
2642         uint16 extrasamples;
2643
2644         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2645                               &extrasamples, &sampleinfo);
2646
2647         if(extrasamples >= 1)
2648         {
2649             switch(sampleinfo[0])
2650             {
2651             case EXTRASAMPLE_UNSPECIFIED:
2652                 /* Workaround for some images without correct info about alpha channel
2653 */
2654                 if(tiSpp > 3)
2655                     has_alpha = 1;
2656                 break;
2657
2658             case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2659             case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2660                 has_alpha = 1;
2661                 break;
2662             }
2663         }
2664         else /* extrasamples == 0 */
2665             if(tiSpp == 4 || tiSpp == 2) has_alpha = 1;
2666     }
2667
2668     /* initialize image components
2669 */ 
2670     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2671
2672     if ((tiPhoto == PHOTOMETRIC_RGB) && (parameters->cp_cinema)) {
2673         fprintf(stdout,"WARNING:\n"
2674                 "Input image bitdepth is %d bits\n"
2675                 "TIF conversion has automatically rescaled to 12-bits\n"
2676                 "to comply with cinema profiles.\n",
2677                 tiBps);
2678     }
2679
2680     if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2681     {
2682         numcomps = 3 + has_alpha;
2683         color_space = OPJ_CLRSPC_SRGB;
2684
2685         /*#define USETILEMODE*/
2686         for(j = 0; j < numcomps; j++)
2687         {
2688             if(parameters->cp_cinema)
2689             {
2690                 cmptparm[j].prec = 12;
2691                 cmptparm[j].bpp = 12;
2692             }
2693             else
2694             {
2695                 cmptparm[j].prec = tiBps;
2696                 cmptparm[j].bpp = tiBps;
2697             }
2698             cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2699             cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2700             cmptparm[j].w = (OPJ_UINT32)w;
2701             cmptparm[j].h = (OPJ_UINT32)h;
2702 #ifdef USETILEMODE
2703             cmptparm[j].x0 = 0;
2704             cmptparm[j].y0 = 0;
2705 #endif
2706         }
2707
2708 #ifdef USETILEMODE
2709         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2710 #else
2711         image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2712 #endif
2713
2714         if(!image)
2715         {
2716             TIFFClose(tif);
2717             return NULL;
2718         }
2719         /* set image offset and reference grid
2720 */
2721         image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2722         image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2723         image->x1 =     !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2724                                  image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2725         image->y1 =     !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2726                                  image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2727
2728         buf = _TIFFmalloc(TIFFStripSize(tif));
2729
2730         strip_size=TIFFStripSize(tif);
2731         index = 0;
2732         imgsize = (int)(image->comps[0].w * image->comps[0].h);
2733         /* Read the Image components
2734 */
2735         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2736         {
2737             unsigned char *dat8;
2738             int step;
2739             tsize_t i, ssize;
2740             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2741             dat8 = (unsigned char*)buf;
2742
2743             if(tiBps == 16)
2744             {
2745                 step = 6 + has_alpha + has_alpha;
2746
2747                 for(i = 0; i < ssize; i += step)
2748                 {
2749                     if(index < imgsize)
2750                     {
2751                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2752                         image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2753                         image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2754                         if(has_alpha)
2755                             image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2756
2757                         if(parameters->cp_cinema)
2758                         {
2759                             /* Rounding 16 to 12 bits
2760 */
2761                             image->comps[0].data[index] =
2762                                     (image->comps[0].data[index] + 0x08) >> 4 ;
2763                             image->comps[1].data[index] =
2764                                     (image->comps[1].data[index] + 0x08) >> 4 ;
2765                             image->comps[2].data[index] =
2766                                     (image->comps[2].data[index] + 0x08) >> 4 ;
2767                             if(has_alpha)
2768                                 image->comps[3].data[index] =
2769                                         (image->comps[3].data[index] + 0x08) >> 4 ;
2770                         }
2771                         index++;
2772                     }
2773                     else
2774                         break;
2775                 }/*for(i = 0)*/
2776             }/*if(tiBps == 16)*/
2777             else
2778                 if(tiBps == 8)
2779                 {
2780                     step = 3 + has_alpha;
2781
2782                     for(i = 0; i < ssize; i += step)
2783                     {
2784                         if(index < imgsize)
2785                         {
2786 #ifndef USETILEMODE
2787                             image->comps[0].data[index] = dat8[i+0];/* R */
2788                             image->comps[1].data[index] = dat8[i+1];/* G */
2789                             image->comps[2].data[index] = dat8[i+2];/* B */
2790                             if(has_alpha)
2791                                 image->comps[3].data[index] = dat8[i+3];
2792 #endif
2793
2794                             if(parameters->cp_cinema)
2795                             {
2796                                 /* Rounding 8 to 12 bits
2797 */
2798 #ifndef USETILEMODE
2799                                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2800                                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2801                                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2802                                 if(has_alpha)
2803                                     image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2804 #endif
2805                             }
2806                             index++;
2807                         }/*if(index*/
2808                         else
2809                             break;
2810                     }/*for(i )*/
2811                 }/*if( tiBps == 8)*/
2812                 else
2813                     if(tiBps == 12)/* CINEMA file */
2814                     {
2815                         step = 9;
2816
2817                         for(i = 0; i < ssize; i += step)
2818                         {
2819                             if((index < imgsize)&(index+1 < imgsize))
2820                             {
2821                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
2822                                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2823
2824                                 image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
2825                                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2826
2827                                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
2828                                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2829
2830                                 index += 2;
2831                             }
2832                             else
2833                                 break;
2834                         }/*for(i )*/
2835                     }
2836         }/*for(strip = 0; )*/
2837
2838         _TIFFfree(buf);
2839         TIFFClose(tif);
2840
2841         return image;
2842     }/*RGB(A)*/
2843
2844     if(tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2845     {
2846         numcomps = 1 + has_alpha;
2847         color_space = OPJ_CLRSPC_GRAY;
2848
2849         for(j = 0; j < numcomps; ++j)
2850         {
2851             cmptparm[j].prec = tiBps;
2852             cmptparm[j].bpp = tiBps;
2853             cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2854             cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2855             cmptparm[j].w = (OPJ_UINT32)w;
2856             cmptparm[j].h = (OPJ_UINT32)h;
2857         }
2858 #ifdef USETILEMODE
2859         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2860 #else
2861         image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2862 #endif
2863
2864         if(!image)
2865         {
2866             TIFFClose(tif);
2867             return NULL;
2868         }
2869         /* set image offset and reference grid
2870 */
2871         image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2872         image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2873         image->x1 =     !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2874                                  image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2875         image->y1 =     !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2876                                  image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2877
2878         buf = _TIFFmalloc(TIFFStripSize(tif));
2879
2880         strip_size = TIFFStripSize(tif);
2881         index = 0;
2882         imgsize = (int)(image->comps[0].w * image->comps[0].h);
2883         /* Read the Image components
2884 */
2885         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2886         {
2887             unsigned char *dat8;
2888             tsize_t i, ssize;
2889             int step;
2890
2891             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2892             dat8 = (unsigned char*)buf;
2893
2894             if(tiBps == 16)
2895             {
2896                 step = 2 + has_alpha + has_alpha;
2897
2898                 for(i = 0; i < ssize; i += step)
2899                 {
2900                     if(index < imgsize)
2901                     {
2902                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2903                         if(has_alpha)
2904                             image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2905                         index++;
2906                     }
2907                     else
2908                         break;
2909                 }/*for(i )*/
2910             }
2911             else
2912                 if(tiBps == 8)
2913                 {
2914                     step = 1 + has_alpha;
2915
2916                     for(i = 0; i < ssize; i += step)
2917                     {
2918                         if(index < imgsize)
2919                         {
2920                             image->comps[0].data[index] = dat8[i+0];
2921                             if(has_alpha)
2922                                 image->comps[1].data[index] = dat8[i+1];
2923                             index++;
2924                         }
2925                         else
2926                             break;
2927                     }/*for(i )*/
2928                 }
2929         }/*for(strip = 0;*/
2930
2931         _TIFFfree(buf);
2932         TIFFClose(tif);
2933
2934     }/*GRAY(A)*/
2935
2936     return image;
2937
2938 }/* tiftoimage() */
2939
2940 #endif /* OPJ_HAVE_LIBTIFF */
2941
2942 /* -->> -->> -->> -->>
2943
2944     RAW IMAGE FORMAT
2945
2946  <<-- <<-- <<-- <<-- */
2947 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
2948     int subsampling_dx = parameters->subsampling_dx;
2949     int subsampling_dy = parameters->subsampling_dy;
2950
2951     FILE *f = NULL;
2952     int i, compno, numcomps, w, h;
2953     OPJ_COLOR_SPACE color_space;
2954     opj_image_cmptparm_t *cmptparm;
2955     opj_image_t * image = NULL;
2956     unsigned short ch;
2957
2958     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2959     {
2960         fprintf(stderr,"\nError: invalid raw image parameters\n");
2961         fprintf(stderr,"Please use the Format option -F:\n");
2962         fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2963         fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2964         fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2965         fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
2966         fprintf(stderr,"Aborting.\n");
2967         return NULL;
2968     }
2969
2970     f = fopen(filename, "rb");
2971     if (!f) {
2972         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2973         fprintf(stderr,"Aborting\n");
2974         return NULL;
2975     }
2976     numcomps = raw_cp->rawComp;
2977
2978     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2979     if (numcomps == 0) {
2980         color_space = OPJ_CLRSPC_GRAY;
2981     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2982         color_space = OPJ_CLRSPC_SYCC;
2983     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2984         color_space = OPJ_CLRSPC_SRGB;
2985     } else {
2986         color_space = OPJ_CLRSPC_UNKNOWN;
2987     }
2988     w = raw_cp->rawWidth;
2989     h = raw_cp->rawHeight;
2990     cmptparm = (opj_image_cmptparm_t*) malloc((size_t)numcomps * sizeof(opj_image_cmptparm_t));
2991
2992     /* initialize image components */
2993     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
2994     for(i = 0; i < numcomps; i++) {
2995         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2996         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2997         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2998         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2999         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
3000         cmptparm[i].w = (OPJ_UINT32)w;
3001         cmptparm[i].h = (OPJ_UINT32)h;
3002     }
3003     /* create the image */
3004     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
3005     free(cmptparm);
3006     if(!image) {
3007         fclose(f);
3008         return NULL;
3009     }
3010     /* set image offset and reference grid */
3011     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
3012     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
3013     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
3014     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
3015
3016     if(raw_cp->rawBitDepth <= 8)
3017     {
3018         unsigned char value = 0;
3019         for(compno = 0; compno < numcomps; compno++) {
3020             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
3021             for (i = 0; i < nloop; i++) {
3022                 if (!fread(&value, 1, 1, f)) {
3023                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
3024                     return NULL;
3025                 }
3026                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
3027             }
3028         }
3029     }
3030     else if(raw_cp->rawBitDepth <= 16)
3031     {
3032         unsigned short value;
3033         for(compno = 0; compno < numcomps; compno++) {
3034             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
3035             for (i = 0; i < nloop; i++) {
3036                 unsigned char temp1;
3037                 unsigned char temp2;
3038                 if (!fread(&temp1, 1, 1, f)) {
3039                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
3040                     return NULL;
3041                 }
3042                 if (!fread(&temp2, 1, 1, f)) {
3043                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
3044                     return NULL;
3045                 }
3046                 if( big_endian )
3047                 {
3048                     value = (unsigned short)((temp1 << 8) + temp2);
3049                 }
3050                 else
3051                 {
3052                     value = (unsigned short)((temp2 << 8) + temp1);
3053                 }
3054                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
3055             }
3056         }
3057     }
3058     else {
3059         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
3060         return NULL;
3061     }
3062
3063     if (fread(&ch, 1, 1, f)) {
3064         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
3065     }
3066     fclose(f);
3067
3068     return image;
3069 }
3070
3071 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
3072     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
3073 }
3074
3075 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
3076     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
3077 }
3078
3079 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
3080 {
3081     FILE *rawFile = NULL;
3082     size_t res;
3083     unsigned int compno;
3084     int w, h, fails;
3085     int line, row, curr, mask;
3086     int *ptr;
3087     unsigned char uc;
3088     (void)big_endian;
3089
3090     if((image->numcomps * image->x1 * image->y1) == 0)
3091     {
3092         fprintf(stderr,"\nError: invalid raw image parameters\n");
3093         return 1;
3094     }
3095
3096     rawFile = fopen(outfile, "wb");
3097     if (!rawFile) {
3098         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
3099         return 1;
3100     }
3101
3102     fails = 1;
3103     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
3104
3105     for(compno = 0; compno < image->numcomps; compno++)
3106     {
3107         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
3108                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
3109
3110         w = (int)image->comps[compno].w;
3111         h = (int)image->comps[compno].h;
3112
3113         if(image->comps[compno].prec <= 8)
3114         {
3115             if(image->comps[compno].sgnd == 1)
3116             {
3117                 mask = (1 << image->comps[compno].prec) - 1;
3118                 ptr = image->comps[compno].data;
3119                 for (line = 0; line < h; line++) {
3120                     for(row = 0; row < w; row++)        {
3121                         curr = *ptr;
3122                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
3123                         uc = (unsigned char) (curr & mask);
3124                         res = fwrite(&uc, 1, 1, rawFile);
3125                         if( res < 1 ) {
3126                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
3127                             goto fin;
3128                         }
3129                         ptr++;
3130                     }
3131                 }
3132             }
3133             else if(image->comps[compno].sgnd == 0)
3134             {
3135                 mask = (1 << image->comps[compno].prec) - 1;
3136                 ptr = image->comps[compno].data;
3137                 for (line = 0; line < h; line++) {
3138                     for(row = 0; row < w; row++)        {
3139                         curr = *ptr;
3140                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
3141                         uc = (unsigned char) (curr & mask);
3142                         res = fwrite(&uc, 1, 1, rawFile);
3143                         if( res < 1 ) {
3144                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
3145                             goto fin;
3146                         }
3147                         ptr++;
3148                     }
3149                 }
3150             }
3151         }
3152         else if(image->comps[compno].prec <= 16)
3153         {
3154             if(image->comps[compno].sgnd == 1)
3155             {
3156                 union { signed short val; signed char vals[2]; } uc16;
3157                 mask = (1 << image->comps[compno].prec) - 1;
3158                 ptr = image->comps[compno].data;
3159                 for (line = 0; line < h; line++) {
3160                     for(row = 0; row < w; row++)        {
3161                         curr = *ptr;
3162                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
3163                         uc16.val = (signed short)(curr & mask);
3164                         res = fwrite(uc16.vals, 1, 2, rawFile);
3165                         if( res < 2 ) {
3166                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
3167                             goto fin;
3168                         }
3169                         ptr++;
3170                     }
3171                 }
3172             }
3173             else if(image->comps[compno].sgnd == 0)
3174             {
3175                 union { unsigned short val; unsigned char vals[2]; } uc16;
3176                 mask = (1 << image->comps[compno].prec) - 1;
3177                 ptr = image->comps[compno].data;
3178                 for (line = 0; line < h; line++) {
3179                     for(row = 0; row < w; row++)        {
3180                         curr = *ptr;
3181                         if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
3182                         uc16.val = (unsigned short)(curr & mask);
3183                         res = fwrite(uc16.vals, 1, 2, rawFile);
3184                         if( res < 2 ) {
3185                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
3186                             goto fin;
3187                         }
3188                         ptr++;
3189                     }
3190                 }
3191             }
3192         }
3193         else if (image->comps[compno].prec <= 32)
3194         {
3195             fprintf(stderr,"More than 16 bits per component no handled yet\n");
3196             goto fin;
3197         }
3198         else
3199         {
3200             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
3201             goto fin;
3202         }
3203     }
3204   fails = 0;
3205 fin:
3206     fclose(rawFile);
3207     return fails;
3208 }
3209
3210 int imagetoraw(opj_image_t * image, const char *outfile)
3211 {
3212     return imagetoraw_common(image, outfile, OPJ_TRUE);
3213 }
3214
3215 int imagetorawl(opj_image_t * image, const char *outfile)
3216 {
3217     return imagetoraw_common(image, outfile, OPJ_FALSE);
3218 }
3219
3220 #ifdef OPJ_HAVE_LIBPNG
3221
3222 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
3223 #define MAGIC_SIZE 8
3224 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
3225
3226 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
3227 {
3228     png_structp  png;
3229     png_infop    info;
3230     double gamma, display_exponent;
3231     int bit_depth, interlace_type,compression_type, filter_type;
3232     int unit;
3233     png_uint_32 resx, resy;
3234     unsigned int i, j;
3235     png_uint_32  width, height;
3236     int color_type, has_alpha, is16;
3237     unsigned char *s;
3238     FILE *reader;
3239     unsigned char **rows;
3240     /* j2k: */
3241     opj_image_t *image;
3242     opj_image_cmptparm_t cmptparm[4];
3243     int sub_dx, sub_dy;
3244     unsigned int nr_comp;
3245     int *r, *g, *b, *a = NULL;
3246     unsigned char sigbuf[8];
3247
3248     if((reader = fopen(read_idf, "rb")) == NULL)
3249     {
3250         fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
3251         return NULL;
3252     }
3253     image = NULL; png = NULL; rows = NULL;
3254
3255     if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
3256             || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
3257     {
3258         fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
3259         goto fin;
3260     }
3261     /* libpng-VERSION/example.c:
3262  * PC : screen_gamma = 2.2;
3263  * Mac: screen_gamma = 1.7 or 1.0;
3264 */
3265     display_exponent = 2.2;
3266
3267     if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
3268                                      NULL, NULL, NULL)) == NULL)
3269         goto fin;
3270     if((info = png_create_info_struct(png)) == NULL)
3271         goto fin;
3272
3273     if(setjmp(png_jmpbuf(png)))
3274         goto fin;
3275
3276     png_init_io(png, reader);
3277     png_set_sig_bytes(png, MAGIC_SIZE);
3278
3279     png_read_info(png, info);
3280
3281     if(png_get_IHDR(png, info, &width, &height,
3282                     &bit_depth, &color_type, &interlace_type,
3283                     &compression_type, &filter_type) == 0)
3284         goto fin;
3285
3286     /* png_set_expand():
3287  * expand paletted images to RGB, expand grayscale images of
3288  * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
3289  * to alpha channels.
3290 */
3291     if(color_type == PNG_COLOR_TYPE_PALETTE)
3292         png_set_expand(png);
3293     else
3294         if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
3295             png_set_expand(png);
3296
3297     if(png_get_valid(png, info, PNG_INFO_tRNS))
3298         png_set_expand(png);
3299
3300     is16 = (bit_depth == 16);
3301
3302     /* GRAY => RGB; GRAY_ALPHA => RGBA
3303 */
3304     if(color_type == PNG_COLOR_TYPE_GRAY
3305             || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
3306     {
3307         png_set_gray_to_rgb(png);
3308         color_type =
3309                 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
3310                                                     PNG_COLOR_TYPE_RGB_ALPHA);
3311     }
3312     if( !png_get_gAMA(png, info, &gamma))
3313         gamma = 0.45455;
3314
3315     png_set_gamma(png, display_exponent, gamma);
3316
3317     png_read_update_info(png, info);
3318
3319     png_get_pHYs(png, info, &resx, &resy, &unit);
3320
3321     color_type = png_get_color_type(png, info);
3322
3323     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
3324
3325     nr_comp = 3 + (unsigned int)has_alpha;
3326
3327     bit_depth = png_get_bit_depth(png, info);
3328
3329     rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
3330     for(i = 0; i < height; ++i)
3331         rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
3332
3333     png_read_image(png, rows);
3334
3335     memset(cmptparm, 0, sizeof(cmptparm));
3336
3337     sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
3338
3339     for(i = 0; i < nr_comp; ++i)
3340     {
3341         cmptparm[i].prec = (OPJ_UINT32)bit_depth;
3342         /* bits_per_pixel: 8 or 16 */
3343         cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
3344         cmptparm[i].sgnd = 0;
3345         cmptparm[i].dx = (OPJ_UINT32)sub_dx;
3346         cmptparm[i].dy = (OPJ_UINT32)sub_dy;
3347         cmptparm[i].w = (OPJ_UINT32)width;
3348         cmptparm[i].h = (OPJ_UINT32)height;
3349     }
3350
3351     image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
3352
3353     if(image == NULL) goto fin;
3354
3355     image->x0 = (OPJ_UINT32)params->image_offset_x0;
3356     image->y0 = (OPJ_UINT32)params->image_offset_y0;
3357     image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
3358     image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
3359
3360     r = image->comps[0].data;
3361     g = image->comps[1].data;
3362     b = image->comps[2].data;
3363     if(has_alpha) a = image->comps[3].data;
3364
3365     for(i = 0; i < height; ++i)
3366     {
3367         s = rows[i];
3368
3369         for(j = 0; j < width; ++j)
3370         {
3371             if(is16)
3372             {
3373                 *r++ = s[0]<<8|s[1]; s += 2;
3374
3375                 *g++ = s[0]<<8|s[1]; s += 2;
3376
3377                 *b++ = s[0]<<8|s[1]; s += 2;
3378
3379                 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
3380
3381                 continue;
3382             }
3383             *r++ = *s++; *g++ = *s++; *b++ = *s++;
3384
3385             if(has_alpha) *a++ = *s++;
3386         }
3387     }
3388 fin:
3389     if(rows)
3390     {
3391         for(i = 0; i < height; ++i)
3392             free(rows[i]);
3393         free(rows);
3394     }
3395     if(png)
3396         png_destroy_read_struct(&png, &info, NULL);
3397
3398     fclose(reader);
3399
3400     return image;
3401
3402 }/* pngtoimage() */
3403
3404 int imagetopng(opj_image_t * image, const char *write_idf)
3405 {
3406     FILE *writer;
3407     png_structp png;
3408     png_infop info;
3409     int *red, *green, *blue, *alpha;
3410     unsigned char *row_buf, *d;
3411     int has_alpha, width, height, nr_comp, color_type;
3412     int adjustR, adjustG, adjustB, adjustA, x, y, fails;
3413     int prec, ushift, dshift, is16, force16, force8;
3414     unsigned short mask = 0xffff;
3415     png_color_8 sig_bit;
3416
3417     is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
3418     prec = (int)image->comps[0].prec;
3419     nr_comp = (int)image->numcomps;
3420
3421     if(prec > 8 && prec < 16)
3422     {
3423         ushift = 16 - prec; dshift = prec - ushift;
3424         prec = 16; force16 = 1;
3425     }
3426     else
3427         if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
3428         {
3429             ushift = 8 - prec; dshift = 8 - ushift;
3430             prec = 8; force8 = 1;
3431         }
3432
3433     if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
3434     {
3435         fprintf(stderr,"imagetopng: can not create %s"
3436                 "\n\twrong bit_depth %d\n", write_idf, prec);
3437         return fails;
3438     }
3439     writer = fopen(write_idf, "wb");
3440
3441     if(writer == NULL) return fails;
3442
3443     info = NULL; has_alpha = 0;
3444
3445     /* Create and initialize the png_struct with the desired error handler
3446  * functions.  If you want to use the default stderr and longjump method,
3447  * you can supply NULL for the last three parameters.  We also check that
3448  * the library version is compatible with the one used at compile time,
3449  * in case we are using dynamically linked libraries.  REQUIRED.
3450 */
3451     png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
3452                                   NULL, NULL, NULL);
3453     /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
3454
3455     if(png == NULL) goto fin;
3456
3457     /* Allocate/initialize the image information data.  REQUIRED
3458 */
3459     info = png_create_info_struct(png);
3460
3461     if(info == NULL) goto fin;
3462
3463     /* Set error handling.  REQUIRED if you are not supplying your own
3464  * error handling functions in the png_create_write_struct() call.
3465 */
3466     if(setjmp(png_jmpbuf(png))) goto fin;
3467
3468     /* I/O initialization functions is REQUIRED
3469 */
3470     png_init_io(png, writer);
3471
3472     /* Set the image information here.  Width and height are up to 2^31,
3473  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
3474  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
3475  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
3476  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
3477  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
3478  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
3479  * REQUIRED
3480  *
3481  * ERRORS:
3482  *
3483  * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
3484  * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
3485  * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
3486  * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
3487  *
3488 */
3489     png_set_compression_level(png, Z_BEST_COMPRESSION);
3490
3491     if(prec == 16) mask = 0xffff;
3492     else
3493         if(prec == 8) mask = 0x00ff;
3494         else
3495             if(prec == 4) mask = 0x000f;
3496             else
3497                 if(prec == 2) mask = 0x0003;
3498                 else
3499                     if(prec == 1) mask = 0x0001;
3500
3501     if(nr_comp >= 3
3502             && image->comps[0].dx == image->comps[1].dx
3503             && image->comps[1].dx == image->comps[2].dx
3504             && image->comps[0].dy == image->comps[1].dy
3505             && image->comps[1].dy == image->comps[2].dy
3506             && image->comps[0].prec == image->comps[1].prec
3507             && image->comps[1].prec == image->comps[2].prec)
3508     {
3509         int v;
3510
3511         has_alpha = (nr_comp > 3);
3512
3513         is16 = (prec == 16);
3514
3515         width = (int)image->comps[0].w;
3516         height = (int)image->comps[0].h;
3517
3518         red = image->comps[0].data;
3519         green = image->comps[1].data;
3520         blue = image->comps[2].data;
3521
3522         sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
3523
3524         if(has_alpha)
3525         {
3526             sig_bit.alpha = (png_byte)prec;
3527             alpha = image->comps[3].data;
3528             color_type = PNG_COLOR_TYPE_RGB_ALPHA;
3529             adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
3530         }
3531         else
3532         {
3533             sig_bit.alpha = 0; alpha = NULL;
3534             color_type = PNG_COLOR_TYPE_RGB;
3535             adjustA = 0;
3536         }
3537         png_set_sBIT(png, info, &sig_bit);
3538
3539         png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
3540                      color_type,
3541                      PNG_INTERLACE_NONE,
3542                      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3543
3544         png_set_gamma(png, 2.2, 1./2.2);
3545         png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3546         /*=============================*/
3547         png_write_info(png, info);
3548         /*=============================*/
3549         if(prec < 8)
3550         {
3551             png_set_packing(png);
3552         }
3553 printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
3554 image->comps[0].sgnd,
3555 image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
3556
3557         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3558         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3559         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
3560
3561         row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
3562
3563         for(y = 0; y < height; ++y)
3564         {
3565             d = row_buf;
3566
3567             for(x = 0; x < width; ++x)
3568             {
3569                 if(is16)
3570                 {
3571                     v = *red + adjustR; ++red;
3572                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3573
3574                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3575
3576                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3577
3578                     v = *green + adjustG; ++green;
3579                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3580
3581                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3582
3583                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3584
3585                     v =  *blue + adjustB; ++blue;
3586                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3587
3588                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3589
3590                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3591
3592                     if(has_alpha)
3593                     {
3594                         v = *alpha + adjustA; ++alpha;
3595                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3596
3597                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3598
3599                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3600                     }
3601                     continue;
3602                 }/* if(is16) */
3603
3604                 v = *red + adjustR; ++red;
3605                 if(v > 255) v = 255; else if(v < 0) v = 0;
3606
3607                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3608
3609                 *d++ = (unsigned char)(v & mask);
3610
3611                 v = *green + adjustG; ++green;
3612                 if(v > 255) v = 255; else if(v < 0) v = 0;
3613
3614                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3615
3616                 *d++ = (unsigned char)(v & mask);
3617
3618                 v = *blue + adjustB; ++blue;
3619                 if(v > 255) v = 255; else if(v < 0) v = 0;
3620
3621                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3622
3623                 *d++ = (unsigned char)(v & mask);
3624
3625                 if(has_alpha)
3626                 {
3627                     v = *alpha + adjustA; ++alpha;
3628                 if(v > 255) v = 255; else if(v < 0) v = 0;
3629
3630                     if(force8) { v = (v<<ushift) + (v>>dshift); }
3631
3632                     *d++ = (unsigned char)(v & mask);
3633                 }
3634             }   /* for(x) */
3635
3636             png_write_row(png, row_buf);
3637
3638         }       /* for(y) */
3639         free(row_buf);
3640
3641     }/* nr_comp >= 3 */
3642     else
3643         if(nr_comp == 1 /* GRAY */
3644                 || (   nr_comp == 2 /* GRAY_ALPHA */
3645                        && image->comps[0].dx == image->comps[1].dx
3646                        && image->comps[0].dy == image->comps[1].dy
3647                        && image->comps[0].prec == image->comps[1].prec))
3648         {
3649             int v;
3650
3651             red = image->comps[0].data;
3652
3653             sig_bit.gray = (png_byte)prec;
3654             sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3655             alpha = NULL; adjustA = 0;
3656             color_type = PNG_COLOR_TYPE_GRAY;
3657
3658             if(nr_comp == 2)
3659             {
3660                 has_alpha = 1; sig_bit.alpha = (png_byte)prec;
3661                 alpha = image->comps[1].data;
3662                 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3663                 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3664             }
3665             width = (int)image->comps[0].w;
3666             height = (int)image->comps[0].h;
3667
3668             png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
3669                          color_type,
3670                          PNG_INTERLACE_NONE,
3671                          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3672
3673             png_set_sBIT(png, info, &sig_bit);
3674
3675             png_set_gamma(png, 2.2, 1./2.2);
3676             png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3677             /*=============================*/
3678             png_write_info(png, info);
3679             /*=============================*/
3680             adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3681
3682             if(prec < 8)
3683             {
3684                 png_set_packing(png);
3685             }
3686
3687             if(prec > 8)
3688             {
3689                 row_buf = (unsigned char*)
3690                         malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
3691
3692                 for(y = 0; y < height; ++y)
3693                 {
3694                     d = row_buf;
3695
3696                     for(x = 0; x < width; ++x)
3697                     {
3698                         v = *red + adjustR; ++red;
3699                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3700
3701                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3702
3703                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3704
3705                         if(has_alpha)
3706                         {
3707                             v = *alpha++;
3708                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3709
3710                             if(force16) { v = (v<<ushift) + (v>>dshift); }
3711
3712                             *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3713                         }
3714                     }/* for(x) */
3715                     png_write_row(png, row_buf);
3716
3717                 }       /* for(y) */
3718                 free(row_buf);
3719             }
3720             else /* prec <= 8 */
3721             {
3722                 row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
3723
3724                 for(y = 0; y < height; ++y)
3725                 {
3726                     d = row_buf;
3727
3728                     for(x = 0; x < width; ++x)
3729                     {
3730                         v = *red + adjustR; ++red;
3731                 if(v > 255) v = 255; else if(v < 0) v = 0;
3732
3733                         if(force8) { v = (v<<ushift) + (v>>dshift); }
3734
3735                         *d++ = (unsigned char)(v & mask);
3736
3737                         if(has_alpha)
3738                         {
3739                             v = *alpha + adjustA; ++alpha;
3740                 if(v > 255) v = 255; else if(v < 0) v = 0;
3741
3742                             if(force8) { v = (v<<ushift) + (v>>dshift); }
3743
3744                             *d++ = (unsigned char)(v & mask);
3745                         }
3746                     }/* for(x) */
3747
3748                     png_write_row(png, row_buf);
3749
3750                 }       /* for(y) */
3751                 free(row_buf);
3752             }
3753         }
3754         else
3755         {
3756             fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3757             goto fin;
3758         }
3759     png_write_end(png, info);
3760
3761     fails = 0;
3762
3763 fin:
3764
3765     if(png)
3766     {
3767         png_destroy_write_struct(&png, &info);
3768     }
3769     fclose(writer);
3770
3771     if(fails) remove(write_idf);
3772
3773     return fails;
3774 }/* imagetopng() */
3775 #endif /* OPJ_HAVE_LIBPNG */