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 void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
111 if (component->prec == precision) {
114 if (component->prec < precision) {
115 shift = (int)(precision - component->prec);
117 shift = (int)(component->prec - precision);
119 len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
121 if (component->sgnd) {
122 OPJ_INT32* l_data = component->data;
123 if (component->prec < precision) {
124 for (i = 0; i < len; ++i) {
128 for (i = 0; i < len; ++i) {
133 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
134 if (component->prec < precision) {
135 for (i = 0; i < len; ++i) {
139 for (i = 0; i < len; ++i) {
144 component->prec = precision;
148 /* -->> -->> -->> -->>
152 <<-- <<-- <<-- <<-- */
154 #ifdef INFORMATION_ONLY
155 /* TGA header definition. */
158 unsigned char id_length; /* Image id field length */
159 unsigned char colour_map_type; /* Colour map type */
160 unsigned char image_type; /* Image type */
162 ** Colour map specification
164 unsigned short colour_map_index; /* First entry index */
165 unsigned short colour_map_length; /* Colour map length */
166 unsigned char colour_map_entry_size; /* Colour map entry size */
168 ** Image specification
170 unsigned short x_origin; /* x origin of image */
171 unsigned short y_origin; /* u origin of image */
172 unsigned short image_width; /* Image width */
173 unsigned short image_height; /* Image height */
174 unsigned char pixel_depth; /* Pixel depth */
175 unsigned char image_desc; /* Image descriptor */
177 #endif /* INFORMATION_ONLY */
179 static unsigned short get_ushort(unsigned short val) {
181 #ifdef OPJ_BIG_ENDIAN
182 return( ((val & 0xff) << 8) + (val >> 8) );
189 #define TGA_HEADER_SIZE 18
191 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
192 unsigned int *width, unsigned int *height, int *flip_image)
196 unsigned char id_len, /*cmap_type,*/ image_type;
197 unsigned char pixel_depth, image_desc;
198 unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
199 unsigned short /*x_origin, y_origin,*/ image_w, image_h;
201 if (!bits_per_pixel || !width || !height || !flip_image)
203 tga = (unsigned char*)malloc(18);
205 if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
207 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
210 id_len = (unsigned char)tga[0];
211 /*cmap_type = (unsigned char)tga[1];*/
212 image_type = (unsigned char)tga[2];
213 /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
214 cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
215 cmap_entry_size = (unsigned char)tga[7];
219 x_origin = get_ushort(*(unsigned short*)(&tga[8]));
220 y_origin = get_ushort(*(unsigned short*)(&tga[10]));
222 image_w = get_ushort(*(unsigned short*)(&tga[12]));
223 image_h = get_ushort(*(unsigned short*)(&tga[14]));
224 pixel_depth = (unsigned char)tga[16];
225 image_desc = (unsigned char)tga[17];
229 *bits_per_pixel = (unsigned int)pixel_depth;
230 *width = (unsigned int)image_w;
231 *height = (unsigned int)image_h;
233 /* Ignore tga identifier, if present ... */
236 unsigned char *id = (unsigned char *) malloc(id_len);
237 if ( !fread(id, id_len, 1, fp) )
239 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
246 /* Test for compressed formats ... not yet supported ...
247 // Note :- 9 - RLE encoded palettized.
248 // 10 - RLE encoded RGB. */
251 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
255 *flip_image = !(image_desc & 32);
257 /* Palettized formats are not yet supported, skip over the palette, if present ... */
258 palette_size = cmap_len * (cmap_entry_size/8);
262 fprintf(stderr, "File contains a palette - not yet supported.");
263 fseek(fp, palette_size, SEEK_CUR);
268 #ifdef OPJ_BIG_ENDIAN
270 static INLINE int16_t swap16(int16_t x)
272 return((((u_int16_t)x & 0x00ffU) << 8) |
273 (((u_int16_t)x & 0xff00U) >> 8));
278 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
281 unsigned short image_w, image_h, us0;
282 unsigned char uc0, image_type;
283 unsigned char pixel_depth, image_desc;
285 if (!bits_per_pixel || !width || !height)
290 if ( bits_per_pixel < 256 )
291 pixel_depth = (unsigned char)bits_per_pixel;
293 fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
298 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
299 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
301 image_type = 2; /* Uncompressed. */
302 if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
305 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
306 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
307 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
309 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
310 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
312 image_w = (unsigned short)width;
313 image_h = (unsigned short) height;
315 #ifndef OPJ_BIG_ENDIAN
316 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
317 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
319 image_w = swap16(image_w);
320 image_h = swap16(image_h);
321 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
322 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
325 if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
327 image_desc = 8; /* 8 bits per component. */
331 if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
336 fputs("\nwrite_tgaheader: write ERROR\n", stderr);
340 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
343 unsigned int image_width, image_height, pixel_bit_depth;
346 opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
348 OPJ_COLOR_SPACE color_space;
351 int subsampling_dx, subsampling_dy;
354 f = fopen(filename, "rb");
356 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
360 if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
363 /* We currently only support 24 & 32 bit tga's ... */
364 if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
367 /* initialize image components */
368 memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
370 mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16); /* Mono with & without alpha. */
371 save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
374 color_space = OPJ_CLRSPC_GRAY;
375 numcomps = save_alpha ? 2 : 1;
378 numcomps = save_alpha ? 4 : 3;
379 color_space = OPJ_CLRSPC_SRGB;
382 subsampling_dx = parameters->subsampling_dx;
383 subsampling_dy = parameters->subsampling_dy;
385 for (i = 0; i < numcomps; i++) {
386 cmptparm[i].prec = 8;
388 cmptparm[i].sgnd = 0;
389 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
390 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
391 cmptparm[i].w = image_width;
392 cmptparm[i].h = image_height;
395 /* create the image */
396 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
401 /* set image offset and reference grid */
402 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
403 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
404 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;
405 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;
408 for (y=0; y < image_height; y++)
413 index = (int)((image_height-y-1)*image_width);
415 index = (int)(y*image_width);
419 for (x=0;x<image_width;x++)
423 if( !fread(&b, 1, 1, f) )
425 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
426 opj_image_destroy(image);
429 if ( !fread(&g, 1, 1, f) )
431 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
432 opj_image_destroy(image);
435 if ( !fread(&r, 1, 1, f) )
437 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
438 opj_image_destroy(image);
442 image->comps[0].data[index]=r;
443 image->comps[1].data[index]=g;
444 image->comps[2].data[index]=b;
448 else if (numcomps==4)
450 for (x=0;x<image_width;x++)
452 unsigned char r,g,b,a;
453 if ( !fread(&b, 1, 1, f) )
455 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
456 opj_image_destroy(image);
459 if ( !fread(&g, 1, 1, f) )
461 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
462 opj_image_destroy(image);
465 if ( !fread(&r, 1, 1, f) )
467 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
468 opj_image_destroy(image);
471 if ( !fread(&a, 1, 1, f) )
473 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
474 opj_image_destroy(image);
478 image->comps[0].data[index]=r;
479 image->comps[1].data[index]=g;
480 image->comps[2].data[index]=b;
481 image->comps[3].data[index]=a;
486 fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
492 int imagetotga(opj_image_t * image, const char *outfile) {
493 int width, height, bpp, x, y;
494 OPJ_BOOL write_alpha;
496 int adjustR, adjustG, adjustB, fails;
497 unsigned int alpha_channel;
505 fdest = fopen(outfile, "wb");
507 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
511 for (i = 0; i < image->numcomps-1; i++) {
512 if ((image->comps[0].dx != image->comps[i+1].dx)
513 ||(image->comps[0].dy != image->comps[i+1].dy)
514 ||(image->comps[0].prec != image->comps[i+1].prec)) {
515 fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
520 width = (int)image->comps[0].w;
521 height = (int)image->comps[0].h;
523 /* Mono with alpha, or RGB with alpha. */
524 write_alpha = (image->numcomps==2) || (image->numcomps==4);
526 /* Write TGA header */
527 bpp = write_alpha ? 32 : 24;
529 if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
532 alpha_channel = image->numcomps-1;
534 scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
536 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
537 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
538 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
540 for (y=0; y < height; y++)
542 unsigned int index= (unsigned int)(y*width);
544 for (x=0; x < width; x++, index++)
546 r = (float)(image->comps[0].data[index] + adjustR);
548 if (image->numcomps > 2)
550 g = (float)(image->comps[1].data[index] + adjustG);
551 b = (float)(image->comps[2].data[index] + adjustB);
559 /* TGA format writes BGR ... */
560 if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
561 value = (unsigned char)(b*scale);
562 res = fwrite(&value,1,1,fdest);
566 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
569 if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
570 value = (unsigned char)(g*scale);
571 res = fwrite(&value,1,1,fdest);
575 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
578 if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
579 value = (unsigned char)(r*scale);
580 res = fwrite(&value,1,1,fdest);
584 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
590 a = (float)(image->comps[alpha_channel].data[index]);
591 if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
592 value = (unsigned char)(a*scale);
593 res = fwrite(&value,1,1,fdest);
597 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
610 /* -->> -->> -->> -->>
614 <<-- <<-- <<-- <<-- */
617 static unsigned char readuchar(FILE * f)
620 if ( !fread(&c1, 1, 1, f) )
622 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
628 static unsigned short readushort(FILE * f, int bigendian)
630 unsigned char c1, c2;
631 if ( !fread(&c1, 1, 1, f) )
633 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
636 if ( !fread(&c2, 1, 1, f) )
638 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
642 return (unsigned short)((c1 << 8) + c2);
644 return (unsigned short)((c2 << 8) + c1);
647 static unsigned int readuint(FILE * f, int bigendian)
649 unsigned char c1, c2, c3, c4;
650 if ( !fread(&c1, 1, 1, f) )
652 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
655 if ( !fread(&c2, 1, 1, f) )
657 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
660 if ( !fread(&c3, 1, 1, f) )
662 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
665 if ( !fread(&c4, 1, 1, f) )
667 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
671 return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
673 return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
676 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
679 int i, numcomps, max;
680 OPJ_COLOR_SPACE color_space;
681 opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
682 opj_image_t * image = NULL;
683 int adjustS, ushift, dshift, force8;
685 char endian1,endian2,sign;
690 opj_image_comp_t *comp = NULL;
693 color_space = OPJ_CLRSPC_GRAY;
695 memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
699 f = fopen(filename, "rb");
701 fprintf(stderr, "Failed to open %s for reading !\n", filename);
705 fseek(f, 0, SEEK_SET);
706 if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
707 fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
713 while (signtmp[i]!='\0') {
714 if (signtmp[i]=='-') sign='-';
719 if (endian1=='M' && endian2=='L') {
721 } else if (endian2=='M' && endian1=='L') {
724 fprintf(stderr, "Bad pgx header, please check input file\n");
728 /* initialize image component */
730 cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
731 cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
732 cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
733 cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
743 ushift = 8 - prec; dshift = prec - ushift;
744 if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
748 else ushift = dshift = force8 = adjustS = 0;
750 cmptparm.prec = (OPJ_UINT32)prec;
751 cmptparm.bpp = (OPJ_UINT32)prec;
752 cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
753 cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
755 /* create the image */
756 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
761 /* set image offset and reference grid */
762 image->x0 = cmptparm.x0;
763 image->y0 = cmptparm.x0;
764 image->x1 = cmptparm.w;
765 image->y1 = cmptparm.h;
769 comp = &image->comps[0];
771 for (i = 0; i < w * h; i++) {
775 v = readuchar(f) + adjustS;
776 v = (v<<ushift) + (v>>dshift);
777 comp->data[i] = (unsigned char)v;
783 if (comp->prec == 8) {
787 v = (char) readuchar(f);
789 } else if (comp->prec <= 16) {
791 v = readushort(f, bigendian);
793 v = (short) readushort(f, bigendian);
797 v = (int)readuint(f, bigendian);
799 v = (int) readuint(f, bigendian);
807 comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
812 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
814 static INLINE int clamp( const int value, const int prec, const int sgnd )
818 if (prec <= 8) return CLAMP(value,-128,127);
819 else if (prec <= 16) return CLAMP(value,-32768,32767);
820 else return CLAMP(value,-2147483647-1,2147483647);
824 if (prec <= 8) return CLAMP(value,0,255);
825 else if (prec <= 16) return CLAMP(value,0,65535);
826 else return value; /*CLAMP(value,0,4294967295);*/
830 int imagetopgx(opj_image_t * image, const char *outfile)
837 for (compno = 0; compno < image->numcomps; compno++)
839 opj_image_comp_t *comp = &image->comps[compno];
840 char bname[256]; /* buffer for name */
841 char *name = bname; /* pointer */
844 const size_t olen = strlen(outfile);
845 const size_t dotpos = olen - 4;
846 const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
848 if( outfile[dotpos] != '.' )
850 /* `pgx` was recognized but there is no dot at expected position */
851 fprintf(stderr, "ERROR -> Impossible happen." );
856 name = (char*)malloc(total+1);
858 strncpy(name, outfile, dotpos);
859 sprintf(name+dotpos, "_%d.pgx", compno);
860 fdest = fopen(name, "wb");
861 /* dont need name anymore */
862 if( total > 256 ) free(name);
865 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
869 w = (int)image->comps[compno].w;
870 h = (int)image->comps[compno].h;
872 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
877 else if (comp->prec <= 16)
882 for (i = 0; i < w * h; i++)
884 /* FIXME: clamp func is being called within a loop */
885 const int val = clamp(image->comps[compno].data[i],
886 (int)comp->prec, (int)comp->sgnd);
888 for (j = nbytes - 1; j >= 0; j--)
890 int v = (int)(val >> (j * 8));
891 unsigned char byte = (unsigned char)v;
892 res = fwrite(&byte, 1, 1, fdest);
896 fprintf(stderr, "failed to write 1 byte for %s\n", name);
901 fclose(fdest); fdest = NULL;
905 if(fdest) fclose(fdest);
910 /* -->> -->> -->> -->>
914 <<-- <<-- <<-- <<-- */
918 int width, height, maxval, depth, format;
919 char rgb, rgba, gray, graya, bw;
923 static char *skip_white(char *s)
927 if(*s == '\n' || *s == '\r') return NULL;
928 if(isspace(*s)) { ++s; continue; }
934 static char *skip_int(char *start, int *out_n)
939 *out_n = 0; s = start;
941 s = skip_white(start);
942 if(s == NULL) return NULL;
947 if( !isdigit(*s)) break;
950 c = *s; *s = 0; *out_n = atoi(start); *s = c;
954 static char *skip_idf(char *start, char out_idf[256])
959 s = skip_white(start);
960 if(s == NULL) return NULL;
965 if(isalpha(*s) || *s == '_') { ++s; continue; }
968 c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
972 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
974 int format, have_wh, end, ttype;
975 char idf[256], type[256];
978 if (fgets(line, 250, reader) == NULL)
980 fprintf(stderr,"\nWARNING: fgets return a NULL value");
986 fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
988 format = atoi(line + 1);
989 if(format < 1 || format > 7)
991 fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
995 ttype = end = have_wh = 0;
997 while(fgets(line, 250, reader))
1001 if(*line == '#') continue;
1007 s = skip_idf(s, idf);
1009 if(s == NULL || *s == 0) return;
1011 if(strcmp(idf, "ENDHDR") == 0)
1015 if(strcmp(idf, "WIDTH") == 0)
1017 s = skip_int(s, &ph->width);
1018 if(s == NULL || *s == 0) return;
1022 if(strcmp(idf, "HEIGHT") == 0)
1024 s = skip_int(s, &ph->height);
1025 if(s == NULL || *s == 0) return;
1029 if(strcmp(idf, "DEPTH") == 0)
1031 s = skip_int(s, &ph->depth);
1032 if(s == NULL || *s == 0) return;
1036 if(strcmp(idf, "MAXVAL") == 0)
1038 s = skip_int(s, &ph->maxval);
1039 if(s == NULL || *s == 0) return;
1043 if(strcmp(idf, "TUPLTYPE") == 0)
1045 s = skip_idf(s, type);
1046 if(s == NULL || *s == 0) return;
1048 if(strcmp(type, "BLACKANDWHITE") == 0)
1050 ph->bw = 1; ttype = 1; continue;
1052 if(strcmp(type, "GRAYSCALE") == 0)
1054 ph->gray = 1; ttype = 1; continue;
1056 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1058 ph->graya = 1; ttype = 1; continue;
1060 if(strcmp(type, "RGB") == 0)
1062 ph->rgb = 1; ttype = 1; continue;
1064 if(strcmp(type, "RGB_ALPHA") == 0)
1066 ph->rgba = 1; ttype = 1; continue;
1068 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1071 fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1073 } /* if(format == 7) */
1077 s = skip_int(s, &ph->width);
1079 s = skip_int(s, &ph->height);
1083 if(format == 1 || format == 4) break;
1085 if(format == 2 || format == 3 || format == 5 || format == 6)
1087 if (skip_int(s, &ph->maxval) != NULL) {
1088 if(ph->maxval > 65535) {
1098 if(format == 2 || format == 3 || format == 5 || format == 6)
1100 /* P2, P3, P5, P6: */
1101 s = skip_int(s, &ph->maxval);
1103 if(ph->maxval > 65535) return;
1106 }/* while(fgets( ) */
1107 if(format == 2 || format == 3 || format > 4)
1109 if(ph->maxval < 1 || ph->maxval > 65535) return;
1111 if(ph->width < 1 || ph->height < 1) return;
1117 fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1119 if(ph->depth < 1 || ph->depth > 4) return;
1121 if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1126 if(format != 1 && format != 4)
1128 if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1132 if(ph->width && ph->height) ph->ok = 1;
1138 static int has_prec(int val)
1140 if(val < 2) return 1;
1141 if(val < 4) return 2;
1142 if(val < 8) return 3;
1143 if(val < 16) return 4;
1144 if(val < 32) return 5;
1145 if(val < 64) return 6;
1146 if(val < 128) return 7;
1147 if(val < 256) return 8;
1148 if(val < 512) return 9;
1149 if(val < 1024) return 10;
1150 if(val < 2048) return 11;
1151 if(val < 4096) return 12;
1152 if(val < 8192) return 13;
1153 if(val < 16384) return 14;
1154 if(val < 32768) return 15;
1158 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1159 int subsampling_dx = parameters->subsampling_dx;
1160 int subsampling_dy = parameters->subsampling_dy;
1163 int i, compno, numcomps, w, h, prec, format;
1164 OPJ_COLOR_SPACE color_space;
1165 opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1166 opj_image_t * image = NULL;
1167 struct pnm_header header_info;
1169 if((fp = fopen(filename, "rb")) == NULL)
1171 fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1174 memset(&header_info, 0, sizeof(struct pnm_header));
1176 read_pnm_header(fp, &header_info);
1178 if(!header_info.ok) { fclose(fp); return NULL; }
1180 format = header_info.format;
1184 case 1: /* ascii bitmap */
1185 case 4: /* raw bitmap */
1189 case 2: /* ascii greymap */
1190 case 5: /* raw greymap */
1194 case 3: /* ascii pixmap */
1195 case 6: /* raw pixmap */
1199 case 7: /* arbitrary map */
1200 numcomps = header_info.depth;
1203 default: fclose(fp); return NULL;
1206 color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1208 color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1210 prec = has_prec(header_info.maxval);
1212 if(prec < 8) prec = 8;
1214 w = header_info.width;
1215 h = header_info.height;
1216 subsampling_dx = parameters->subsampling_dx;
1217 subsampling_dy = parameters->subsampling_dy;
1219 memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1221 for(i = 0; i < numcomps; i++)
1223 cmptparm[i].prec = (OPJ_UINT32)prec;
1224 cmptparm[i].bpp = (OPJ_UINT32)prec;
1225 cmptparm[i].sgnd = 0;
1226 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1227 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1228 cmptparm[i].w = (OPJ_UINT32)w;
1229 cmptparm[i].h = (OPJ_UINT32)h;
1231 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1233 if(!image) { fclose(fp); return NULL; }
1235 /* set image offset and reference grid */
1236 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1237 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1238 image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1239 image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1241 if((format == 2) || (format == 3)) /* ascii pixmap */
1245 for (i = 0; i < w * h; i++)
1247 for(compno = 0; compno < numcomps; compno++)
1250 if (fscanf(fp, "%u", &index) != 1)
1251 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1253 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1261 && ( header_info.gray || header_info.graya
1262 || header_info.rgb || header_info.rgba)))/* binary pixmap */
1264 unsigned char c0, c1, one;
1268 for (i = 0; i < w * h; i++)
1270 for(compno = 0; compno < numcomps; compno++)
1272 if ( !fread(&c0, 1, 1, fp) )
1274 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1275 opj_image_destroy(image);
1280 image->comps[compno].data[i] = c0;
1284 if ( !fread(&c1, 1, 1, fp) )
1285 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1287 image->comps[compno].data[i] = ((c0<<8) | c1);
1293 if(format == 1) /* ascii bitmap */
1295 for (i = 0; i < w * h; i++)
1299 if ( fscanf(fp, "%u", &index) != 1)
1300 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1302 image->comps[0].data[i] = (index?0:255);
1312 for(y = 0; y < h; ++y)
1316 for(x = 0; x < w; ++x)
1321 uc = (unsigned char)getc(fp);
1323 image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1329 if((format == 7 && header_info.bw)) /*MONO*/
1333 for(i = 0; i < w * h; ++i)
1335 if ( !fread(&uc, 1, 1, fp) )
1336 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1337 image->comps[0].data[i] = (uc & 1)?0:255;
1345 int imagetopnm(opj_image_t * image, const char *outfile)
1347 int *red, *green, *blue, *alpha;
1350 unsigned int compno, ncomp;
1351 int adjustR, adjustG, adjustB, adjustA;
1352 int fails, two, want_gray, has_alpha, triple;
1355 const char *tmp = outfile;
1360 if((prec = (int)image->comps[0].prec) > 16)
1362 fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1363 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1366 two = has_alpha = 0; fails = 1;
1367 ncomp = image->numcomps;
1369 while (*tmp) ++tmp; tmp -= 2;
1370 want_gray = (*tmp == 'g' || *tmp == 'G');
1371 ncomp = image->numcomps;
1373 if(want_gray) ncomp = 1;
1375 if (ncomp == 2 /* GRAYA */
1376 || (ncomp > 2 /* RGB, RGBA */
1377 && image->comps[0].dx == image->comps[1].dx
1378 && image->comps[1].dx == image->comps[2].dx
1379 && image->comps[0].dy == image->comps[1].dy
1380 && image->comps[1].dy == image->comps[2].dy
1381 && image->comps[0].prec == image->comps[1].prec
1382 && image->comps[1].prec == image->comps[2].prec
1385 fdest = fopen(outfile, "wb");
1389 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1393 triple = (ncomp > 2);
1394 wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1395 max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1397 red = image->comps[0].data;
1401 green = image->comps[1].data;
1402 blue = image->comps[2].data;
1404 else green = blue = NULL;
1408 const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1410 fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1411 "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1412 wr, hr, ncomp, max, tt);
1413 alpha = image->comps[ncomp - 1].data;
1414 adjustA = (image->comps[ncomp - 1].sgnd ?
1415 1 << (image->comps[ncomp - 1].prec - 1) : 0);
1419 fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1420 opj_version(), wr, hr, max);
1423 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1427 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1428 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1430 else adjustG = adjustB = 0;
1432 for(i = 0; i < wr * hr; ++i)
1436 v = *red + adjustR; ++red;
1437 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1440 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1444 v = *green + adjustG; ++green;
1445 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1448 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1450 v = *blue + adjustB; ++blue;
1451 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1454 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1460 v = *alpha + adjustA; ++alpha;
1461 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1464 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1472 if(v > 255) v = 255; else if(v < 0) v = 0;
1474 fprintf(fdest, "%c", (unsigned char)v);
1478 if(v > 255) v = 255; else if(v < 0) v = 0;
1480 fprintf(fdest, "%c", (unsigned char)v);
1482 if(v > 255) v = 255; else if(v < 0) v = 0;
1484 fprintf(fdest, "%c", (unsigned char)v);
1489 if(v > 255) v = 255; else if(v < 0) v = 0;
1491 fprintf(fdest, "%c", (unsigned char)v);
1495 fclose(fdest); return 0;
1500 if (image->numcomps > ncomp)
1502 fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1503 fprintf(stderr," is written to the file\n");
1505 destname = (char*)malloc(strlen(outfile) + 8);
1507 for (compno = 0; compno < ncomp; compno++)
1511 /*sprintf(destname, "%d.%s", compno, outfile);*/
1512 const size_t olen = strlen(outfile);
1513 const size_t dotpos = olen - 4;
1515 strncpy(destname, outfile, dotpos);
1516 sprintf(destname+dotpos, "_%d.pgm", compno);
1519 sprintf(destname, "%s", outfile);
1521 fdest = fopen(destname, "wb");
1524 fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1528 wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1529 prec = (int)image->comps[compno].prec;
1530 max = (1<<prec) - 1;
1532 fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1533 opj_version(), wr, hr, max);
1535 red = image->comps[compno].data;
1537 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1541 for (i = 0; i < wr * hr; i++)
1543 v = *red + adjustR; ++red;
1544 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1547 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1552 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1555 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1559 else /* prec <= 8 */
1561 for(i = 0; i < wr * hr; ++i)
1563 v = *red + adjustR; ++red;
1564 if(v > 255) v = 255; else if(v < 0) v = 0;
1566 fprintf(fdest, "%c", (unsigned char)v);
1576 #ifdef OPJ_HAVE_LIBTIFF
1577 /* -->> -->> -->> -->>
1581 <<-- <<-- <<-- <<-- */
1583 int imagetotif(opj_image_t * image, const char *outfile)
1585 int width, height, imgsize;
1586 int bps,index,adjust, sgnd;
1587 int ushift, dshift, has_alpha, force16;
1593 ushift = dshift = force16 = has_alpha = 0;
1594 bps = (int)image->comps[0].prec;
1596 if(bps > 8 && bps < 16)
1598 ushift = 16 - bps; dshift = bps - ushift;
1599 bps = 16; force16 = 1;
1602 if(bps != 8 && bps != 16)
1604 fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
1606 fprintf(stderr,"\tAborting\n");
1609 tif = TIFFOpen(outfile, "wb");
1613 fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
1616 sgnd = (int)image->comps[0].sgnd;
1617 adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
1619 if(image->numcomps >= 3
1620 && image->comps[0].dx == image->comps[1].dx
1621 && image->comps[1].dx == image->comps[2].dx
1622 && image->comps[0].dy == image->comps[1].dy
1623 && image->comps[1].dy == image->comps[2].dy
1624 && image->comps[0].prec == image->comps[1].prec
1625 && image->comps[1].prec == image->comps[2].prec)
1627 has_alpha = (image->numcomps == 4);
1629 width = (int)image->comps[0].w;
1630 height = (int)image->comps[0].h;
1631 imgsize = width * height ;
1633 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1634 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1635 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
1636 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1637 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1638 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1639 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1640 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1641 strip_size = TIFFStripSize(tif);
1642 buf = _TIFFmalloc(strip_size);
1645 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1647 unsigned char *dat8;
1648 tsize_t i, ssize, last_i = 0;
1650 ssize = TIFFStripSize(tif);
1651 dat8 = (unsigned char*)buf;
1655 step = 3 + has_alpha;
1658 for(i=0; i < ssize - restx; i += step)
1664 r = image->comps[0].data[index];
1665 g = image->comps[1].data[index];
1666 b = image->comps[2].data[index];
1667 if(has_alpha) a = image->comps[3].data[index];
1674 if(has_alpha) a += adjust;
1676 if(r > 255) r = 255; else if(r < 0) r = 0;
1677 dat8[i+0] = (unsigned char)r ;
1678 if(g > 255) g = 255; else if(g < 0) g = 0;
1679 dat8[i+1] = (unsigned char)g ;
1680 if(b > 255) b = 255; else if(b < 0) b = 0;
1681 dat8[i+2] = (unsigned char)b ;
1684 if(a > 255) a = 255; else if(a < 0) a = 0;
1685 dat8[i+3] = (unsigned char)a;
1697 for(i = last_i; i < ssize; i += step)
1703 r = image->comps[0].data[index];
1704 g = image->comps[1].data[index];
1705 b = image->comps[2].data[index];
1706 if(has_alpha) a = image->comps[3].data[index];
1713 if(has_alpha) a += adjust;
1715 if(r > 255) r = 255; else if(r < 0) r = 0;
1716 if(g > 255) g = 255; else if(g < 0) g = 0;
1717 if(b > 255) b = 255; else if(b < 0) b = 0;
1719 dat8[i+0] = (unsigned char)r ;
1720 if(i+1 < ssize) dat8[i+1] = (unsigned char)g ; else break;
1721 if(i+2 < ssize) dat8[i+2] = (unsigned char)b ; else break;
1724 if(a > 255) a = 255; else if(a < 0) a = 0;
1726 if(i+3 < ssize) dat8[i+3] = (unsigned char)a ; else break;
1733 }/*if(last_i < ssize)*/
1739 step = 6 + has_alpha + has_alpha;
1742 for(i = 0; i < ssize - restx ; i += step)
1748 r = image->comps[0].data[index];
1749 g = image->comps[1].data[index];
1750 b = image->comps[2].data[index];
1751 if(has_alpha) a = image->comps[3].data[index];
1758 if(has_alpha) a += adjust;
1762 r = (r<<ushift) + (r>>dshift);
1763 g = (g<<ushift) + (g>>dshift);
1764 b = (b<<ushift) + (b>>dshift);
1765 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1767 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1768 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1769 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1771 dat8[i+0] = (unsigned char)r;/*LSB*/
1772 dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1773 dat8[i+2] = (unsigned char)g;
1774 dat8[i+3] = (unsigned char)(g >> 8);
1775 dat8[i+4] = (unsigned char)b;
1776 dat8[i+5] = (unsigned char)(b >> 8);
1779 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1780 dat8[i+6] = (unsigned char)a;
1781 dat8[i+7] = (unsigned char)(a >> 8);
1792 for(i = last_i ; i < ssize ; i += step)
1798 r = image->comps[0].data[index];
1799 g = image->comps[1].data[index];
1800 b = image->comps[2].data[index];
1801 if(has_alpha) a = image->comps[3].data[index];
1808 if(has_alpha) a += adjust;
1812 r = (r<<ushift) + (r>>dshift);
1813 g = (g<<ushift) + (g>>dshift);
1814 b = (b<<ushift) + (b>>dshift);
1815 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1817 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1818 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1819 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1821 dat8[i+0] = (unsigned char) r;/*LSB*/
1822 if(i+1 < ssize) dat8[i+1] = (unsigned char)(r >> 8);else break;/*MSB*/
1823 if(i+2 < ssize) dat8[i+2] = (unsigned char) g; else break;
1824 if(i+3 < ssize) dat8[i+3] = (unsigned char)(g >> 8);else break;
1825 if(i+4 < ssize) dat8[i+4] = (unsigned char) b; else break;
1826 if(i+5 < ssize) dat8[i+5] = (unsigned char)(b >> 8);else break;
1830 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1831 if(i+6 < ssize) dat8[i+6] = (unsigned char)a; else break;
1832 if(i+7 < ssize) dat8[i+7] = (unsigned char)(a >> 8); else break;
1839 }/*if(last_i < ssize)*/
1842 (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1843 }/*for(strip = 0; )*/
1845 _TIFFfree((void*)buf);
1851 if(image->numcomps == 1 /* GRAY */
1852 || ( image->numcomps == 2 /* GRAY_ALPHA */
1853 && image->comps[0].dx == image->comps[1].dx
1854 && image->comps[0].dy == image->comps[1].dy
1855 && image->comps[0].prec == image->comps[1].prec))
1859 has_alpha = (image->numcomps == 2);
1861 width = (int)image->comps[0].w;
1862 height = (int)image->comps[0].h;
1863 imgsize = width * height;
1866 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1867 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1868 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
1869 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1870 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1871 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1872 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1873 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1875 /* Get a buffer for the data */
1876 strip_size = TIFFStripSize(tif);
1877 buf = _TIFFmalloc(strip_size);
1880 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1882 unsigned char *dat8;
1883 tsize_t i, ssize = TIFFStripSize(tif);
1884 dat8 = (unsigned char*)buf;
1888 step = 1 + has_alpha;
1890 for(i=0; i < ssize; i += step)
1896 r = image->comps[0].data[index];
1897 if(has_alpha) a = image->comps[1].data[index];
1902 if(has_alpha) a += adjust;
1904 if(r > 255) r = 255; else if(r < 0) r = 0;
1905 dat8[i+0] = (unsigned char)r;
1909 if(a > 255) a = 255; else if(a < 0) a = 0;
1910 dat8[i+1] = (unsigned char)a;
1921 step = 2 + has_alpha + has_alpha;
1923 for(i=0; i < ssize; i += step)
1929 r = image->comps[0].data[index];
1930 if(has_alpha) a = image->comps[1].data[index];
1935 if(has_alpha) a += adjust;
1939 r = (r<<ushift) + (r>>dshift);
1940 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1942 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1943 dat8[i+0] = (unsigned char)r;/*LSB*/
1944 dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1947 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1948 dat8[i+2] = (unsigned char)a;
1949 dat8[i+3] = (unsigned char)(a >> 8);
1952 }/*if(index < imgsize)*/
1957 (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1968 fprintf(stderr,"imagetotif: Bad color format.\n"
1969 "\tOnly RGB(A) and GRAY(A) has been implemented\n");
1970 fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
1977 * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
1978 * CINEMA : 12 bit precision
1980 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1982 int subsampling_dx = parameters->subsampling_dx;
1983 int subsampling_dy = parameters->subsampling_dy;
1988 int j, numcomps, w, h,index;
1989 OPJ_COLOR_SPACE color_space;
1990 opj_image_cmptparm_t cmptparm[4]; /* RGBA */
1991 opj_image_t *image = NULL;
1994 unsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;
1995 unsigned int tiWidth, tiHeight;
1996 OPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);
1998 tif = TIFFOpen(filename, "r");
2002 fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2005 tiBps = tiPhoto = tiSf = tiSpp = tiPC = 0;
2006 tiWidth = tiHeight = 0;
2008 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiWidth);
2009 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiHeight);
2010 TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiBps);
2011 TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &tiSf);
2012 TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
2013 TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
2014 TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
2018 if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
2019 if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
2021 if( !tiBps || !tiPhoto)
2024 fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
2025 " implemented\n",tiBps);
2028 fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2029 " and GRAY(A) has been implemented\n",(int) tiPhoto);
2031 fprintf(stderr,"\tAborting\n");
2037 {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2039 uint16 extrasamples;
2041 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2042 &extrasamples, &sampleinfo);
2044 if(extrasamples >= 1)
2046 switch(sampleinfo[0])
2048 case EXTRASAMPLE_UNSPECIFIED:
2049 /* Workaround for some images without correct info about alpha channel
2055 case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2056 case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2061 else /* extrasamples == 0 */
2062 if(tiSpp == 4 || tiSpp == 2) has_alpha = 1;
2065 /* initialize image components
2067 memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2069 if ((tiPhoto == PHOTOMETRIC_RGB) && (is_cinema)) {
2070 fprintf(stdout,"WARNING:\n"
2071 "Input image bitdepth is %d bits\n"
2072 "TIF conversion has automatically rescaled to 12-bits\n"
2073 "to comply with cinema profiles.\n",
2077 if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2079 numcomps = 3 + has_alpha;
2080 color_space = OPJ_CLRSPC_SRGB;
2082 /*#define USETILEMODE*/
2083 for(j = 0; j < numcomps; j++)
2087 cmptparm[j].prec = 12;
2088 cmptparm[j].bpp = 12;
2092 cmptparm[j].prec = tiBps;
2093 cmptparm[j].bpp = tiBps;
2095 cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2096 cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2097 cmptparm[j].w = (OPJ_UINT32)w;
2098 cmptparm[j].h = (OPJ_UINT32)h;
2106 image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2108 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2116 /* set image offset and reference grid
2118 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2119 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2120 image->x1 = !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2121 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2122 image->y1 = !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2123 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2125 buf = _TIFFmalloc(TIFFStripSize(tif));
2127 strip_size=TIFFStripSize(tif);
2129 imgsize = (int)(image->comps[0].w * image->comps[0].h);
2130 /* Read the Image components
2132 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2134 unsigned char *dat8;
2137 ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2138 dat8 = (unsigned char*)buf;
2142 step = 6 + has_alpha + has_alpha;
2144 for(i = 0; i < ssize; i += step)
2148 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2149 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2150 image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2152 image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2156 /* Rounding 16 to 12 bits
2158 image->comps[0].data[index] =
2159 (image->comps[0].data[index] + 0x08) >> 4 ;
2160 image->comps[1].data[index] =
2161 (image->comps[1].data[index] + 0x08) >> 4 ;
2162 image->comps[2].data[index] =
2163 (image->comps[2].data[index] + 0x08) >> 4 ;
2165 image->comps[3].data[index] =
2166 (image->comps[3].data[index] + 0x08) >> 4 ;
2173 }/*if(tiBps == 16)*/
2177 step = 3 + has_alpha;
2179 for(i = 0; i < ssize; i += step)
2184 image->comps[0].data[index] = dat8[i+0];/* R */
2185 image->comps[1].data[index] = dat8[i+1];/* G */
2186 image->comps[2].data[index] = dat8[i+2];/* B */
2188 image->comps[3].data[index] = dat8[i+3];
2193 /* Rounding 8 to 12 bits
2196 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2197 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2198 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2200 image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2208 }/*if( tiBps == 8)*/
2210 if(tiBps == 12)/* CINEMA file */
2214 for(i = 0; i < ssize; i += step)
2216 if((index < imgsize)&&(index+1 < imgsize))
2218 image->comps[0].data[index] = ( dat8[i+0]<<4 ) |(dat8[i+1]>>4);
2219 image->comps[1].data[index] = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2221 image->comps[2].data[index] = ( dat8[i+3]<<4) |(dat8[i+4]>>4);
2222 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2224 image->comps[1].data[index+1] = ( dat8[i+6] <<4) |(dat8[i+7]>>4);
2225 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2233 }/*for(strip = 0; )*/
2241 if(tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2243 numcomps = 1 + has_alpha;
2244 color_space = OPJ_CLRSPC_GRAY;
2246 for(j = 0; j < numcomps; ++j)
2248 cmptparm[j].prec = tiBps;
2249 cmptparm[j].bpp = tiBps;
2250 cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2251 cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2252 cmptparm[j].w = (OPJ_UINT32)w;
2253 cmptparm[j].h = (OPJ_UINT32)h;
2256 image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2258 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2266 /* set image offset and reference grid
2268 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2269 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2270 image->x1 = !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2271 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2272 image->y1 = !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2273 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2275 buf = _TIFFmalloc(TIFFStripSize(tif));
2277 strip_size = TIFFStripSize(tif);
2279 imgsize = (int)(image->comps[0].w * image->comps[0].h);
2280 /* Read the Image components
2282 for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2284 unsigned char *dat8;
2288 ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2289 dat8 = (unsigned char*)buf;
2293 step = 2 + has_alpha + has_alpha;
2295 for(i = 0; i < ssize; i += step)
2299 image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2301 image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2311 step = 1 + has_alpha;
2313 for(i = 0; i < ssize; i += step)
2317 image->comps[0].data[index] = dat8[i+0];
2319 image->comps[1].data[index] = dat8[i+1];
2337 #endif /* OPJ_HAVE_LIBTIFF */
2339 /* -->> -->> -->> -->>
2343 <<-- <<-- <<-- <<-- */
2344 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
2345 int subsampling_dx = parameters->subsampling_dx;
2346 int subsampling_dy = parameters->subsampling_dy;
2349 int i, compno, numcomps, w, h;
2350 OPJ_COLOR_SPACE color_space;
2351 opj_image_cmptparm_t *cmptparm;
2352 opj_image_t * image = NULL;
2355 if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2357 fprintf(stderr,"\nError: invalid raw image parameters\n");
2358 fprintf(stderr,"Please use the Format option -F:\n");
2359 fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2360 fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2361 fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2362 fprintf(stderr," for raw 512x512 image with 4:2:0 subsampling\n");
2363 fprintf(stderr,"Aborting.\n");
2367 f = fopen(filename, "rb");
2369 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2370 fprintf(stderr,"Aborting\n");
2373 numcomps = raw_cp->rawComp;
2375 /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2376 if (numcomps == 0) {
2377 color_space = OPJ_CLRSPC_GRAY;
2378 } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2379 color_space = OPJ_CLRSPC_SYCC;
2380 } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2381 color_space = OPJ_CLRSPC_SRGB;
2383 color_space = OPJ_CLRSPC_UNKNOWN;
2385 w = raw_cp->rawWidth;
2386 h = raw_cp->rawHeight;
2387 cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
2389 fprintf(stderr, "Failed to allocate image components parameters !!\n");
2390 fprintf(stderr,"Aborting\n");
2393 /* initialize image components */
2394 for(i = 0; i < numcomps; i++) {
2395 cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2396 cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2397 cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2398 cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2399 cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2400 cmptparm[i].w = (OPJ_UINT32)w;
2401 cmptparm[i].h = (OPJ_UINT32)h;
2403 /* create the image */
2404 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2410 /* set image offset and reference grid */
2411 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2412 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2413 image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2414 image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2416 if(raw_cp->rawBitDepth <= 8)
2418 unsigned char value = 0;
2419 for(compno = 0; compno < numcomps; compno++) {
2420 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2421 for (i = 0; i < nloop; i++) {
2422 if (!fread(&value, 1, 1, f)) {
2423 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2426 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2430 else if(raw_cp->rawBitDepth <= 16)
2432 unsigned short value;
2433 for(compno = 0; compno < numcomps; compno++) {
2434 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
2435 for (i = 0; i < nloop; i++) {
2436 unsigned char temp1;
2437 unsigned char temp2;
2438 if (!fread(&temp1, 1, 1, f)) {
2439 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2442 if (!fread(&temp2, 1, 1, f)) {
2443 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2448 value = (unsigned short)((temp1 << 8) + temp2);
2452 value = (unsigned short)((temp2 << 8) + temp1);
2454 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2459 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2463 if (fread(&ch, 1, 1, f)) {
2464 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2471 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2472 return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2475 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2476 return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2479 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
2481 FILE *rawFile = NULL;
2483 unsigned int compno;
2485 int line, row, curr, mask;
2490 if((image->numcomps * image->x1 * image->y1) == 0)
2492 fprintf(stderr,"\nError: invalid raw image parameters\n");
2496 rawFile = fopen(outfile, "wb");
2498 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2503 fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2505 for(compno = 0; compno < image->numcomps; compno++)
2507 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2508 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2510 w = (int)image->comps[compno].w;
2511 h = (int)image->comps[compno].h;
2513 if(image->comps[compno].prec <= 8)
2515 if(image->comps[compno].sgnd == 1)
2517 mask = (1 << image->comps[compno].prec) - 1;
2518 ptr = image->comps[compno].data;
2519 for (line = 0; line < h; line++) {
2520 for(row = 0; row < w; row++) {
2522 if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
2523 uc = (unsigned char) (curr & mask);
2524 res = fwrite(&uc, 1, 1, rawFile);
2526 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2533 else if(image->comps[compno].sgnd == 0)
2535 mask = (1 << image->comps[compno].prec) - 1;
2536 ptr = image->comps[compno].data;
2537 for (line = 0; line < h; line++) {
2538 for(row = 0; row < w; row++) {
2540 if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
2541 uc = (unsigned char) (curr & mask);
2542 res = fwrite(&uc, 1, 1, rawFile);
2544 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2552 else if(image->comps[compno].prec <= 16)
2554 if(image->comps[compno].sgnd == 1)
2556 union { signed short val; signed char vals[2]; } uc16;
2557 mask = (1 << image->comps[compno].prec) - 1;
2558 ptr = image->comps[compno].data;
2559 for (line = 0; line < h; line++) {
2560 for(row = 0; row < w; row++) {
2562 if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
2563 uc16.val = (signed short)(curr & mask);
2564 res = fwrite(uc16.vals, 1, 2, rawFile);
2566 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2573 else if(image->comps[compno].sgnd == 0)
2575 union { unsigned short val; unsigned char vals[2]; } uc16;
2576 mask = (1 << image->comps[compno].prec) - 1;
2577 ptr = image->comps[compno].data;
2578 for (line = 0; line < h; line++) {
2579 for(row = 0; row < w; row++) {
2581 if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
2582 uc16.val = (unsigned short)(curr & mask);
2583 res = fwrite(uc16.vals, 1, 2, rawFile);
2585 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2593 else if (image->comps[compno].prec <= 32)
2595 fprintf(stderr,"More than 16 bits per component no handled yet\n");
2600 fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2610 int imagetoraw(opj_image_t * image, const char *outfile)
2612 return imagetoraw_common(image, outfile, OPJ_TRUE);
2615 int imagetorawl(opj_image_t * image, const char *outfile)
2617 return imagetoraw_common(image, outfile, OPJ_FALSE);
2620 #ifdef OPJ_HAVE_LIBPNG
2622 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
2623 #define MAGIC_SIZE 8
2624 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
2626 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
2630 double gamma, display_exponent;
2631 int bit_depth, interlace_type,compression_type, filter_type;
2633 png_uint_32 resx, resy;
2635 png_uint_32 width, height;
2636 int color_type, has_alpha, is16;
2639 unsigned char **rows;
2642 opj_image_cmptparm_t cmptparm[4];
2644 unsigned int nr_comp;
2645 int *r, *g, *b, *a = NULL;
2646 unsigned char sigbuf[8];
2648 if((reader = fopen(read_idf, "rb")) == NULL)
2650 fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
2653 image = NULL; png = NULL; rows = NULL;
2655 if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
2656 || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
2658 fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
2661 /* libpng-VERSION/example.c:
2662 * PC : screen_gamma = 2.2;
2663 * Mac: screen_gamma = 1.7 or 1.0;
2665 display_exponent = 2.2;
2667 if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
2668 NULL, NULL, NULL)) == NULL)
2670 if((info = png_create_info_struct(png)) == NULL)
2673 if(setjmp(png_jmpbuf(png)))
2676 png_init_io(png, reader);
2677 png_set_sig_bytes(png, MAGIC_SIZE);
2679 png_read_info(png, info);
2681 if(png_get_IHDR(png, info, &width, &height,
2682 &bit_depth, &color_type, &interlace_type,
2683 &compression_type, &filter_type) == 0)
2686 /* png_set_expand():
2687 * expand paletted images to RGB, expand grayscale images of
2688 * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
2689 * to alpha channels.
2691 if(color_type == PNG_COLOR_TYPE_PALETTE)
2692 png_set_expand(png);
2694 if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
2695 png_set_expand(png);
2697 if(png_get_valid(png, info, PNG_INFO_tRNS))
2698 png_set_expand(png);
2700 is16 = (bit_depth == 16);
2702 /* GRAY => RGB; GRAY_ALPHA => RGBA
2704 if(color_type == PNG_COLOR_TYPE_GRAY
2705 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
2707 png_set_gray_to_rgb(png);
2709 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
2710 PNG_COLOR_TYPE_RGB_ALPHA);
2712 if( !png_get_gAMA(png, info, &gamma))
2715 png_set_gamma(png, display_exponent, gamma);
2717 png_read_update_info(png, info);
2719 png_get_pHYs(png, info, &resx, &resy, &unit);
2721 color_type = png_get_color_type(png, info);
2723 has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
2725 nr_comp = 3 + (unsigned int)has_alpha;
2727 bit_depth = png_get_bit_depth(png, info);
2729 rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
2730 for(i = 0; i < height; ++i)
2731 rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
2733 png_read_image(png, rows);
2735 memset(cmptparm, 0, sizeof(cmptparm));
2737 sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
2739 for(i = 0; i < nr_comp; ++i)
2741 cmptparm[i].prec = (OPJ_UINT32)bit_depth;
2742 /* bits_per_pixel: 8 or 16 */
2743 cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
2744 cmptparm[i].sgnd = 0;
2745 cmptparm[i].dx = (OPJ_UINT32)sub_dx;
2746 cmptparm[i].dy = (OPJ_UINT32)sub_dy;
2747 cmptparm[i].w = (OPJ_UINT32)width;
2748 cmptparm[i].h = (OPJ_UINT32)height;
2751 image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
2753 if(image == NULL) goto fin;
2755 image->x0 = (OPJ_UINT32)params->image_offset_x0;
2756 image->y0 = (OPJ_UINT32)params->image_offset_y0;
2757 image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
2758 image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
2760 r = image->comps[0].data;
2761 g = image->comps[1].data;
2762 b = image->comps[2].data;
2764 a = image->comps[3].data;
2765 image->comps[3].alpha = 1;
2768 for(i = 0; i < height; ++i)
2772 for(j = 0; j < width; ++j)
2776 *r++ = s[0]<<8|s[1]; s += 2;
2778 *g++ = s[0]<<8|s[1]; s += 2;
2780 *b++ = s[0]<<8|s[1]; s += 2;
2782 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
2786 *r++ = *s++; *g++ = *s++; *b++ = *s++;
2788 if(has_alpha) *a++ = *s++;
2794 for(i = 0; i < height; ++i)
2799 png_destroy_read_struct(&png, &info, NULL);
2807 int imagetopng(opj_image_t * image, const char *write_idf)
2812 int *red, *green, *blue, *alpha;
2813 unsigned char *row_buf, *d;
2814 int has_alpha, width, height, nr_comp, color_type;
2815 int adjustR, adjustG, adjustB, adjustA, x, y, fails;
2816 int prec, ushift, dshift, is16, force16, force8;
2817 unsigned short mask = 0xffff;
2818 png_color_8 sig_bit;
2820 is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
2821 prec = (int)image->comps[0].prec;
2822 nr_comp = (int)image->numcomps;
2824 if(prec > 8 && prec < 16)
2826 ushift = 16 - prec; dshift = prec - ushift;
2827 prec = 16; force16 = 1;
2830 if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
2832 ushift = 8 - prec; dshift = 8 - ushift;
2833 prec = 8; force8 = 1;
2836 if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
2838 fprintf(stderr,"imagetopng: can not create %s"
2839 "\n\twrong bit_depth %d\n", write_idf, prec);
2842 writer = fopen(write_idf, "wb");
2844 if(writer == NULL) return fails;
2846 info = NULL; has_alpha = 0;
2848 /* Create and initialize the png_struct with the desired error handler
2849 * functions. If you want to use the default stderr and longjump method,
2850 * you can supply NULL for the last three parameters. We also check that
2851 * the library version is compatible with the one used at compile time,
2852 * in case we are using dynamically linked libraries. REQUIRED.
2854 png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2856 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2858 if(png == NULL) goto fin;
2860 /* Allocate/initialize the image information data. REQUIRED
2862 info = png_create_info_struct(png);
2864 if(info == NULL) goto fin;
2866 /* Set error handling. REQUIRED if you are not supplying your own
2867 * error handling functions in the png_create_write_struct() call.
2869 if(setjmp(png_jmpbuf(png))) goto fin;
2871 /* I/O initialization functions is REQUIRED
2873 png_init_io(png, writer);
2875 /* Set the image information here. Width and height are up to 2^31,
2876 * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2877 * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2878 * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2879 * or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
2880 * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2881 * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
2886 * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
2887 * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
2888 * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
2889 * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
2892 png_set_compression_level(png, Z_BEST_COMPRESSION);
2894 if(prec == 16) mask = 0xffff;
2896 if(prec == 8) mask = 0x00ff;
2898 if(prec == 4) mask = 0x000f;
2900 if(prec == 2) mask = 0x0003;
2902 if(prec == 1) mask = 0x0001;
2905 && image->comps[0].dx == image->comps[1].dx
2906 && image->comps[1].dx == image->comps[2].dx
2907 && image->comps[0].dy == image->comps[1].dy
2908 && image->comps[1].dy == image->comps[2].dy
2909 && image->comps[0].prec == image->comps[1].prec
2910 && image->comps[1].prec == image->comps[2].prec)
2914 has_alpha = (nr_comp > 3);
2916 is16 = (prec == 16);
2918 width = (int)image->comps[0].w;
2919 height = (int)image->comps[0].h;
2921 red = image->comps[0].data;
2922 green = image->comps[1].data;
2923 blue = image->comps[2].data;
2925 sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
2929 sig_bit.alpha = (png_byte)prec;
2930 alpha = image->comps[3].data;
2931 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2932 adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
2936 sig_bit.alpha = 0; alpha = NULL;
2937 color_type = PNG_COLOR_TYPE_RGB;
2940 png_set_sBIT(png, info, &sig_bit);
2942 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
2945 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2947 png_set_gamma(png, 2.2, 1./2.2);
2948 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
2949 /*=============================*/
2950 png_write_info(png, info);
2951 /*=============================*/
2954 png_set_packing(png);
2956 printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
2957 image->comps[0].sgnd,
2958 image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
2960 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2961 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2962 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2964 row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
2966 for(y = 0; y < height; ++y)
2970 for(x = 0; x < width; ++x)
2974 v = *red + adjustR; ++red;
2975 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2977 if(force16) { v = (v<<ushift) + (v>>dshift); }
2979 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2981 v = *green + adjustG; ++green;
2982 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2984 if(force16) { v = (v<<ushift) + (v>>dshift); }
2986 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2988 v = *blue + adjustB; ++blue;
2989 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2991 if(force16) { v = (v<<ushift) + (v>>dshift); }
2993 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2997 v = *alpha + adjustA; ++alpha;
2998 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3000 if(force16) { v = (v<<ushift) + (v>>dshift); }
3002 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3007 v = *red + adjustR; ++red;
3008 if(v > 255) v = 255; else if(v < 0) v = 0;
3010 if(force8) { v = (v<<ushift) + (v>>dshift); }
3012 *d++ = (unsigned char)(v & mask);
3014 v = *green + adjustG; ++green;
3015 if(v > 255) v = 255; else if(v < 0) v = 0;
3017 if(force8) { v = (v<<ushift) + (v>>dshift); }
3019 *d++ = (unsigned char)(v & mask);
3021 v = *blue + adjustB; ++blue;
3022 if(v > 255) v = 255; else if(v < 0) v = 0;
3024 if(force8) { v = (v<<ushift) + (v>>dshift); }
3026 *d++ = (unsigned char)(v & mask);
3030 v = *alpha + adjustA; ++alpha;
3031 if(v > 255) v = 255; else if(v < 0) v = 0;
3033 if(force8) { v = (v<<ushift) + (v>>dshift); }
3035 *d++ = (unsigned char)(v & mask);
3039 png_write_row(png, row_buf);
3046 if(nr_comp == 1 /* GRAY */
3047 || ( nr_comp == 2 /* GRAY_ALPHA */
3048 && image->comps[0].dx == image->comps[1].dx
3049 && image->comps[0].dy == image->comps[1].dy
3050 && image->comps[0].prec == image->comps[1].prec))
3054 red = image->comps[0].data;
3056 sig_bit.gray = (png_byte)prec;
3057 sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3058 alpha = NULL; adjustA = 0;
3059 color_type = PNG_COLOR_TYPE_GRAY;
3063 has_alpha = 1; sig_bit.alpha = (png_byte)prec;
3064 alpha = image->comps[1].data;
3065 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3066 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3068 width = (int)image->comps[0].w;
3069 height = (int)image->comps[0].h;
3071 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
3074 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3076 png_set_sBIT(png, info, &sig_bit);
3078 png_set_gamma(png, 2.2, 1./2.2);
3079 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3080 /*=============================*/
3081 png_write_info(png, info);
3082 /*=============================*/
3083 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3087 png_set_packing(png);
3092 row_buf = (unsigned char*)
3093 malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
3095 for(y = 0; y < height; ++y)
3099 for(x = 0; x < width; ++x)
3101 v = *red + adjustR; ++red;
3102 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3104 if(force16) { v = (v<<ushift) + (v>>dshift); }
3106 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3111 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3113 if(force16) { v = (v<<ushift) + (v>>dshift); }
3115 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3118 png_write_row(png, row_buf);
3123 else /* prec <= 8 */
3125 row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
3127 for(y = 0; y < height; ++y)
3131 for(x = 0; x < width; ++x)
3133 v = *red + adjustR; ++red;
3134 if(v > 255) v = 255; else if(v < 0) v = 0;
3136 if(force8) { v = (v<<ushift) + (v>>dshift); }
3138 *d++ = (unsigned char)(v & mask);
3142 v = *alpha + adjustA; ++alpha;
3143 if(v > 255) v = 255; else if(v < 0) v = 0;
3145 if(force8) { v = (v<<ushift) + (v>>dshift); }
3147 *d++ = (unsigned char)(v & mask);
3151 png_write_row(png, row_buf);
3159 fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3162 png_write_end(png, info);
3170 png_destroy_write_struct(&png, &info);
3174 if(fails) remove(write_idf);
3178 #endif /* OPJ_HAVE_LIBPNG */