2 * The copyright in this software is being made available under the 2-clauses
3 * BSD License, included below. This software may be subject to other third
4 * party and contributor rights, including patent rights, and no such rights
5 * are granted under this license.
7 * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8 * Copyright (c) 2002-2014, Professor Benoit Macq
9 * Copyright (c) 2001-2003, David Janssens
10 * Copyright (c) 2002-2003, Yannick Verschueren
11 * Copyright (c) 2003-2007, Francois-Olivier Devaux
12 * Copyright (c) 2003-2014, Antonin Descampe
13 * Copyright (c) 2005, Herve Drolon, FreeImage Team
14 * Copyright (c) 2006-2007, Parvatha Elangovan
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
27 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
38 #include "opj_apps_config.h"
45 #ifdef OPJ_HAVE_LIBTIFF
47 #endif /* OPJ_HAVE_LIBTIFF */
49 #ifdef OPJ_HAVE_LIBPNG
52 #endif /* OPJ_HAVE_LIBPNG */
58 * Get logarithm of an integer and round downwards.
62 static int int_floorlog2(int a) {
64 for (l = 0; a > 1; l++) {
70 /* Component precision scaling */
71 void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
75 OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32)-1);
77 len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
79 umax = (1U << precision) - 1U;
82 if (component->sgnd) {
83 OPJ_INT32* l_data = component->data;
84 OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
85 OPJ_INT32 min = -max - 1;
86 for (i = 0; i < len; ++i) {
87 if (l_data[i] > max) {
89 } else if (l_data[i] < min) {
94 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
95 for (i = 0; i < len; ++i) {
96 if (l_data[i] > umax) {
101 component->prec = precision;
104 /* Component precision scaling */
105 static void scale_component_up(opj_image_comp_t* component, OPJ_UINT32 precision)
109 len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
110 if (component->sgnd) {
111 OPJ_INT64 newMax = (1U << (precision - 1));
112 OPJ_INT64 oldMax = (1U << (component->prec - 1));
113 OPJ_INT32* l_data = component->data;
114 for (i = 0; i < len; ++i) {
115 l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
118 OPJ_UINT64 newMax = (1U << precision) - 1U;
119 OPJ_UINT64 oldMax = (1U << component->prec) - 1U;
120 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
121 for (i = 0; i < len; ++i) {
122 l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
125 component->prec = precision;
127 void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
132 if (component->prec == precision) {
135 if (component->prec < precision) {
136 scale_component_up(component, precision);
139 shift = (int)(component->prec - precision);
140 len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
141 if (component->sgnd) {
142 OPJ_INT32* l_data = component->data;
143 for (i = 0; i < len; ++i) {
147 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
148 for (i = 0; i < len; ++i) {
152 component->prec = precision;
156 /* -->> -->> -->> -->>
160 <<-- <<-- <<-- <<-- */
162 #ifdef INFORMATION_ONLY
163 /* TGA header definition. */
166 unsigned char id_length; /* Image id field length */
167 unsigned char colour_map_type; /* Colour map type */
168 unsigned char image_type; /* Image type */
170 ** Colour map specification
172 unsigned short colour_map_index; /* First entry index */
173 unsigned short colour_map_length; /* Colour map length */
174 unsigned char colour_map_entry_size; /* Colour map entry size */
176 ** Image specification
178 unsigned short x_origin; /* x origin of image */
179 unsigned short y_origin; /* u origin of image */
180 unsigned short image_width; /* Image width */
181 unsigned short image_height; /* Image height */
182 unsigned char pixel_depth; /* Pixel depth */
183 unsigned char image_desc; /* Image descriptor */
185 #endif /* INFORMATION_ONLY */
187 static unsigned short get_ushort(unsigned short val) {
189 #ifdef OPJ_BIG_ENDIAN
190 return( ((val & 0xff) << 8) + (val >> 8) );
197 #define TGA_HEADER_SIZE 18
199 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
200 unsigned int *width, unsigned int *height, int *flip_image)
204 unsigned char id_len, /*cmap_type,*/ image_type;
205 unsigned char pixel_depth, image_desc;
206 unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
207 unsigned short /*x_origin, y_origin,*/ image_w, image_h;
209 if (!bits_per_pixel || !width || !height || !flip_image)
211 tga = (unsigned char*)malloc(18);
213 if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
215 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
218 id_len = (unsigned char)tga[0];
219 /*cmap_type = (unsigned char)tga[1];*/
220 image_type = (unsigned char)tga[2];
221 /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
222 cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
223 cmap_entry_size = (unsigned char)tga[7];
227 x_origin = get_ushort(*(unsigned short*)(&tga[8]));
228 y_origin = get_ushort(*(unsigned short*)(&tga[10]));
230 image_w = get_ushort(*(unsigned short*)(&tga[12]));
231 image_h = get_ushort(*(unsigned short*)(&tga[14]));
232 pixel_depth = (unsigned char)tga[16];
233 image_desc = (unsigned char)tga[17];
237 *bits_per_pixel = (unsigned int)pixel_depth;
238 *width = (unsigned int)image_w;
239 *height = (unsigned int)image_h;
241 /* Ignore tga identifier, if present ... */
244 unsigned char *id = (unsigned char *) malloc(id_len);
245 if ( !fread(id, id_len, 1, fp) )
247 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
254 /* Test for compressed formats ... not yet supported ...
255 // Note :- 9 - RLE encoded palettized.
256 // 10 - RLE encoded RGB. */
259 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
263 *flip_image = !(image_desc & 32);
265 /* Palettized formats are not yet supported, skip over the palette, if present ... */
266 palette_size = cmap_len * (cmap_entry_size/8);
270 fprintf(stderr, "File contains a palette - not yet supported.");
271 fseek(fp, palette_size, SEEK_CUR);
276 #ifdef OPJ_BIG_ENDIAN
278 static INLINE int16_t swap16(int16_t x)
280 return((((u_int16_t)x & 0x00ffU) << 8) |
281 (((u_int16_t)x & 0xff00U) >> 8));
286 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
289 unsigned short image_w, image_h, us0;
290 unsigned char uc0, image_type;
291 unsigned char pixel_depth, image_desc;
293 if (!bits_per_pixel || !width || !height)
298 if ( bits_per_pixel < 256 )
299 pixel_depth = (unsigned char)bits_per_pixel;
301 fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
306 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
307 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
309 image_type = 2; /* Uncompressed. */
310 if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
313 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
314 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
315 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
317 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
318 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
320 image_w = (unsigned short)width;
321 image_h = (unsigned short) height;
323 #ifndef OPJ_BIG_ENDIAN
324 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
325 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
327 image_w = swap16(image_w);
328 image_h = swap16(image_h);
329 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
330 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
333 if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
335 image_desc = 8; /* 8 bits per component. */
339 if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
344 fputs("\nwrite_tgaheader: write ERROR\n", stderr);
348 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
351 unsigned int image_width, image_height, pixel_bit_depth;
354 opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
356 OPJ_COLOR_SPACE color_space;
359 int subsampling_dx, subsampling_dy;
362 f = fopen(filename, "rb");
364 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
368 if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
371 /* We currently only support 24 & 32 bit tga's ... */
372 if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
375 /* initialize image components */
376 memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
378 mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16); /* Mono with & without alpha. */
379 save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
382 color_space = OPJ_CLRSPC_GRAY;
383 numcomps = save_alpha ? 2 : 1;
386 numcomps = save_alpha ? 4 : 3;
387 color_space = OPJ_CLRSPC_SRGB;
390 subsampling_dx = parameters->subsampling_dx;
391 subsampling_dy = parameters->subsampling_dy;
393 for (i = 0; i < numcomps; i++) {
394 cmptparm[i].prec = 8;
396 cmptparm[i].sgnd = 0;
397 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
398 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
399 cmptparm[i].w = image_width;
400 cmptparm[i].h = image_height;
403 /* create the image */
404 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
409 /* set image offset and reference grid */
410 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
411 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
412 image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1;
413 image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1;
416 for (y=0; y < image_height; y++)
421 index = (int)((image_height-y-1)*image_width);
423 index = (int)(y*image_width);
427 for (x=0;x<image_width;x++)
431 if( !fread(&b, 1, 1, f) )
433 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
434 opj_image_destroy(image);
437 if ( !fread(&g, 1, 1, f) )
439 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
440 opj_image_destroy(image);
443 if ( !fread(&r, 1, 1, f) )
445 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
446 opj_image_destroy(image);
450 image->comps[0].data[index]=r;
451 image->comps[1].data[index]=g;
452 image->comps[2].data[index]=b;
456 else if (numcomps==4)
458 for (x=0;x<image_width;x++)
460 unsigned char r,g,b,a;
461 if ( !fread(&b, 1, 1, f) )
463 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
464 opj_image_destroy(image);
467 if ( !fread(&g, 1, 1, f) )
469 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
470 opj_image_destroy(image);
473 if ( !fread(&r, 1, 1, f) )
475 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
476 opj_image_destroy(image);
479 if ( !fread(&a, 1, 1, f) )
481 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
482 opj_image_destroy(image);
486 image->comps[0].data[index]=r;
487 image->comps[1].data[index]=g;
488 image->comps[2].data[index]=b;
489 image->comps[3].data[index]=a;
494 fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
500 int imagetotga(opj_image_t * image, const char *outfile) {
501 int width, height, bpp, x, y;
502 OPJ_BOOL write_alpha;
504 int adjustR, adjustG, adjustB, fails;
505 unsigned int alpha_channel;
513 fdest = fopen(outfile, "wb");
515 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
519 for (i = 0; i < image->numcomps-1; i++) {
520 if ((image->comps[0].dx != image->comps[i+1].dx)
521 ||(image->comps[0].dy != image->comps[i+1].dy)
522 ||(image->comps[0].prec != image->comps[i+1].prec)) {
523 fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
528 width = (int)image->comps[0].w;
529 height = (int)image->comps[0].h;
531 /* Mono with alpha, or RGB with alpha. */
532 write_alpha = (image->numcomps==2) || (image->numcomps==4);
534 /* Write TGA header */
535 bpp = write_alpha ? 32 : 24;
537 if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
540 alpha_channel = image->numcomps-1;
542 scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
544 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
545 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
546 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
548 for (y=0; y < height; y++)
550 unsigned int index= (unsigned int)(y*width);
552 for (x=0; x < width; x++, index++)
554 r = (float)(image->comps[0].data[index] + adjustR);
556 if (image->numcomps > 2)
558 g = (float)(image->comps[1].data[index] + adjustG);
559 b = (float)(image->comps[2].data[index] + adjustB);
567 /* TGA format writes BGR ... */
568 if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
569 value = (unsigned char)(b*scale);
570 res = fwrite(&value,1,1,fdest);
574 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
577 if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
578 value = (unsigned char)(g*scale);
579 res = fwrite(&value,1,1,fdest);
583 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
586 if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
587 value = (unsigned char)(r*scale);
588 res = fwrite(&value,1,1,fdest);
592 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
598 a = (float)(image->comps[alpha_channel].data[index]);
599 if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
600 value = (unsigned char)(a*scale);
601 res = fwrite(&value,1,1,fdest);
605 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
618 /* -->> -->> -->> -->>
622 <<-- <<-- <<-- <<-- */
625 static unsigned char readuchar(FILE * f)
628 if ( !fread(&c1, 1, 1, f) )
630 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
636 static unsigned short readushort(FILE * f, int bigendian)
638 unsigned char c1, c2;
639 if ( !fread(&c1, 1, 1, f) )
641 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
644 if ( !fread(&c2, 1, 1, f) )
646 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
650 return (unsigned short)((c1 << 8) + c2);
652 return (unsigned short)((c2 << 8) + c1);
655 static unsigned int readuint(FILE * f, int bigendian)
657 unsigned char c1, c2, c3, c4;
658 if ( !fread(&c1, 1, 1, f) )
660 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
663 if ( !fread(&c2, 1, 1, f) )
665 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
668 if ( !fread(&c3, 1, 1, f) )
670 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
673 if ( !fread(&c4, 1, 1, f) )
675 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
679 return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
681 return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
684 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
687 int i, numcomps, max;
688 OPJ_COLOR_SPACE color_space;
689 opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
690 opj_image_t * image = NULL;
691 int adjustS, ushift, dshift, force8;
693 char endian1,endian2,sign;
698 opj_image_comp_t *comp = NULL;
701 color_space = OPJ_CLRSPC_GRAY;
703 memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
707 f = fopen(filename, "rb");
709 fprintf(stderr, "Failed to open %s for reading !\n", filename);
713 fseek(f, 0, SEEK_SET);
714 if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
715 fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
721 while (signtmp[i]!='\0') {
722 if (signtmp[i]=='-') sign='-';
727 if (endian1=='M' && endian2=='L') {
729 } else if (endian2=='M' && endian1=='L') {
732 fprintf(stderr, "Bad pgx header, please check input file\n");
736 /* initialize image component */
738 cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
739 cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
740 cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
741 cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
751 ushift = 8 - prec; dshift = prec - ushift;
752 if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
756 else ushift = dshift = force8 = adjustS = 0;
758 cmptparm.prec = (OPJ_UINT32)prec;
759 cmptparm.bpp = (OPJ_UINT32)prec;
760 cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
761 cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
763 /* create the image */
764 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
769 /* set image offset and reference grid */
770 image->x0 = cmptparm.x0;
771 image->y0 = cmptparm.x0;
772 image->x1 = cmptparm.w;
773 image->y1 = cmptparm.h;
777 comp = &image->comps[0];
779 for (i = 0; i < w * h; i++) {
783 v = readuchar(f) + adjustS;
784 v = (v<<ushift) + (v>>dshift);
785 comp->data[i] = (unsigned char)v;
791 if (comp->prec == 8) {
795 v = (char) readuchar(f);
797 } else if (comp->prec <= 16) {
799 v = readushort(f, bigendian);
801 v = (short) readushort(f, bigendian);
805 v = (int)readuint(f, bigendian);
807 v = (int) readuint(f, bigendian);
815 comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
820 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
822 static INLINE int clamp( const int value, const int prec, const int sgnd )
826 if (prec <= 8) return CLAMP(value,-128,127);
827 else if (prec <= 16) return CLAMP(value,-32768,32767);
828 else return CLAMP(value,-2147483647-1,2147483647);
832 if (prec <= 8) return CLAMP(value,0,255);
833 else if (prec <= 16) return CLAMP(value,0,65535);
834 else return value; /*CLAMP(value,0,4294967295);*/
838 int imagetopgx(opj_image_t * image, const char *outfile)
845 for (compno = 0; compno < image->numcomps; compno++)
847 opj_image_comp_t *comp = &image->comps[compno];
848 char bname[256]; /* buffer for name */
849 char *name = bname; /* pointer */
852 const size_t olen = strlen(outfile);
853 const size_t dotpos = olen - 4;
854 const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
856 if( outfile[dotpos] != '.' )
858 /* `pgx` was recognized but there is no dot at expected position */
859 fprintf(stderr, "ERROR -> Impossible happen." );
864 name = (char*)malloc(total+1);
866 strncpy(name, outfile, dotpos);
867 sprintf(name+dotpos, "_%d.pgx", compno);
868 fdest = fopen(name, "wb");
869 /* dont need name anymore */
870 if( total > 256 ) free(name);
873 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
877 w = (int)image->comps[compno].w;
878 h = (int)image->comps[compno].h;
880 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
885 else if (comp->prec <= 16)
890 for (i = 0; i < w * h; i++)
892 /* FIXME: clamp func is being called within a loop */
893 const int val = clamp(image->comps[compno].data[i],
894 (int)comp->prec, (int)comp->sgnd);
896 for (j = nbytes - 1; j >= 0; j--)
898 int v = (int)(val >> (j * 8));
899 unsigned char byte = (unsigned char)v;
900 res = fwrite(&byte, 1, 1, fdest);
904 fprintf(stderr, "failed to write 1 byte for %s\n", name);
909 fclose(fdest); fdest = NULL;
913 if(fdest) fclose(fdest);
918 /* -->> -->> -->> -->>
922 <<-- <<-- <<-- <<-- */
926 int width, height, maxval, depth, format;
927 char rgb, rgba, gray, graya, bw;
931 static char *skip_white(char *s)
935 if(*s == '\n' || *s == '\r') return NULL;
936 if(isspace(*s)) { ++s; continue; }
942 static char *skip_int(char *start, int *out_n)
947 *out_n = 0; s = start;
949 s = skip_white(start);
950 if(s == NULL) return NULL;
955 if( !isdigit(*s)) break;
958 c = *s; *s = 0; *out_n = atoi(start); *s = c;
962 static char *skip_idf(char *start, char out_idf[256])
967 s = skip_white(start);
968 if(s == NULL) return NULL;
973 if(isalpha(*s) || *s == '_') { ++s; continue; }
976 c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
980 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
982 int format, have_wh, end, ttype;
983 char idf[256], type[256];
986 if (fgets(line, 250, reader) == NULL)
988 fprintf(stderr,"\nWARNING: fgets return a NULL value");
994 fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
996 format = atoi(line + 1);
997 if(format < 1 || format > 7)
999 fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1002 ph->format = format;
1003 ttype = end = have_wh = 0;
1005 while(fgets(line, 250, reader))
1009 if(*line == '#') continue;
1015 s = skip_idf(s, idf);
1017 if(s == NULL || *s == 0) return;
1019 if(strcmp(idf, "ENDHDR") == 0)
1023 if(strcmp(idf, "WIDTH") == 0)
1025 s = skip_int(s, &ph->width);
1026 if(s == NULL || *s == 0) return;
1030 if(strcmp(idf, "HEIGHT") == 0)
1032 s = skip_int(s, &ph->height);
1033 if(s == NULL || *s == 0) return;
1037 if(strcmp(idf, "DEPTH") == 0)
1039 s = skip_int(s, &ph->depth);
1040 if(s == NULL || *s == 0) return;
1044 if(strcmp(idf, "MAXVAL") == 0)
1046 s = skip_int(s, &ph->maxval);
1047 if(s == NULL || *s == 0) return;
1051 if(strcmp(idf, "TUPLTYPE") == 0)
1053 s = skip_idf(s, type);
1054 if(s == NULL || *s == 0) return;
1056 if(strcmp(type, "BLACKANDWHITE") == 0)
1058 ph->bw = 1; ttype = 1; continue;
1060 if(strcmp(type, "GRAYSCALE") == 0)
1062 ph->gray = 1; ttype = 1; continue;
1064 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1066 ph->graya = 1; ttype = 1; continue;
1068 if(strcmp(type, "RGB") == 0)
1070 ph->rgb = 1; ttype = 1; continue;
1072 if(strcmp(type, "RGB_ALPHA") == 0)
1074 ph->rgba = 1; ttype = 1; continue;
1076 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1079 fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1081 } /* if(format == 7) */
1085 s = skip_int(s, &ph->width);
1087 s = skip_int(s, &ph->height);
1091 if(format == 1 || format == 4) break;
1093 if(format == 2 || format == 3 || format == 5 || format == 6)
1095 if (skip_int(s, &ph->maxval) != NULL) {
1096 if(ph->maxval > 65535) {
1106 if(format == 2 || format == 3 || format == 5 || format == 6)
1108 /* P2, P3, P5, P6: */
1109 s = skip_int(s, &ph->maxval);
1111 if(ph->maxval > 65535) return;
1114 }/* while(fgets( ) */
1115 if(format == 2 || format == 3 || format > 4)
1117 if(ph->maxval < 1 || ph->maxval > 65535) return;
1119 if(ph->width < 1 || ph->height < 1) return;
1125 fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1127 if(ph->depth < 1 || ph->depth > 4) return;
1129 if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1134 if(format != 1 && format != 4)
1136 if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1140 if(ph->width && ph->height) ph->ok = 1;
1146 static int has_prec(int val)
1148 if(val < 2) return 1;
1149 if(val < 4) return 2;
1150 if(val < 8) return 3;
1151 if(val < 16) return 4;
1152 if(val < 32) return 5;
1153 if(val < 64) return 6;
1154 if(val < 128) return 7;
1155 if(val < 256) return 8;
1156 if(val < 512) return 9;
1157 if(val < 1024) return 10;
1158 if(val < 2048) return 11;
1159 if(val < 4096) return 12;
1160 if(val < 8192) return 13;
1161 if(val < 16384) return 14;
1162 if(val < 32768) return 15;
1166 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1167 int subsampling_dx = parameters->subsampling_dx;
1168 int subsampling_dy = parameters->subsampling_dy;
1171 int i, compno, numcomps, w, h, prec, format;
1172 OPJ_COLOR_SPACE color_space;
1173 opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1174 opj_image_t * image = NULL;
1175 struct pnm_header header_info;
1177 if((fp = fopen(filename, "rb")) == NULL)
1179 fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1182 memset(&header_info, 0, sizeof(struct pnm_header));
1184 read_pnm_header(fp, &header_info);
1186 if(!header_info.ok) { fclose(fp); return NULL; }
1188 format = header_info.format;
1192 case 1: /* ascii bitmap */
1193 case 4: /* raw bitmap */
1197 case 2: /* ascii greymap */
1198 case 5: /* raw greymap */
1202 case 3: /* ascii pixmap */
1203 case 6: /* raw pixmap */
1207 case 7: /* arbitrary map */
1208 numcomps = header_info.depth;
1211 default: fclose(fp); return NULL;
1214 color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1216 color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1218 prec = has_prec(header_info.maxval);
1220 if(prec < 8) prec = 8;
1222 w = header_info.width;
1223 h = header_info.height;
1224 subsampling_dx = parameters->subsampling_dx;
1225 subsampling_dy = parameters->subsampling_dy;
1227 memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1229 for(i = 0; i < numcomps; i++)
1231 cmptparm[i].prec = (OPJ_UINT32)prec;
1232 cmptparm[i].bpp = (OPJ_UINT32)prec;
1233 cmptparm[i].sgnd = 0;
1234 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1235 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1236 cmptparm[i].w = (OPJ_UINT32)w;
1237 cmptparm[i].h = (OPJ_UINT32)h;
1239 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1241 if(!image) { fclose(fp); return NULL; }
1243 /* set image offset and reference grid */
1244 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1245 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1246 image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1247 image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1249 if((format == 2) || (format == 3)) /* ascii pixmap */
1253 for (i = 0; i < w * h; i++)
1255 for(compno = 0; compno < numcomps; compno++)
1258 if (fscanf(fp, "%u", &index) != 1)
1259 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1261 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1269 && ( header_info.gray || header_info.graya
1270 || header_info.rgb || header_info.rgba)))/* binary pixmap */
1272 unsigned char c0, c1, one;
1276 for (i = 0; i < w * h; i++)
1278 for(compno = 0; compno < numcomps; compno++)
1280 if ( !fread(&c0, 1, 1, fp) )
1282 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1283 opj_image_destroy(image);
1288 image->comps[compno].data[i] = c0;
1292 if ( !fread(&c1, 1, 1, fp) )
1293 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1295 image->comps[compno].data[i] = ((c0<<8) | c1);
1301 if(format == 1) /* ascii bitmap */
1303 for (i = 0; i < w * h; i++)
1307 if ( fscanf(fp, "%u", &index) != 1)
1308 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1310 image->comps[0].data[i] = (index?0:255);
1320 for(y = 0; y < h; ++y)
1324 for(x = 0; x < w; ++x)
1329 uc = (unsigned char)getc(fp);
1331 image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1337 if((format == 7 && header_info.bw)) /*MONO*/
1341 for(i = 0; i < w * h; ++i)
1343 if ( !fread(&uc, 1, 1, fp) )
1344 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1345 image->comps[0].data[i] = (uc & 1)?0:255;
1353 int imagetopnm(opj_image_t * image, const char *outfile)
1355 int *red, *green, *blue, *alpha;
1358 unsigned int compno, ncomp;
1359 int adjustR, adjustG, adjustB, adjustA;
1360 int fails, two, want_gray, has_alpha, triple;
1363 const char *tmp = outfile;
1368 if((prec = (int)image->comps[0].prec) > 16)
1370 fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1371 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1374 two = has_alpha = 0; fails = 1;
1375 ncomp = image->numcomps;
1377 while (*tmp) ++tmp; tmp -= 2;
1378 want_gray = (*tmp == 'g' || *tmp == 'G');
1379 ncomp = image->numcomps;
1381 if(want_gray) ncomp = 1;
1383 if (ncomp == 2 /* GRAYA */
1384 || (ncomp > 2 /* RGB, RGBA */
1385 && image->comps[0].dx == image->comps[1].dx
1386 && image->comps[1].dx == image->comps[2].dx
1387 && image->comps[0].dy == image->comps[1].dy
1388 && image->comps[1].dy == image->comps[2].dy
1389 && image->comps[0].prec == image->comps[1].prec
1390 && image->comps[1].prec == image->comps[2].prec
1393 fdest = fopen(outfile, "wb");
1397 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1401 triple = (ncomp > 2);
1402 wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1403 max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1405 red = image->comps[0].data;
1409 green = image->comps[1].data;
1410 blue = image->comps[2].data;
1412 else green = blue = NULL;
1416 const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1418 fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1419 "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1420 wr, hr, ncomp, max, tt);
1421 alpha = image->comps[ncomp - 1].data;
1422 adjustA = (image->comps[ncomp - 1].sgnd ?
1423 1 << (image->comps[ncomp - 1].prec - 1) : 0);
1427 fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1428 opj_version(), wr, hr, max);
1431 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1435 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1436 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1438 else adjustG = adjustB = 0;
1440 for(i = 0; i < wr * hr; ++i)
1444 v = *red + adjustR; ++red;
1445 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1448 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1452 v = *green + adjustG; ++green;
1453 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1456 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1458 v = *blue + adjustB; ++blue;
1459 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1462 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1468 v = *alpha + adjustA; ++alpha;
1469 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1472 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1480 if(v > 255) v = 255; else if(v < 0) v = 0;
1482 fprintf(fdest, "%c", (unsigned char)v);
1486 if(v > 255) v = 255; else if(v < 0) v = 0;
1488 fprintf(fdest, "%c", (unsigned char)v);
1490 if(v > 255) v = 255; else if(v < 0) v = 0;
1492 fprintf(fdest, "%c", (unsigned char)v);
1497 if(v > 255) v = 255; else if(v < 0) v = 0;
1499 fprintf(fdest, "%c", (unsigned char)v);
1503 fclose(fdest); return 0;
1508 if (image->numcomps > ncomp)
1510 fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1511 fprintf(stderr," is written to the file\n");
1513 destname = (char*)malloc(strlen(outfile) + 8);
1515 for (compno = 0; compno < ncomp; compno++)
1519 /*sprintf(destname, "%d.%s", compno, outfile);*/
1520 const size_t olen = strlen(outfile);
1521 const size_t dotpos = olen - 4;
1523 strncpy(destname, outfile, dotpos);
1524 sprintf(destname+dotpos, "_%d.pgm", compno);
1527 sprintf(destname, "%s", outfile);
1529 fdest = fopen(destname, "wb");
1532 fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1536 wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1537 prec = (int)image->comps[compno].prec;
1538 max = (1<<prec) - 1;
1540 fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1541 opj_version(), wr, hr, max);
1543 red = image->comps[compno].data;
1545 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1549 for (i = 0; i < wr * hr; i++)
1551 v = *red + adjustR; ++red;
1552 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1555 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1560 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1563 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1567 else /* prec <= 8 */
1569 for(i = 0; i < wr * hr; ++i)
1571 v = *red + adjustR; ++red;
1572 if(v > 255) v = 255; else if(v < 0) v = 0;
1574 fprintf(fdest, "%c", (unsigned char)v);
1584 #ifdef OPJ_HAVE_LIBTIFF
1585 /* -->> -->> -->> -->>
1589 <<-- <<-- <<-- <<-- */
1591 int imagetotif(opj_image_t * image, const char *outfile)
1593 int width, height, imgsize;
1594 int bps,index,adjust, sgnd;
1595 int ushift, dshift, has_alpha, force16;
1601 ushift = dshift = force16 = has_alpha = 0;
1602 bps = (int)image->comps[0].prec;
1604 if(bps > 8 && bps < 16)
1606 ushift = 16 - bps; dshift = bps - ushift;
1607 bps = 16; force16 = 1;
1610 if(bps != 8 && bps != 16)
1612 fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
1614 fprintf(stderr,"\tAborting\n");
1617 tif = TIFFOpen(outfile, "wb");
1621 fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
1624 sgnd = (int)image->comps[0].sgnd;
1625 adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
1627 if(image->numcomps >= 3
1628 && image->comps[0].dx == image->comps[1].dx
1629 && image->comps[1].dx == image->comps[2].dx
1630 && image->comps[0].dy == image->comps[1].dy
1631 && image->comps[1].dy == image->comps[2].dy
1632 && image->comps[0].prec == image->comps[1].prec
1633 && image->comps[1].prec == image->comps[2].prec)
1635 has_alpha = (image->numcomps == 4);
1637 width = (int)image->comps[0].w;
1638 height = (int)image->comps[0].h;
1639 imgsize = width * height ;
1641 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1642 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1643 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
1644 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1645 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1646 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1647 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1648 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1649 strip_size = TIFFStripSize(tif);
1650 buf = _TIFFmalloc(strip_size);
1653 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1655 unsigned char *dat8;
1656 tsize_t i, ssize, last_i = 0;
1658 ssize = TIFFStripSize(tif);
1659 dat8 = (unsigned char*)buf;
1663 step = 3 + has_alpha;
1666 for(i=0; i < ssize - restx; i += step)
1672 r = image->comps[0].data[index];
1673 g = image->comps[1].data[index];
1674 b = image->comps[2].data[index];
1675 if(has_alpha) a = image->comps[3].data[index];
1682 if(has_alpha) a += adjust;
1684 if(r > 255) r = 255; else if(r < 0) r = 0;
1685 dat8[i+0] = (unsigned char)r ;
1686 if(g > 255) g = 255; else if(g < 0) g = 0;
1687 dat8[i+1] = (unsigned char)g ;
1688 if(b > 255) b = 255; else if(b < 0) b = 0;
1689 dat8[i+2] = (unsigned char)b ;
1692 if(a > 255) a = 255; else if(a < 0) a = 0;
1693 dat8[i+3] = (unsigned char)a;
1705 for(i = last_i; i < ssize; i += step)
1711 r = image->comps[0].data[index];
1712 g = image->comps[1].data[index];
1713 b = image->comps[2].data[index];
1714 if(has_alpha) a = image->comps[3].data[index];
1721 if(has_alpha) a += adjust;
1723 if(r > 255) r = 255; else if(r < 0) r = 0;
1724 if(g > 255) g = 255; else if(g < 0) g = 0;
1725 if(b > 255) b = 255; else if(b < 0) b = 0;
1727 dat8[i+0] = (unsigned char)r ;
1728 if(i+1 < ssize) dat8[i+1] = (unsigned char)g ; else break;
1729 if(i+2 < ssize) dat8[i+2] = (unsigned char)b ; else break;
1732 if(a > 255) a = 255; else if(a < 0) a = 0;
1734 if(i+3 < ssize) dat8[i+3] = (unsigned char)a ; else break;
1741 }/*if(last_i < ssize)*/
1747 step = 6 + has_alpha + has_alpha;
1750 for(i = 0; i < ssize - restx ; i += step)
1756 r = image->comps[0].data[index];
1757 g = image->comps[1].data[index];
1758 b = image->comps[2].data[index];
1759 if(has_alpha) a = image->comps[3].data[index];
1766 if(has_alpha) a += adjust;
1770 r = (r<<ushift) + (r>>dshift);
1771 g = (g<<ushift) + (g>>dshift);
1772 b = (b<<ushift) + (b>>dshift);
1773 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1775 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1776 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1777 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1779 dat8[i+0] = (unsigned char)r;/*LSB*/
1780 dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1781 dat8[i+2] = (unsigned char)g;
1782 dat8[i+3] = (unsigned char)(g >> 8);
1783 dat8[i+4] = (unsigned char)b;
1784 dat8[i+5] = (unsigned char)(b >> 8);
1787 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1788 dat8[i+6] = (unsigned char)a;
1789 dat8[i+7] = (unsigned char)(a >> 8);
1800 for(i = last_i ; i < ssize ; i += step)
1806 r = image->comps[0].data[index];
1807 g = image->comps[1].data[index];
1808 b = image->comps[2].data[index];
1809 if(has_alpha) a = image->comps[3].data[index];
1816 if(has_alpha) a += adjust;
1820 r = (r<<ushift) + (r>>dshift);
1821 g = (g<<ushift) + (g>>dshift);
1822 b = (b<<ushift) + (b>>dshift);
1823 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1825 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1826 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1827 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1829 dat8[i+0] = (unsigned char) r;/*LSB*/
1830 if(i+1 < ssize) dat8[i+1] = (unsigned char)(r >> 8);else break;/*MSB*/
1831 if(i+2 < ssize) dat8[i+2] = (unsigned char) g; else break;
1832 if(i+3 < ssize) dat8[i+3] = (unsigned char)(g >> 8);else break;
1833 if(i+4 < ssize) dat8[i+4] = (unsigned char) b; else break;
1834 if(i+5 < ssize) dat8[i+5] = (unsigned char)(b >> 8);else break;
1838 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1839 if(i+6 < ssize) dat8[i+6] = (unsigned char)a; else break;
1840 if(i+7 < ssize) dat8[i+7] = (unsigned char)(a >> 8); else break;
1847 }/*if(last_i < ssize)*/
1850 (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1851 }/*for(strip = 0; )*/
1853 _TIFFfree((void*)buf);
1859 if(image->numcomps == 1 /* GRAY */
1860 || ( image->numcomps == 2 /* GRAY_ALPHA */
1861 && image->comps[0].dx == image->comps[1].dx
1862 && image->comps[0].dy == image->comps[1].dy
1863 && image->comps[0].prec == image->comps[1].prec))
1867 has_alpha = (image->numcomps == 2);
1869 width = (int)image->comps[0].w;
1870 height = (int)image->comps[0].h;
1871 imgsize = width * height;
1874 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1875 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1876 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
1877 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1878 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1879 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1880 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1881 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1883 /* Get a buffer for the data */
1884 strip_size = TIFFStripSize(tif);
1885 buf = _TIFFmalloc(strip_size);
1888 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1890 unsigned char *dat8;
1891 tsize_t i, ssize = TIFFStripSize(tif);
1892 dat8 = (unsigned char*)buf;
1896 step = 1 + has_alpha;
1898 for(i=0; i < ssize; i += step)
1904 r = image->comps[0].data[index];
1905 if(has_alpha) a = image->comps[1].data[index];
1910 if(has_alpha) a += adjust;
1912 if(r > 255) r = 255; else if(r < 0) r = 0;
1913 dat8[i+0] = (unsigned char)r;
1917 if(a > 255) a = 255; else if(a < 0) a = 0;
1918 dat8[i+1] = (unsigned char)a;
1929 step = 2 + has_alpha + has_alpha;
1931 for(i=0; i < ssize; i += step)
1937 r = image->comps[0].data[index];
1938 if(has_alpha) a = image->comps[1].data[index];
1943 if(has_alpha) a += adjust;
1947 r = (r<<ushift) + (r>>dshift);
1948 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1950 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1951 dat8[i+0] = (unsigned char)r;/*LSB*/
1952 dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1955 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1956 dat8[i+2] = (unsigned char)a;
1957 dat8[i+3] = (unsigned char)(a >> 8);
1960 }/*if(index < imgsize)*/
1965 (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1976 fprintf(stderr,"imagetotif: Bad color format.\n"
1977 "\tOnly RGB(A) and GRAY(A) has been implemented\n");
1978 fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
1985 * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
1986 * CINEMA : 12 bit precision
1988 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1990 int subsampling_dx = parameters->subsampling_dx;
1991 int subsampling_dy = parameters->subsampling_dy;
1996 int j, numcomps, w, h,index;
1997 OPJ_COLOR_SPACE color_space;
1998 opj_image_cmptparm_t cmptparm[4]; /* RGBA */
1999 opj_image_t *image = NULL;
2002 unsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;
2003 unsigned int tiWidth, tiHeight;
2004 OPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);
2006 tif = TIFFOpen(filename, "r");
2010 fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2013 tiBps = tiPhoto = tiSf = tiSpp = tiPC = 0;
2014 tiWidth = tiHeight = 0;
2016 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiWidth);
2017 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiHeight);
2018 TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiBps);
2019 TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &tiSf);
2020 TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
2021 TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
2022 TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
2026 if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
2027 if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
2029 if( !tiBps || !tiPhoto)
2032 fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
2033 " implemented\n",tiBps);
2036 fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2037 " and GRAY(A) has been implemented\n",(int) tiPhoto);
2039 fprintf(stderr,"\tAborting\n");
2045 {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2047 uint16 extrasamples;
2049 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2050 &extrasamples, &sampleinfo);
2052 if(extrasamples >= 1)
2054 switch(sampleinfo[0])
2056 case EXTRASAMPLE_UNSPECIFIED:
2057 /* Workaround for some images without correct info about alpha channel
2063 case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2064 case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2069 else /* extrasamples == 0 */
2070 if(tiSpp == 4 || tiSpp == 2) has_alpha = 1;
2073 /* initialize image components
2075 memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2077 if ((tiPhoto == PHOTOMETRIC_RGB) && (is_cinema)) {
2078 fprintf(stdout,"WARNING:\n"
2079 "Input image bitdepth is %d bits\n"
2080 "TIF conversion has automatically rescaled to 12-bits\n"
2081 "to comply with cinema profiles.\n",
2085 if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2087 numcomps = 3 + has_alpha;
2088 color_space = OPJ_CLRSPC_SRGB;
2090 /*#define USETILEMODE*/
2091 for(j = 0; j < numcomps; j++)
2095 cmptparm[j].prec = 12;
2096 cmptparm[j].bpp = 12;
2100 cmptparm[j].prec = tiBps;
2101 cmptparm[j].bpp = tiBps;
2103 cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2104 cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2105 cmptparm[j].w = (OPJ_UINT32)w;
2106 cmptparm[j].h = (OPJ_UINT32)h;
2114 image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2116 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2124 /* set image offset and reference grid
2126 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2127 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2128 image->x1 = !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2129 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2130 image->y1 = !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2131 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2133 buf = _TIFFmalloc(TIFFStripSize(tif));
2135 strip_size=TIFFStripSize(tif);
2137 imgsize = (int)(image->comps[0].w * image->comps[0].h);
2138 /* Read the Image components
2140 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2142 unsigned char *dat8;
2145 ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2146 dat8 = (unsigned char*)buf;
2150 step = 6 + has_alpha + has_alpha;
2152 for(i = 0; i < ssize; i += step)
2156 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2157 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2158 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2160 image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2164 /* Rounding 16 to 12 bits
2166 image->comps[0].data[index] =
2167 (image->comps[0].data[index] + 0x08) >> 4 ;
2168 image->comps[1].data[index] =
2169 (image->comps[1].data[index] + 0x08) >> 4 ;
2170 image->comps[2].data[index] =
2171 (image->comps[2].data[index] + 0x08) >> 4 ;
2173 image->comps[3].data[index] =
2174 (image->comps[3].data[index] + 0x08) >> 4 ;
2181 }/*if(tiBps == 16)*/
2185 step = 3 + has_alpha;
2187 for(i = 0; i < ssize; i += step)
2192 image->comps[0].data[index] = dat8[i+0];/* R */
2193 image->comps[1].data[index] = dat8[i+1];/* G */
2194 image->comps[2].data[index] = dat8[i+2];/* B */
2196 image->comps[3].data[index] = dat8[i+3];
2201 /* Rounding 8 to 12 bits
2204 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2205 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2206 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2208 image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2216 }/*if( tiBps == 8)*/
2218 if(tiBps == 12)/* CINEMA file */
2222 for(i = 0; i < ssize; i += step)
2224 if((index < imgsize)&&(index+1 < imgsize))
2226 image->comps[0].data[index] = ( dat8[i+0]<<4 ) |(dat8[i+1]>>4);
2227 image->comps[1].data[index] = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2229 image->comps[2].data[index] = ( dat8[i+3]<<4) |(dat8[i+4]>>4);
2230 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2232 image->comps[1].data[index+1] = ( dat8[i+6] <<4) |(dat8[i+7]>>4);
2233 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2241 }/*for(strip = 0; )*/
2249 if(tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2251 numcomps = 1 + has_alpha;
2252 color_space = OPJ_CLRSPC_GRAY;
2254 for(j = 0; j < numcomps; ++j)
2256 cmptparm[j].prec = tiBps;
2257 cmptparm[j].bpp = tiBps;
2258 cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2259 cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2260 cmptparm[j].w = (OPJ_UINT32)w;
2261 cmptparm[j].h = (OPJ_UINT32)h;
2264 image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2266 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2274 /* set image offset and reference grid
2276 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2277 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2278 image->x1 = !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2279 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2280 image->y1 = !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2281 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2283 buf = _TIFFmalloc(TIFFStripSize(tif));
2285 strip_size = TIFFStripSize(tif);
2287 imgsize = (int)(image->comps[0].w * image->comps[0].h);
2288 /* Read the Image components
2290 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2292 unsigned char *dat8;
2296 ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2297 dat8 = (unsigned char*)buf;
2301 step = 2 + has_alpha + has_alpha;
2303 for(i = 0; i < ssize; i += step)
2307 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2309 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2319 step = 1 + has_alpha;
2321 for(i = 0; i < ssize; i += step)
2325 image->comps[0].data[index] = dat8[i+0];
2327 image->comps[1].data[index] = dat8[i+1];
2345 #endif /* OPJ_HAVE_LIBTIFF */
2347 /* -->> -->> -->> -->>
2351 <<-- <<-- <<-- <<-- */
2352 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
2353 int subsampling_dx = parameters->subsampling_dx;
2354 int subsampling_dy = parameters->subsampling_dy;
2357 int i, compno, numcomps, w, h;
2358 OPJ_COLOR_SPACE color_space;
2359 opj_image_cmptparm_t *cmptparm;
2360 opj_image_t * image = NULL;
2363 if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2365 fprintf(stderr,"\nError: invalid raw image parameters\n");
2366 fprintf(stderr,"Please use the Format option -F:\n");
2367 fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2368 fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2369 fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2370 fprintf(stderr," for raw 512x512 image with 4:2:0 subsampling\n");
2371 fprintf(stderr,"Aborting.\n");
2375 f = fopen(filename, "rb");
2377 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2378 fprintf(stderr,"Aborting\n");
2381 numcomps = raw_cp->rawComp;
2383 /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2384 if (numcomps == 0) {
2385 color_space = OPJ_CLRSPC_GRAY;
2386 } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2387 color_space = OPJ_CLRSPC_SYCC;
2388 } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2389 color_space = OPJ_CLRSPC_SRGB;
2391 color_space = OPJ_CLRSPC_UNKNOWN;
2393 w = raw_cp->rawWidth;
2394 h = raw_cp->rawHeight;
2395 cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
2397 fprintf(stderr, "Failed to allocate image components parameters !!\n");
2398 fprintf(stderr,"Aborting\n");
2401 /* initialize image components */
2402 for(i = 0; i < numcomps; i++) {
2403 cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2404 cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2405 cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2406 cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2407 cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2408 cmptparm[i].w = (OPJ_UINT32)w;
2409 cmptparm[i].h = (OPJ_UINT32)h;
2411 /* create the image */
2412 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2418 /* set image offset and reference grid */
2419 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2420 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2421 image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2422 image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2424 if(raw_cp->rawBitDepth <= 8)
2426 unsigned char value = 0;
2427 for(compno = 0; compno < numcomps; compno++) {
2428 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2429 for (i = 0; i < nloop; i++) {
2430 if (!fread(&value, 1, 1, f)) {
2431 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2434 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2438 else if(raw_cp->rawBitDepth <= 16)
2440 unsigned short value;
2441 for(compno = 0; compno < numcomps; compno++) {
2442 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
2443 for (i = 0; i < nloop; i++) {
2444 unsigned char temp1;
2445 unsigned char temp2;
2446 if (!fread(&temp1, 1, 1, f)) {
2447 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2450 if (!fread(&temp2, 1, 1, f)) {
2451 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2456 value = (unsigned short)((temp1 << 8) + temp2);
2460 value = (unsigned short)((temp2 << 8) + temp1);
2462 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2467 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2471 if (fread(&ch, 1, 1, f)) {
2472 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2479 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2480 return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2483 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2484 return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2487 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
2489 FILE *rawFile = NULL;
2491 unsigned int compno;
2493 int line, row, curr, mask;
2498 if((image->numcomps * image->x1 * image->y1) == 0)
2500 fprintf(stderr,"\nError: invalid raw image parameters\n");
2504 rawFile = fopen(outfile, "wb");
2506 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2511 fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2513 for(compno = 0; compno < image->numcomps; compno++)
2515 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2516 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2518 w = (int)image->comps[compno].w;
2519 h = (int)image->comps[compno].h;
2521 if(image->comps[compno].prec <= 8)
2523 if(image->comps[compno].sgnd == 1)
2525 mask = (1 << image->comps[compno].prec) - 1;
2526 ptr = image->comps[compno].data;
2527 for (line = 0; line < h; line++) {
2528 for(row = 0; row < w; row++) {
2530 if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
2531 uc = (unsigned char) (curr & mask);
2532 res = fwrite(&uc, 1, 1, rawFile);
2534 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2541 else if(image->comps[compno].sgnd == 0)
2543 mask = (1 << image->comps[compno].prec) - 1;
2544 ptr = image->comps[compno].data;
2545 for (line = 0; line < h; line++) {
2546 for(row = 0; row < w; row++) {
2548 if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
2549 uc = (unsigned char) (curr & mask);
2550 res = fwrite(&uc, 1, 1, rawFile);
2552 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2560 else if(image->comps[compno].prec <= 16)
2562 if(image->comps[compno].sgnd == 1)
2564 union { signed short val; signed char vals[2]; } uc16;
2565 mask = (1 << image->comps[compno].prec) - 1;
2566 ptr = image->comps[compno].data;
2567 for (line = 0; line < h; line++) {
2568 for(row = 0; row < w; row++) {
2570 if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
2571 uc16.val = (signed short)(curr & mask);
2572 res = fwrite(uc16.vals, 1, 2, rawFile);
2574 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2581 else if(image->comps[compno].sgnd == 0)
2583 union { unsigned short val; unsigned char vals[2]; } uc16;
2584 mask = (1 << image->comps[compno].prec) - 1;
2585 ptr = image->comps[compno].data;
2586 for (line = 0; line < h; line++) {
2587 for(row = 0; row < w; row++) {
2589 if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
2590 uc16.val = (unsigned short)(curr & mask);
2591 res = fwrite(uc16.vals, 1, 2, rawFile);
2593 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2601 else if (image->comps[compno].prec <= 32)
2603 fprintf(stderr,"More than 16 bits per component no handled yet\n");
2608 fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2618 int imagetoraw(opj_image_t * image, const char *outfile)
2620 return imagetoraw_common(image, outfile, OPJ_TRUE);
2623 int imagetorawl(opj_image_t * image, const char *outfile)
2625 return imagetoraw_common(image, outfile, OPJ_FALSE);
2628 #ifdef OPJ_HAVE_LIBPNG
2630 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
2631 #define MAGIC_SIZE 8
2632 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
2634 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
2638 double gamma, display_exponent;
2639 int bit_depth, interlace_type,compression_type, filter_type;
2641 png_uint_32 resx, resy;
2643 png_uint_32 width, height;
2644 int color_type, has_alpha, is16;
2647 unsigned char **rows;
2650 opj_image_cmptparm_t cmptparm[4];
2652 unsigned int nr_comp;
2653 int *r, *g, *b, *a = NULL;
2654 unsigned char sigbuf[8];
2656 if((reader = fopen(read_idf, "rb")) == NULL)
2658 fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
2661 image = NULL; png = NULL; rows = NULL;
2663 if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
2664 || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
2666 fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
2669 /* libpng-VERSION/example.c:
2670 * PC : screen_gamma = 2.2;
2671 * Mac: screen_gamma = 1.7 or 1.0;
2673 display_exponent = 2.2;
2675 if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
2676 NULL, NULL, NULL)) == NULL)
2678 if((info = png_create_info_struct(png)) == NULL)
2681 if(setjmp(png_jmpbuf(png)))
2684 png_init_io(png, reader);
2685 png_set_sig_bytes(png, MAGIC_SIZE);
2687 png_read_info(png, info);
2689 if(png_get_IHDR(png, info, &width, &height,
2690 &bit_depth, &color_type, &interlace_type,
2691 &compression_type, &filter_type) == 0)
2694 /* png_set_expand():
2695 * expand paletted images to RGB, expand grayscale images of
2696 * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
2697 * to alpha channels.
2699 if(color_type == PNG_COLOR_TYPE_PALETTE)
2700 png_set_expand(png);
2702 if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
2703 png_set_expand(png);
2705 if(png_get_valid(png, info, PNG_INFO_tRNS))
2706 png_set_expand(png);
2708 is16 = (bit_depth == 16);
2710 /* GRAY => RGB; GRAY_ALPHA => RGBA
2712 if(color_type == PNG_COLOR_TYPE_GRAY
2713 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
2715 png_set_gray_to_rgb(png);
2717 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
2718 PNG_COLOR_TYPE_RGB_ALPHA);
2720 if( !png_get_gAMA(png, info, &gamma))
2723 png_set_gamma(png, display_exponent, gamma);
2725 png_read_update_info(png, info);
2727 png_get_pHYs(png, info, &resx, &resy, &unit);
2729 color_type = png_get_color_type(png, info);
2731 has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
2733 nr_comp = 3 + (unsigned int)has_alpha;
2735 bit_depth = png_get_bit_depth(png, info);
2737 rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
2738 for(i = 0; i < height; ++i)
2739 rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
2741 png_read_image(png, rows);
2743 memset(cmptparm, 0, sizeof(cmptparm));
2745 sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
2747 for(i = 0; i < nr_comp; ++i)
2749 cmptparm[i].prec = (OPJ_UINT32)bit_depth;
2750 /* bits_per_pixel: 8 or 16 */
2751 cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
2752 cmptparm[i].sgnd = 0;
2753 cmptparm[i].dx = (OPJ_UINT32)sub_dx;
2754 cmptparm[i].dy = (OPJ_UINT32)sub_dy;
2755 cmptparm[i].w = (OPJ_UINT32)width;
2756 cmptparm[i].h = (OPJ_UINT32)height;
2759 image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
2761 if(image == NULL) goto fin;
2763 image->x0 = (OPJ_UINT32)params->image_offset_x0;
2764 image->y0 = (OPJ_UINT32)params->image_offset_y0;
2765 image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
2766 image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
2768 r = image->comps[0].data;
2769 g = image->comps[1].data;
2770 b = image->comps[2].data;
2772 a = image->comps[3].data;
2773 image->comps[3].alpha = 1;
2776 for(i = 0; i < height; ++i)
2780 for(j = 0; j < width; ++j)
2784 *r++ = s[0]<<8|s[1]; s += 2;
2786 *g++ = s[0]<<8|s[1]; s += 2;
2788 *b++ = s[0]<<8|s[1]; s += 2;
2790 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
2794 *r++ = *s++; *g++ = *s++; *b++ = *s++;
2796 if(has_alpha) *a++ = *s++;
2802 for(i = 0; i < height; ++i)
2807 png_destroy_read_struct(&png, &info, NULL);
2815 int imagetopng(opj_image_t * image, const char *write_idf)
2820 int *red, *green, *blue, *alpha;
2821 unsigned char *row_buf, *d;
2822 int has_alpha, width, height, nr_comp, color_type;
2823 int adjustR, adjustG, adjustB, adjustA, x, y, fails;
2824 int prec, ushift, dshift, is16, force16, force8;
2825 unsigned short mask = 0xffff;
2826 png_color_8 sig_bit;
2828 is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
2829 prec = (int)image->comps[0].prec;
2830 nr_comp = (int)image->numcomps;
2832 if(prec > 8 && prec < 16)
2834 ushift = 16 - prec; dshift = prec - ushift;
2835 prec = 16; force16 = 1;
2838 if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
2840 ushift = 8 - prec; dshift = 8 - ushift;
2841 prec = 8; force8 = 1;
2844 if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
2846 fprintf(stderr,"imagetopng: can not create %s"
2847 "\n\twrong bit_depth %d\n", write_idf, prec);
2850 writer = fopen(write_idf, "wb");
2852 if(writer == NULL) return fails;
2854 info = NULL; has_alpha = 0;
2856 /* Create and initialize the png_struct with the desired error handler
2857 * functions. If you want to use the default stderr and longjump method,
2858 * you can supply NULL for the last three parameters. We also check that
2859 * the library version is compatible with the one used at compile time,
2860 * in case we are using dynamically linked libraries. REQUIRED.
2862 png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2864 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2866 if(png == NULL) goto fin;
2868 /* Allocate/initialize the image information data. REQUIRED
2870 info = png_create_info_struct(png);
2872 if(info == NULL) goto fin;
2874 /* Set error handling. REQUIRED if you are not supplying your own
2875 * error handling functions in the png_create_write_struct() call.
2877 if(setjmp(png_jmpbuf(png))) goto fin;
2879 /* I/O initialization functions is REQUIRED
2881 png_init_io(png, writer);
2883 /* Set the image information here. Width and height are up to 2^31,
2884 * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2885 * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2886 * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2887 * or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
2888 * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2889 * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
2894 * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
2895 * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
2896 * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
2897 * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
2900 png_set_compression_level(png, Z_BEST_COMPRESSION);
2902 if(prec == 16) mask = 0xffff;
2904 if(prec == 8) mask = 0x00ff;
2906 if(prec == 4) mask = 0x000f;
2908 if(prec == 2) mask = 0x0003;
2910 if(prec == 1) mask = 0x0001;
2913 && image->comps[0].dx == image->comps[1].dx
2914 && image->comps[1].dx == image->comps[2].dx
2915 && image->comps[0].dy == image->comps[1].dy
2916 && image->comps[1].dy == image->comps[2].dy
2917 && image->comps[0].prec == image->comps[1].prec
2918 && image->comps[1].prec == image->comps[2].prec)
2922 has_alpha = (nr_comp > 3);
2924 is16 = (prec == 16);
2926 width = (int)image->comps[0].w;
2927 height = (int)image->comps[0].h;
2929 red = image->comps[0].data;
2930 green = image->comps[1].data;
2931 blue = image->comps[2].data;
2933 sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
2937 sig_bit.alpha = (png_byte)prec;
2938 alpha = image->comps[3].data;
2939 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2940 adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
2944 sig_bit.alpha = 0; alpha = NULL;
2945 color_type = PNG_COLOR_TYPE_RGB;
2948 png_set_sBIT(png, info, &sig_bit);
2950 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
2953 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2955 png_set_gamma(png, 2.2, 1./2.2);
2956 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
2957 /*=============================*/
2958 png_write_info(png, info);
2959 /*=============================*/
2962 png_set_packing(png);
2964 printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
2965 image->comps[0].sgnd,
2966 image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
2968 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2969 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2970 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2972 row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
2974 for(y = 0; y < height; ++y)
2978 for(x = 0; x < width; ++x)
2982 v = *red + adjustR; ++red;
2983 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2985 if(force16) { v = (v<<ushift) + (v>>dshift); }
2987 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2989 v = *green + adjustG; ++green;
2990 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2992 if(force16) { v = (v<<ushift) + (v>>dshift); }
2994 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2996 v = *blue + adjustB; ++blue;
2997 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2999 if(force16) { v = (v<<ushift) + (v>>dshift); }
3001 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3005 v = *alpha + adjustA; ++alpha;
3006 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3008 if(force16) { v = (v<<ushift) + (v>>dshift); }
3010 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3015 v = *red + adjustR; ++red;
3016 if(v > 255) v = 255; else if(v < 0) v = 0;
3018 if(force8) { v = (v<<ushift) + (v>>dshift); }
3020 *d++ = (unsigned char)(v & mask);
3022 v = *green + adjustG; ++green;
3023 if(v > 255) v = 255; else if(v < 0) v = 0;
3025 if(force8) { v = (v<<ushift) + (v>>dshift); }
3027 *d++ = (unsigned char)(v & mask);
3029 v = *blue + adjustB; ++blue;
3030 if(v > 255) v = 255; else if(v < 0) v = 0;
3032 if(force8) { v = (v<<ushift) + (v>>dshift); }
3034 *d++ = (unsigned char)(v & mask);
3038 v = *alpha + adjustA; ++alpha;
3039 if(v > 255) v = 255; else if(v < 0) v = 0;
3041 if(force8) { v = (v<<ushift) + (v>>dshift); }
3043 *d++ = (unsigned char)(v & mask);
3047 png_write_row(png, row_buf);
3054 if(nr_comp == 1 /* GRAY */
3055 || ( nr_comp == 2 /* GRAY_ALPHA */
3056 && image->comps[0].dx == image->comps[1].dx
3057 && image->comps[0].dy == image->comps[1].dy
3058 && image->comps[0].prec == image->comps[1].prec))
3062 red = image->comps[0].data;
3064 sig_bit.gray = (png_byte)prec;
3065 sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3066 alpha = NULL; adjustA = 0;
3067 color_type = PNG_COLOR_TYPE_GRAY;
3071 has_alpha = 1; sig_bit.alpha = (png_byte)prec;
3072 alpha = image->comps[1].data;
3073 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3074 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3076 width = (int)image->comps[0].w;
3077 height = (int)image->comps[0].h;
3079 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
3082 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3084 png_set_sBIT(png, info, &sig_bit);
3086 png_set_gamma(png, 2.2, 1./2.2);
3087 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3088 /*=============================*/
3089 png_write_info(png, info);
3090 /*=============================*/
3091 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3095 png_set_packing(png);
3100 row_buf = (unsigned char*)
3101 malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
3103 for(y = 0; y < height; ++y)
3107 for(x = 0; x < width; ++x)
3109 v = *red + adjustR; ++red;
3110 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3112 if(force16) { v = (v<<ushift) + (v>>dshift); }
3114 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3119 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3121 if(force16) { v = (v<<ushift) + (v>>dshift); }
3123 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3126 png_write_row(png, row_buf);
3131 else /* prec <= 8 */
3133 row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
3135 for(y = 0; y < height; ++y)
3139 for(x = 0; x < width; ++x)
3141 v = *red + adjustR; ++red;
3142 if(v > 255) v = 255; else if(v < 0) v = 0;
3144 if(force8) { v = (v<<ushift) + (v>>dshift); }
3146 *d++ = (unsigned char)(v & mask);
3150 v = *alpha + adjustA; ++alpha;
3151 if(v > 255) v = 255; else if(v < 0) v = 0;
3153 if(force8) { v = (v<<ushift) + (v>>dshift); }
3155 *d++ = (unsigned char)(v & mask);
3159 png_write_row(png, row_buf);
3167 fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3170 png_write_end(png, info);
3178 png_destroy_write_struct(&png, &info);
3182 if(fails) remove(write_idf);
3186 #endif /* OPJ_HAVE_LIBPNG */