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