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