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 = (OPJ_INT64)(1U << (precision - 1));
112 OPJ_INT64 oldMax = (OPJ_INT64)(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 = (OPJ_UINT64)((1U << precision) - 1U);
119 OPJ_UINT64 oldMax = (OPJ_UINT64)((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->bpp = precision;
153 component->prec = precision;
157 /* -->> -->> -->> -->>
161 <<-- <<-- <<-- <<-- */
163 #ifdef INFORMATION_ONLY
164 /* TGA header definition. */
167 unsigned char id_length; /* Image id field length */
168 unsigned char colour_map_type; /* Colour map type */
169 unsigned char image_type; /* Image type */
171 ** Colour map specification
173 unsigned short colour_map_index; /* First entry index */
174 unsigned short colour_map_length; /* Colour map length */
175 unsigned char colour_map_entry_size; /* Colour map entry size */
177 ** Image specification
179 unsigned short x_origin; /* x origin of image */
180 unsigned short y_origin; /* u origin of image */
181 unsigned short image_width; /* Image width */
182 unsigned short image_height; /* Image height */
183 unsigned char pixel_depth; /* Pixel depth */
184 unsigned char image_desc; /* Image descriptor */
186 #endif /* INFORMATION_ONLY */
188 static unsigned short get_ushort(unsigned short val) {
190 #ifdef OPJ_BIG_ENDIAN
191 return( ((val & 0xff) << 8) + (val >> 8) );
198 #define TGA_HEADER_SIZE 18
200 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
201 unsigned int *width, unsigned int *height, int *flip_image)
205 unsigned char id_len, /*cmap_type,*/ image_type;
206 unsigned char pixel_depth, image_desc;
207 unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
208 unsigned short /*x_origin, y_origin,*/ image_w, image_h;
210 if (!bits_per_pixel || !width || !height || !flip_image)
212 tga = (unsigned char*)malloc(18);
214 if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
216 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
219 id_len = (unsigned char)tga[0];
220 /*cmap_type = (unsigned char)tga[1];*/
221 image_type = (unsigned char)tga[2];
222 /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
223 cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
224 cmap_entry_size = (unsigned char)tga[7];
228 x_origin = get_ushort(*(unsigned short*)(&tga[8]));
229 y_origin = get_ushort(*(unsigned short*)(&tga[10]));
231 image_w = get_ushort(*(unsigned short*)(&tga[12]));
232 image_h = get_ushort(*(unsigned short*)(&tga[14]));
233 pixel_depth = (unsigned char)tga[16];
234 image_desc = (unsigned char)tga[17];
238 *bits_per_pixel = (unsigned int)pixel_depth;
239 *width = (unsigned int)image_w;
240 *height = (unsigned int)image_h;
242 /* Ignore tga identifier, if present ... */
245 unsigned char *id = (unsigned char *) malloc(id_len);
246 if ( !fread(id, id_len, 1, fp) )
248 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
255 /* Test for compressed formats ... not yet supported ...
256 // Note :- 9 - RLE encoded palettized.
257 // 10 - RLE encoded RGB. */
260 fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
264 *flip_image = !(image_desc & 32);
266 /* Palettized formats are not yet supported, skip over the palette, if present ... */
267 palette_size = cmap_len * (cmap_entry_size/8);
271 fprintf(stderr, "File contains a palette - not yet supported.");
272 fseek(fp, palette_size, SEEK_CUR);
277 #ifdef OPJ_BIG_ENDIAN
279 static INLINE int16_t swap16(int16_t x)
281 return((((u_int16_t)x & 0x00ffU) << 8) |
282 (((u_int16_t)x & 0xff00U) >> 8));
287 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
290 unsigned short image_w, image_h, us0;
291 unsigned char uc0, image_type;
292 unsigned char pixel_depth, image_desc;
294 if (!bits_per_pixel || !width || !height)
299 if ( bits_per_pixel < 256 )
300 pixel_depth = (unsigned char)bits_per_pixel;
302 fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
307 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
308 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
310 image_type = 2; /* Uncompressed. */
311 if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
314 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
315 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
316 if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
318 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
319 if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
321 image_w = (unsigned short)width;
322 image_h = (unsigned short) height;
324 #ifndef OPJ_BIG_ENDIAN
325 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
326 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
328 image_w = swap16(image_w);
329 image_h = swap16(image_h);
330 if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
331 if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
334 if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
336 image_desc = 8; /* 8 bits per component. */
340 if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
345 fputs("\nwrite_tgaheader: write ERROR\n", stderr);
349 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
352 unsigned int image_width, image_height, pixel_bit_depth;
355 opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
357 OPJ_COLOR_SPACE color_space;
360 int subsampling_dx, subsampling_dy;
363 f = fopen(filename, "rb");
365 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
369 if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
372 /* We currently only support 24 & 32 bit tga's ... */
373 if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
376 /* initialize image components */
377 memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
379 mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16); /* Mono with & without alpha. */
380 save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
383 color_space = OPJ_CLRSPC_GRAY;
384 numcomps = save_alpha ? 2 : 1;
387 numcomps = save_alpha ? 4 : 3;
388 color_space = OPJ_CLRSPC_SRGB;
391 subsampling_dx = parameters->subsampling_dx;
392 subsampling_dy = parameters->subsampling_dy;
394 for (i = 0; i < numcomps; i++) {
395 cmptparm[i].prec = 8;
397 cmptparm[i].sgnd = 0;
398 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
399 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
400 cmptparm[i].w = image_width;
401 cmptparm[i].h = image_height;
404 /* create the image */
405 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
410 /* set image offset and reference grid */
411 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
412 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
413 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;
414 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;
417 for (y=0; y < image_height; y++)
422 index = (int)((image_height-y-1)*image_width);
424 index = (int)(y*image_width);
428 for (x=0;x<image_width;x++)
432 if( !fread(&b, 1, 1, f) )
434 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
435 opj_image_destroy(image);
438 if ( !fread(&g, 1, 1, f) )
440 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
441 opj_image_destroy(image);
444 if ( !fread(&r, 1, 1, f) )
446 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
447 opj_image_destroy(image);
451 image->comps[0].data[index]=r;
452 image->comps[1].data[index]=g;
453 image->comps[2].data[index]=b;
457 else if (numcomps==4)
459 for (x=0;x<image_width;x++)
461 unsigned char r,g,b,a;
462 if ( !fread(&b, 1, 1, f) )
464 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
465 opj_image_destroy(image);
468 if ( !fread(&g, 1, 1, f) )
470 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
471 opj_image_destroy(image);
474 if ( !fread(&r, 1, 1, f) )
476 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
477 opj_image_destroy(image);
480 if ( !fread(&a, 1, 1, f) )
482 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
483 opj_image_destroy(image);
487 image->comps[0].data[index]=r;
488 image->comps[1].data[index]=g;
489 image->comps[2].data[index]=b;
490 image->comps[3].data[index]=a;
495 fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
501 int imagetotga(opj_image_t * image, const char *outfile) {
502 int width, height, bpp, x, y;
503 OPJ_BOOL write_alpha;
505 int adjustR, adjustG, adjustB, fails;
506 unsigned int alpha_channel;
514 fdest = fopen(outfile, "wb");
516 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
520 for (i = 0; i < image->numcomps-1; i++) {
521 if ((image->comps[0].dx != image->comps[i+1].dx)
522 ||(image->comps[0].dy != image->comps[i+1].dy)
523 ||(image->comps[0].prec != image->comps[i+1].prec)) {
524 fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
529 width = (int)image->comps[0].w;
530 height = (int)image->comps[0].h;
532 /* Mono with alpha, or RGB with alpha. */
533 write_alpha = (image->numcomps==2) || (image->numcomps==4);
535 /* Write TGA header */
536 bpp = write_alpha ? 32 : 24;
538 if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
541 alpha_channel = image->numcomps-1;
543 scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
545 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
546 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
547 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
549 for (y=0; y < height; y++)
551 unsigned int index= (unsigned int)(y*width);
553 for (x=0; x < width; x++, index++)
555 r = (float)(image->comps[0].data[index] + adjustR);
557 if (image->numcomps > 2)
559 g = (float)(image->comps[1].data[index] + adjustG);
560 b = (float)(image->comps[2].data[index] + adjustB);
568 /* TGA format writes BGR ... */
569 if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
570 value = (unsigned char)(b*scale);
571 res = fwrite(&value,1,1,fdest);
575 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
578 if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
579 value = (unsigned char)(g*scale);
580 res = fwrite(&value,1,1,fdest);
584 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
587 if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
588 value = (unsigned char)(r*scale);
589 res = fwrite(&value,1,1,fdest);
593 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
599 a = (float)(image->comps[alpha_channel].data[index]);
600 if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
601 value = (unsigned char)(a*scale);
602 res = fwrite(&value,1,1,fdest);
606 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
619 /* -->> -->> -->> -->>
623 <<-- <<-- <<-- <<-- */
626 static unsigned char readuchar(FILE * f)
629 if ( !fread(&c1, 1, 1, f) )
631 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
637 static unsigned short readushort(FILE * f, int bigendian)
639 unsigned char c1, c2;
640 if ( !fread(&c1, 1, 1, f) )
642 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
645 if ( !fread(&c2, 1, 1, f) )
647 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
651 return (unsigned short)((c1 << 8) + c2);
653 return (unsigned short)((c2 << 8) + c1);
656 static unsigned int readuint(FILE * f, int bigendian)
658 unsigned char c1, c2, c3, c4;
659 if ( !fread(&c1, 1, 1, f) )
661 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
664 if ( !fread(&c2, 1, 1, f) )
666 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
669 if ( !fread(&c3, 1, 1, f) )
671 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
674 if ( !fread(&c4, 1, 1, f) )
676 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
680 return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
682 return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
685 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
688 int i, numcomps, max;
689 OPJ_COLOR_SPACE color_space;
690 opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
691 opj_image_t * image = NULL;
692 int adjustS, ushift, dshift, force8;
694 char endian1,endian2,sign;
699 opj_image_comp_t *comp = NULL;
702 color_space = OPJ_CLRSPC_GRAY;
704 memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
708 f = fopen(filename, "rb");
710 fprintf(stderr, "Failed to open %s for reading !\n", filename);
714 fseek(f, 0, SEEK_SET);
715 if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
716 fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
722 while (signtmp[i]!='\0') {
723 if (signtmp[i]=='-') sign='-';
728 if (endian1=='M' && endian2=='L') {
730 } else if (endian2=='M' && endian1=='L') {
733 fprintf(stderr, "Bad pgx header, please check input file\n");
737 /* initialize image component */
739 cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
740 cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
741 cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
742 cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
752 ushift = 8 - prec; dshift = prec - ushift;
753 if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
757 else ushift = dshift = force8 = adjustS = 0;
759 cmptparm.prec = (OPJ_UINT32)prec;
760 cmptparm.bpp = (OPJ_UINT32)prec;
761 cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
762 cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
764 /* create the image */
765 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
770 /* set image offset and reference grid */
771 image->x0 = cmptparm.x0;
772 image->y0 = cmptparm.x0;
773 image->x1 = cmptparm.w;
774 image->y1 = cmptparm.h;
778 comp = &image->comps[0];
780 for (i = 0; i < w * h; i++) {
784 v = readuchar(f) + adjustS;
785 v = (v<<ushift) + (v>>dshift);
786 comp->data[i] = (unsigned char)v;
792 if (comp->prec == 8) {
796 v = (char) readuchar(f);
798 } else if (comp->prec <= 16) {
800 v = readushort(f, bigendian);
802 v = (short) readushort(f, bigendian);
806 v = (int)readuint(f, bigendian);
808 v = (int) readuint(f, bigendian);
816 comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
821 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
823 static INLINE int clamp( const int value, const int prec, const int sgnd )
827 if (prec <= 8) return CLAMP(value,-128,127);
828 else if (prec <= 16) return CLAMP(value,-32768,32767);
829 else return CLAMP(value,-2147483647-1,2147483647);
833 if (prec <= 8) return CLAMP(value,0,255);
834 else if (prec <= 16) return CLAMP(value,0,65535);
835 else return value; /*CLAMP(value,0,4294967295);*/
839 int imagetopgx(opj_image_t * image, const char *outfile)
846 for (compno = 0; compno < image->numcomps; compno++)
848 opj_image_comp_t *comp = &image->comps[compno];
849 char bname[256]; /* buffer for name */
850 char *name = bname; /* pointer */
853 const size_t olen = strlen(outfile);
854 const size_t dotpos = olen - 4;
855 const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
857 if( outfile[dotpos] != '.' )
859 /* `pgx` was recognized but there is no dot at expected position */
860 fprintf(stderr, "ERROR -> Impossible happen." );
865 name = (char*)malloc(total+1);
867 strncpy(name, outfile, dotpos);
868 sprintf(name+dotpos, "_%d.pgx", compno);
869 fdest = fopen(name, "wb");
870 /* dont need name anymore */
871 if( total > 256 ) free(name);
874 fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
878 w = (int)image->comps[compno].w;
879 h = (int)image->comps[compno].h;
881 fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
886 else if (comp->prec <= 16)
891 for (i = 0; i < w * h; i++)
893 /* FIXME: clamp func is being called within a loop */
894 const int val = clamp(image->comps[compno].data[i],
895 (int)comp->prec, (int)comp->sgnd);
897 for (j = nbytes - 1; j >= 0; j--)
899 int v = (int)(val >> (j * 8));
900 unsigned char byte = (unsigned char)v;
901 res = fwrite(&byte, 1, 1, fdest);
905 fprintf(stderr, "failed to write 1 byte for %s\n", name);
910 fclose(fdest); fdest = NULL;
914 if(fdest) fclose(fdest);
919 /* -->> -->> -->> -->>
923 <<-- <<-- <<-- <<-- */
927 int width, height, maxval, depth, format;
928 char rgb, rgba, gray, graya, bw;
932 static char *skip_white(char *s)
936 if(*s == '\n' || *s == '\r') return NULL;
937 if(isspace(*s)) { ++s; continue; }
943 static char *skip_int(char *start, int *out_n)
948 *out_n = 0; s = start;
950 s = skip_white(start);
951 if(s == NULL) return NULL;
956 if( !isdigit(*s)) break;
959 c = *s; *s = 0; *out_n = atoi(start); *s = c;
963 static char *skip_idf(char *start, char out_idf[256])
968 s = skip_white(start);
969 if(s == NULL) return NULL;
974 if(isalpha(*s) || *s == '_') { ++s; continue; }
977 c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
981 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
983 int format, have_wh, end, ttype;
984 char idf[256], type[256];
987 if (fgets(line, 250, reader) == NULL)
989 fprintf(stderr,"\nWARNING: fgets return a NULL value");
995 fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
997 format = atoi(line + 1);
998 if(format < 1 || format > 7)
1000 fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1003 ph->format = format;
1004 ttype = end = have_wh = 0;
1006 while(fgets(line, 250, reader))
1010 if(*line == '#') continue;
1016 s = skip_idf(s, idf);
1018 if(s == NULL || *s == 0) return;
1020 if(strcmp(idf, "ENDHDR") == 0)
1024 if(strcmp(idf, "WIDTH") == 0)
1026 s = skip_int(s, &ph->width);
1027 if(s == NULL || *s == 0) return;
1031 if(strcmp(idf, "HEIGHT") == 0)
1033 s = skip_int(s, &ph->height);
1034 if(s == NULL || *s == 0) return;
1038 if(strcmp(idf, "DEPTH") == 0)
1040 s = skip_int(s, &ph->depth);
1041 if(s == NULL || *s == 0) return;
1045 if(strcmp(idf, "MAXVAL") == 0)
1047 s = skip_int(s, &ph->maxval);
1048 if(s == NULL || *s == 0) return;
1052 if(strcmp(idf, "TUPLTYPE") == 0)
1054 s = skip_idf(s, type);
1055 if(s == NULL || *s == 0) return;
1057 if(strcmp(type, "BLACKANDWHITE") == 0)
1059 ph->bw = 1; ttype = 1; continue;
1061 if(strcmp(type, "GRAYSCALE") == 0)
1063 ph->gray = 1; ttype = 1; continue;
1065 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1067 ph->graya = 1; ttype = 1; continue;
1069 if(strcmp(type, "RGB") == 0)
1071 ph->rgb = 1; ttype = 1; continue;
1073 if(strcmp(type, "RGB_ALPHA") == 0)
1075 ph->rgba = 1; ttype = 1; continue;
1077 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1080 fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1082 } /* if(format == 7) */
1086 s = skip_int(s, &ph->width);
1088 s = skip_int(s, &ph->height);
1092 if(format == 1 || format == 4) break;
1094 if(format == 2 || format == 3 || format == 5 || format == 6)
1096 if (skip_int(s, &ph->maxval) != NULL) {
1097 if(ph->maxval > 65535) {
1107 if(format == 2 || format == 3 || format == 5 || format == 6)
1109 /* P2, P3, P5, P6: */
1110 s = skip_int(s, &ph->maxval);
1112 if(ph->maxval > 65535) return;
1115 }/* while(fgets( ) */
1116 if(format == 2 || format == 3 || format > 4)
1118 if(ph->maxval < 1 || ph->maxval > 65535) return;
1120 if(ph->width < 1 || ph->height < 1) return;
1126 fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1128 if(ph->depth < 1 || ph->depth > 4) return;
1130 if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1135 if(format != 1 && format != 4)
1137 if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1141 if(ph->width && ph->height) ph->ok = 1;
1147 static int has_prec(int val)
1149 if(val < 2) return 1;
1150 if(val < 4) return 2;
1151 if(val < 8) return 3;
1152 if(val < 16) return 4;
1153 if(val < 32) return 5;
1154 if(val < 64) return 6;
1155 if(val < 128) return 7;
1156 if(val < 256) return 8;
1157 if(val < 512) return 9;
1158 if(val < 1024) return 10;
1159 if(val < 2048) return 11;
1160 if(val < 4096) return 12;
1161 if(val < 8192) return 13;
1162 if(val < 16384) return 14;
1163 if(val < 32768) return 15;
1167 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1168 int subsampling_dx = parameters->subsampling_dx;
1169 int subsampling_dy = parameters->subsampling_dy;
1172 int i, compno, numcomps, w, h, prec, format;
1173 OPJ_COLOR_SPACE color_space;
1174 opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1175 opj_image_t * image = NULL;
1176 struct pnm_header header_info;
1178 if((fp = fopen(filename, "rb")) == NULL)
1180 fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1183 memset(&header_info, 0, sizeof(struct pnm_header));
1185 read_pnm_header(fp, &header_info);
1187 if(!header_info.ok) { fclose(fp); return NULL; }
1189 format = header_info.format;
1193 case 1: /* ascii bitmap */
1194 case 4: /* raw bitmap */
1198 case 2: /* ascii greymap */
1199 case 5: /* raw greymap */
1203 case 3: /* ascii pixmap */
1204 case 6: /* raw pixmap */
1208 case 7: /* arbitrary map */
1209 numcomps = header_info.depth;
1212 default: fclose(fp); return NULL;
1215 color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1217 color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1219 prec = has_prec(header_info.maxval);
1221 if(prec < 8) prec = 8;
1223 w = header_info.width;
1224 h = header_info.height;
1225 subsampling_dx = parameters->subsampling_dx;
1226 subsampling_dy = parameters->subsampling_dy;
1228 memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1230 for(i = 0; i < numcomps; i++)
1232 cmptparm[i].prec = (OPJ_UINT32)prec;
1233 cmptparm[i].bpp = (OPJ_UINT32)prec;
1234 cmptparm[i].sgnd = 0;
1235 cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1236 cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1237 cmptparm[i].w = (OPJ_UINT32)w;
1238 cmptparm[i].h = (OPJ_UINT32)h;
1240 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1242 if(!image) { fclose(fp); return NULL; }
1244 /* set image offset and reference grid */
1245 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1246 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1247 image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1248 image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1250 if((format == 2) || (format == 3)) /* ascii pixmap */
1254 for (i = 0; i < w * h; i++)
1256 for(compno = 0; compno < numcomps; compno++)
1259 if (fscanf(fp, "%u", &index) != 1)
1260 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1262 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1270 && ( header_info.gray || header_info.graya
1271 || header_info.rgb || header_info.rgba)))/* binary pixmap */
1273 unsigned char c0, c1, one;
1277 for (i = 0; i < w * h; i++)
1279 for(compno = 0; compno < numcomps; compno++)
1281 if ( !fread(&c0, 1, 1, fp) )
1283 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1284 opj_image_destroy(image);
1289 image->comps[compno].data[i] = c0;
1293 if ( !fread(&c1, 1, 1, fp) )
1294 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1296 image->comps[compno].data[i] = ((c0<<8) | c1);
1302 if(format == 1) /* ascii bitmap */
1304 for (i = 0; i < w * h; i++)
1308 if ( fscanf(fp, "%u", &index) != 1)
1309 fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1311 image->comps[0].data[i] = (index?0:255);
1321 for(y = 0; y < h; ++y)
1325 for(x = 0; x < w; ++x)
1330 uc = (unsigned char)getc(fp);
1332 image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1338 if((format == 7 && header_info.bw)) /*MONO*/
1342 for(i = 0; i < w * h; ++i)
1344 if ( !fread(&uc, 1, 1, fp) )
1345 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1346 image->comps[0].data[i] = (uc & 1)?0:255;
1354 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1356 int *red, *green, *blue, *alpha;
1359 unsigned int compno, ncomp;
1360 int adjustR, adjustG, adjustB, adjustA;
1361 int fails, two, want_gray, has_alpha, triple;
1364 const char *tmp = outfile;
1369 if((prec = (int)image->comps[0].prec) > 16)
1371 fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1372 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1375 two = has_alpha = 0; fails = 1;
1376 ncomp = image->numcomps;
1378 while (*tmp) ++tmp; tmp -= 2;
1379 want_gray = (*tmp == 'g' || *tmp == 'G');
1380 ncomp = image->numcomps;
1382 if(want_gray) ncomp = 1;
1384 if ((force_split == 0) &&
1385 (ncomp == 2 /* GRAYA */
1386 || (ncomp > 2 /* RGB, RGBA */
1387 && image->comps[0].dx == image->comps[1].dx
1388 && image->comps[1].dx == image->comps[2].dx
1389 && image->comps[0].dy == image->comps[1].dy
1390 && image->comps[1].dy == image->comps[2].dy
1391 && image->comps[0].prec == image->comps[1].prec
1392 && image->comps[1].prec == image->comps[2].prec
1395 fdest = fopen(outfile, "wb");
1399 fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1403 triple = (ncomp > 2);
1404 wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1405 max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1407 red = image->comps[0].data;
1411 green = image->comps[1].data;
1412 blue = image->comps[2].data;
1414 else green = blue = NULL;
1418 const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1420 fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1421 "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1422 wr, hr, ncomp, max, tt);
1423 alpha = image->comps[ncomp - 1].data;
1424 adjustA = (image->comps[ncomp - 1].sgnd ?
1425 1 << (image->comps[ncomp - 1].prec - 1) : 0);
1429 fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1430 opj_version(), wr, hr, max);
1433 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1437 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1438 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1440 else adjustG = adjustB = 0;
1442 for(i = 0; i < wr * hr; ++i)
1446 v = *red + adjustR; ++red;
1447 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1450 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1454 v = *green + adjustG; ++green;
1455 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1458 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1460 v = *blue + adjustB; ++blue;
1461 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1464 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1470 v = *alpha + adjustA; ++alpha;
1471 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1474 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1482 if(v > 255) v = 255; else if(v < 0) v = 0;
1484 fprintf(fdest, "%c", (unsigned char)v);
1488 if(v > 255) v = 255; else if(v < 0) v = 0;
1490 fprintf(fdest, "%c", (unsigned char)v);
1492 if(v > 255) v = 255; else if(v < 0) v = 0;
1494 fprintf(fdest, "%c", (unsigned char)v);
1499 if(v > 255) v = 255; else if(v < 0) v = 0;
1501 fprintf(fdest, "%c", (unsigned char)v);
1505 fclose(fdest); return 0;
1510 if (image->numcomps > ncomp)
1512 fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1513 fprintf(stderr," is written to the file\n");
1515 destname = (char*)malloc(strlen(outfile) + 8);
1517 for (compno = 0; compno < ncomp; compno++)
1521 /*sprintf(destname, "%d.%s", compno, outfile);*/
1522 const size_t olen = strlen(outfile);
1523 const size_t dotpos = olen - 4;
1525 strncpy(destname, outfile, dotpos);
1526 sprintf(destname+dotpos, "_%d.pgm", compno);
1529 sprintf(destname, "%s", outfile);
1531 fdest = fopen(destname, "wb");
1534 fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1538 wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1539 prec = (int)image->comps[compno].prec;
1540 max = (1<<prec) - 1;
1542 fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1543 opj_version(), wr, hr, max);
1545 red = image->comps[compno].data;
1547 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1551 for (i = 0; i < wr * hr; i++)
1553 v = *red + adjustR; ++red;
1554 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1557 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1562 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1565 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1569 else /* prec <= 8 */
1571 for(i = 0; i < wr * hr; ++i)
1573 v = *red + adjustR; ++red;
1574 if(v > 255) v = 255; else if(v < 0) v = 0;
1576 fprintf(fdest, "%c", (unsigned char)v);
1586 /* -->> -->> -->> -->>
1590 <<-- <<-- <<-- <<-- */
1591 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
1592 int subsampling_dx = parameters->subsampling_dx;
1593 int subsampling_dy = parameters->subsampling_dy;
1596 int i, compno, numcomps, w, h;
1597 OPJ_COLOR_SPACE color_space;
1598 opj_image_cmptparm_t *cmptparm;
1599 opj_image_t * image = NULL;
1602 if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
1604 fprintf(stderr,"\nError: invalid raw image parameters\n");
1605 fprintf(stderr,"Please use the Format option -F:\n");
1606 fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
1607 fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
1608 fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
1609 fprintf(stderr," for raw 512x512 image with 4:2:0 subsampling\n");
1610 fprintf(stderr,"Aborting.\n");
1614 f = fopen(filename, "rb");
1616 fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1617 fprintf(stderr,"Aborting\n");
1620 numcomps = raw_cp->rawComp;
1622 /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
1623 if (numcomps == 1) {
1624 color_space = OPJ_CLRSPC_GRAY;
1625 } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
1626 color_space = OPJ_CLRSPC_SYCC;
1627 } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
1628 color_space = OPJ_CLRSPC_SRGB;
1630 color_space = OPJ_CLRSPC_UNKNOWN;
1632 w = raw_cp->rawWidth;
1633 h = raw_cp->rawHeight;
1634 cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
1636 fprintf(stderr, "Failed to allocate image components parameters !!\n");
1637 fprintf(stderr,"Aborting\n");
1640 /* initialize image components */
1641 for(i = 0; i < numcomps; i++) {
1642 cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
1643 cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
1644 cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
1645 cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
1646 cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
1647 cmptparm[i].w = (OPJ_UINT32)w;
1648 cmptparm[i].h = (OPJ_UINT32)h;
1650 /* create the image */
1651 image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1657 /* set image offset and reference grid */
1658 image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1659 image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1660 image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
1661 image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
1663 if(raw_cp->rawBitDepth <= 8)
1665 unsigned char value = 0;
1666 for(compno = 0; compno < numcomps; compno++) {
1667 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
1668 for (i = 0; i < nloop; i++) {
1669 if (!fread(&value, 1, 1, f)) {
1670 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1673 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
1677 else if(raw_cp->rawBitDepth <= 16)
1679 unsigned short value;
1680 for(compno = 0; compno < numcomps; compno++) {
1681 int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
1682 for (i = 0; i < nloop; i++) {
1683 unsigned char temp1;
1684 unsigned char temp2;
1685 if (!fread(&temp1, 1, 1, f)) {
1686 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1689 if (!fread(&temp2, 1, 1, f)) {
1690 fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1695 value = (unsigned short)((temp1 << 8) + temp2);
1699 value = (unsigned short)((temp2 << 8) + temp1);
1701 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
1706 fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
1710 if (fread(&ch, 1, 1, f)) {
1711 fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
1718 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1719 return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
1722 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1723 return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
1726 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
1728 FILE *rawFile = NULL;
1730 unsigned int compno;
1732 int line, row, curr, mask;
1737 if((image->numcomps * image->x1 * image->y1) == 0)
1739 fprintf(stderr,"\nError: invalid raw image parameters\n");
1743 rawFile = fopen(outfile, "wb");
1745 fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
1750 fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
1752 for(compno = 0; compno < image->numcomps; compno++)
1754 fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
1755 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
1757 w = (int)image->comps[compno].w;
1758 h = (int)image->comps[compno].h;
1760 if(image->comps[compno].prec <= 8)
1762 if(image->comps[compno].sgnd == 1)
1764 mask = (1 << image->comps[compno].prec) - 1;
1765 ptr = image->comps[compno].data;
1766 for (line = 0; line < h; line++) {
1767 for(row = 0; row < w; row++) {
1769 if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
1770 uc = (unsigned char) (curr & mask);
1771 res = fwrite(&uc, 1, 1, rawFile);
1773 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1780 else if(image->comps[compno].sgnd == 0)
1782 mask = (1 << image->comps[compno].prec) - 1;
1783 ptr = image->comps[compno].data;
1784 for (line = 0; line < h; line++) {
1785 for(row = 0; row < w; row++) {
1787 if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
1788 uc = (unsigned char) (curr & mask);
1789 res = fwrite(&uc, 1, 1, rawFile);
1791 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1799 else if(image->comps[compno].prec <= 16)
1801 if(image->comps[compno].sgnd == 1)
1803 union { signed short val; signed char vals[2]; } uc16;
1804 mask = (1 << image->comps[compno].prec) - 1;
1805 ptr = image->comps[compno].data;
1806 for (line = 0; line < h; line++) {
1807 for(row = 0; row < w; row++) {
1809 if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
1810 uc16.val = (signed short)(curr & mask);
1811 res = fwrite(uc16.vals, 1, 2, rawFile);
1813 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
1820 else if(image->comps[compno].sgnd == 0)
1822 union { unsigned short val; unsigned char vals[2]; } uc16;
1823 mask = (1 << image->comps[compno].prec) - 1;
1824 ptr = image->comps[compno].data;
1825 for (line = 0; line < h; line++) {
1826 for(row = 0; row < w; row++) {
1828 if(curr > 65535 ) curr = 65535; else if( curr < 0) curr = 0;
1829 uc16.val = (unsigned short)(curr & mask);
1830 res = fwrite(uc16.vals, 1, 2, rawFile);
1832 fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
1840 else if (image->comps[compno].prec <= 32)
1842 fprintf(stderr,"More than 16 bits per component no handled yet\n");
1847 fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
1857 int imagetoraw(opj_image_t * image, const char *outfile)
1859 return imagetoraw_common(image, outfile, OPJ_TRUE);
1862 int imagetorawl(opj_image_t * image, const char *outfile)
1864 return imagetoraw_common(image, outfile, OPJ_FALSE);
1867 #ifdef OPJ_HAVE_LIBPNG
1869 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
1870 #define MAGIC_SIZE 8
1871 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
1873 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
1877 double gamma, display_exponent;
1878 int bit_depth, interlace_type,compression_type, filter_type;
1880 png_uint_32 resx, resy;
1882 png_uint_32 width, height;
1883 int color_type, has_alpha, is16;
1886 unsigned char **rows;
1889 opj_image_cmptparm_t cmptparm[4];
1891 unsigned int nr_comp;
1892 int *r, *g, *b, *a = NULL;
1893 unsigned char sigbuf[8];
1895 if((reader = fopen(read_idf, "rb")) == NULL)
1897 fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
1900 image = NULL; png = NULL; rows = NULL;
1902 if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
1903 || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
1905 fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
1908 /* libpng-VERSION/example.c:
1909 * PC : screen_gamma = 2.2;
1910 * Mac: screen_gamma = 1.7 or 1.0;
1912 display_exponent = 2.2;
1914 if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
1915 NULL, NULL, NULL)) == NULL)
1917 if((info = png_create_info_struct(png)) == NULL)
1920 if(setjmp(png_jmpbuf(png)))
1923 png_init_io(png, reader);
1924 png_set_sig_bytes(png, MAGIC_SIZE);
1926 png_read_info(png, info);
1928 if(png_get_IHDR(png, info, &width, &height,
1929 &bit_depth, &color_type, &interlace_type,
1930 &compression_type, &filter_type) == 0)
1933 /* png_set_expand():
1934 * expand paletted images to RGB, expand grayscale images of
1935 * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
1936 * to alpha channels.
1938 if(color_type == PNG_COLOR_TYPE_PALETTE)
1939 png_set_expand(png);
1941 if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
1942 png_set_expand(png);
1944 if(png_get_valid(png, info, PNG_INFO_tRNS))
1945 png_set_expand(png);
1947 is16 = (bit_depth == 16);
1949 /* GRAY => RGB; GRAY_ALPHA => RGBA
1951 if(color_type == PNG_COLOR_TYPE_GRAY
1952 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
1954 png_set_gray_to_rgb(png);
1956 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
1957 PNG_COLOR_TYPE_RGB_ALPHA);
1959 if( !png_get_gAMA(png, info, &gamma))
1962 png_set_gamma(png, display_exponent, gamma);
1964 png_read_update_info(png, info);
1966 png_get_pHYs(png, info, &resx, &resy, &unit);
1968 color_type = png_get_color_type(png, info);
1970 has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
1972 nr_comp = 3 + (unsigned int)has_alpha;
1974 bit_depth = png_get_bit_depth(png, info);
1976 rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
1977 for(i = 0; i < height; ++i)
1978 rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
1980 png_read_image(png, rows);
1982 memset(cmptparm, 0, sizeof(cmptparm));
1984 sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
1986 for(i = 0; i < nr_comp; ++i)
1988 cmptparm[i].prec = (OPJ_UINT32)bit_depth;
1989 /* bits_per_pixel: 8 or 16 */
1990 cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
1991 cmptparm[i].sgnd = 0;
1992 cmptparm[i].dx = (OPJ_UINT32)sub_dx;
1993 cmptparm[i].dy = (OPJ_UINT32)sub_dy;
1994 cmptparm[i].w = (OPJ_UINT32)width;
1995 cmptparm[i].h = (OPJ_UINT32)height;
1998 image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
2000 if(image == NULL) goto fin;
2002 image->x0 = (OPJ_UINT32)params->image_offset_x0;
2003 image->y0 = (OPJ_UINT32)params->image_offset_y0;
2004 image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
2005 image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
2007 r = image->comps[0].data;
2008 g = image->comps[1].data;
2009 b = image->comps[2].data;
2011 a = image->comps[3].data;
2012 image->comps[3].alpha = 1;
2015 for(i = 0; i < height; ++i)
2019 for(j = 0; j < width; ++j)
2023 *r++ = s[0]<<8|s[1]; s += 2;
2025 *g++ = s[0]<<8|s[1]; s += 2;
2027 *b++ = s[0]<<8|s[1]; s += 2;
2029 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
2033 *r++ = *s++; *g++ = *s++; *b++ = *s++;
2035 if(has_alpha) *a++ = *s++;
2041 for(i = 0; i < height; ++i)
2046 png_destroy_read_struct(&png, &info, NULL);
2054 int imagetopng(opj_image_t * image, const char *write_idf)
2059 int *red, *green, *blue, *alpha;
2060 unsigned char *row_buf, *d;
2061 int has_alpha, width, height, nr_comp, color_type;
2062 int adjustR, adjustG, adjustB, adjustA, x, y, fails;
2063 int prec, ushift, dshift, is16, force16, force8;
2064 unsigned short mask = 0xffff;
2065 png_color_8 sig_bit;
2067 is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
2068 prec = (int)image->comps[0].prec;
2069 nr_comp = (int)image->numcomps;
2071 if(prec > 8 && prec < 16)
2073 ushift = 16 - prec; dshift = prec - ushift;
2074 prec = 16; force16 = 1;
2077 if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
2079 ushift = 8 - prec; dshift = 8 - ushift;
2080 prec = 8; force8 = 1;
2083 if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
2085 fprintf(stderr,"imagetopng: can not create %s"
2086 "\n\twrong bit_depth %d\n", write_idf, prec);
2089 writer = fopen(write_idf, "wb");
2091 if(writer == NULL) return fails;
2093 info = NULL; has_alpha = 0;
2095 /* Create and initialize the png_struct with the desired error handler
2096 * functions. If you want to use the default stderr and longjump method,
2097 * you can supply NULL for the last three parameters. We also check that
2098 * the library version is compatible with the one used at compile time,
2099 * in case we are using dynamically linked libraries. REQUIRED.
2101 png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2103 /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2105 if(png == NULL) goto fin;
2107 /* Allocate/initialize the image information data. REQUIRED
2109 info = png_create_info_struct(png);
2111 if(info == NULL) goto fin;
2113 /* Set error handling. REQUIRED if you are not supplying your own
2114 * error handling functions in the png_create_write_struct() call.
2116 if(setjmp(png_jmpbuf(png))) goto fin;
2118 /* I/O initialization functions is REQUIRED
2120 png_init_io(png, writer);
2122 /* Set the image information here. Width and height are up to 2^31,
2123 * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2124 * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2125 * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2126 * or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
2127 * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2128 * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
2133 * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
2134 * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
2135 * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
2136 * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
2139 png_set_compression_level(png, Z_BEST_COMPRESSION);
2141 if(prec == 16) mask = 0xffff;
2143 if(prec == 8) mask = 0x00ff;
2145 if(prec == 4) mask = 0x000f;
2147 if(prec == 2) mask = 0x0003;
2149 if(prec == 1) mask = 0x0001;
2152 && image->comps[0].dx == image->comps[1].dx
2153 && image->comps[1].dx == image->comps[2].dx
2154 && image->comps[0].dy == image->comps[1].dy
2155 && image->comps[1].dy == image->comps[2].dy
2156 && image->comps[0].prec == image->comps[1].prec
2157 && image->comps[1].prec == image->comps[2].prec)
2161 has_alpha = (nr_comp > 3);
2163 is16 = (prec == 16);
2165 width = (int)image->comps[0].w;
2166 height = (int)image->comps[0].h;
2168 red = image->comps[0].data;
2169 green = image->comps[1].data;
2170 blue = image->comps[2].data;
2172 sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
2176 sig_bit.alpha = (png_byte)prec;
2177 alpha = image->comps[3].data;
2178 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2179 adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
2183 sig_bit.alpha = 0; alpha = NULL;
2184 color_type = PNG_COLOR_TYPE_RGB;
2187 png_set_sBIT(png, info, &sig_bit);
2189 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
2192 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2194 png_set_gamma(png, 2.2, 1./2.2);
2195 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
2196 /*=============================*/
2197 png_write_info(png, info);
2198 /*=============================*/
2201 png_set_packing(png);
2203 // printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
2204 //image->comps[0].sgnd,
2205 //image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
2207 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2208 adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2209 adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2211 row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
2213 for(y = 0; y < height; ++y)
2217 for(x = 0; x < width; ++x)
2221 v = *red + adjustR; ++red;
2222 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2224 if(force16) { v = (v<<ushift) + (v>>dshift); }
2226 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2228 v = *green + adjustG; ++green;
2229 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2231 if(force16) { v = (v<<ushift) + (v>>dshift); }
2233 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2235 v = *blue + adjustB; ++blue;
2236 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2238 if(force16) { v = (v<<ushift) + (v>>dshift); }
2240 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2244 v = *alpha + adjustA; ++alpha;
2245 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2247 if(force16) { v = (v<<ushift) + (v>>dshift); }
2249 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2254 v = *red + adjustR; ++red;
2255 if(v > 255) v = 255; else if(v < 0) v = 0;
2257 if(force8) { v = (v<<ushift) + (v>>dshift); }
2259 *d++ = (unsigned char)(v & mask);
2261 v = *green + adjustG; ++green;
2262 if(v > 255) v = 255; else if(v < 0) v = 0;
2264 if(force8) { v = (v<<ushift) + (v>>dshift); }
2266 *d++ = (unsigned char)(v & mask);
2268 v = *blue + adjustB; ++blue;
2269 if(v > 255) v = 255; else if(v < 0) v = 0;
2271 if(force8) { v = (v<<ushift) + (v>>dshift); }
2273 *d++ = (unsigned char)(v & mask);
2277 v = *alpha + adjustA; ++alpha;
2278 if(v > 255) v = 255; else if(v < 0) v = 0;
2280 if(force8) { v = (v<<ushift) + (v>>dshift); }
2282 *d++ = (unsigned char)(v & mask);
2286 png_write_row(png, row_buf);
2293 if(nr_comp == 1 /* GRAY */
2294 || ( nr_comp == 2 /* GRAY_ALPHA */
2295 && image->comps[0].dx == image->comps[1].dx
2296 && image->comps[0].dy == image->comps[1].dy
2297 && image->comps[0].prec == image->comps[1].prec))
2301 red = image->comps[0].data;
2303 sig_bit.gray = (png_byte)prec;
2304 sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
2305 alpha = NULL; adjustA = 0;
2306 color_type = PNG_COLOR_TYPE_GRAY;
2310 has_alpha = 1; sig_bit.alpha = (png_byte)prec;
2311 alpha = image->comps[1].data;
2312 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
2313 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2315 width = (int)image->comps[0].w;
2316 height = (int)image->comps[0].h;
2318 png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
2321 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2323 png_set_sBIT(png, info, &sig_bit);
2325 png_set_gamma(png, 2.2, 1./2.2);
2326 png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
2327 /*=============================*/
2328 png_write_info(png, info);
2329 /*=============================*/
2330 adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2334 png_set_packing(png);
2339 row_buf = (unsigned char*)
2340 malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
2342 for(y = 0; y < height; ++y)
2346 for(x = 0; x < width; ++x)
2348 v = *red + adjustR; ++red;
2349 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2351 if(force16) { v = (v<<ushift) + (v>>dshift); }
2353 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2358 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2360 if(force16) { v = (v<<ushift) + (v>>dshift); }
2362 *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2365 png_write_row(png, row_buf);
2370 else /* prec <= 8 */
2372 row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
2374 for(y = 0; y < height; ++y)
2378 for(x = 0; x < width; ++x)
2380 v = *red + adjustR; ++red;
2381 if(v > 255) v = 255; else if(v < 0) v = 0;
2383 if(force8) { v = (v<<ushift) + (v>>dshift); }
2385 *d++ = (unsigned char)(v & mask);
2389 v = *alpha + adjustA; ++alpha;
2390 if(v > 255) v = 255; else if(v < 0) v = 0;
2392 if(force8) { v = (v<<ushift) + (v>>dshift); }
2394 *d++ = (unsigned char)(v & mask);
2398 png_write_row(png, row_buf);
2406 fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
2409 png_write_end(png, info);
2417 png_destroy_write_struct(&png, &info);
2421 if(fails) remove(write_idf);
2425 #endif /* OPJ_HAVE_LIBPNG */