File: png_support.hpp

package info (click to toggle)
gamera 1%3A3.4.2%2Bgit20160808.1725654-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,312 kB
  • ctags: 24,991
  • sloc: xml: 122,324; ansic: 52,869; cpp: 50,664; python: 35,034; makefile: 118; sh: 101
file content (496 lines) | stat: -rw-r--r-- 14,771 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 *
 * Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom, Karl MacMillan
 *               2015      Christoph Dalitz
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 Resolution support graciously donated by Damon Li.
*/

#ifndef mgd_png_support
#define mgd_png_support

#include "image_utilities.hpp"
#include <png.h>
#include <stdio.h>
#include <stdint.h>

// TODO: Get/Save resolution information

using namespace Gamera;

#define PNG_BYTES_TO_CHECK 8
#define METER_PER_INCH 0.0254

void PNG_info_specific(const char* filename, FILE* & fp, png_structp& png_ptr, png_infop& info_ptr, png_infop& end_info, png_uint_32& width, png_uint_32& height, int& bit_depth, int& color_type, double& x_resolution, double& y_resolution) {
  fp = fopen(filename, "rb");
  if (!fp)
    throw std::invalid_argument("Failed to open image");

  // Check if a PNG file
  char buf[PNG_BYTES_TO_CHECK];
  if (fread(buf, 1, PNG_BYTES_TO_CHECK, fp) != PNG_BYTES_TO_CHECK) {
    fclose(fp);
    throw std::runtime_error("Image file too small");
  }
  if (png_sig_cmp((png_byte*)buf, 0, PNG_BYTES_TO_CHECK)) {
    fclose(fp);
    throw std::runtime_error("Not a PNG file");
  }
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
                   NULL, NULL);
  if (!png_ptr) {
    fclose(fp);
    throw std::runtime_error("Could not read PNG header");
  }

  info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
    fclose(fp);
    throw std::runtime_error("Could not read PNG info");
  }
  
  end_info = png_create_info_struct(png_ptr);
  if (!end_info) {
    png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
    fclose(fp);
    throw std::runtime_error("Could not read PNG info");
  }

  if (setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
    fclose(fp);
    throw std::runtime_error("error in reading PNG header");
  }

  png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK);

  // Initialize IO
  png_init_io(png_ptr, fp);

  // Read in info
  png_read_info(png_ptr, info_ptr);

  int dummy;

  png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &dummy, &dummy, &dummy);

  //Damon
  x_resolution = (double)png_get_x_pixels_per_meter(png_ptr, info_ptr) * METER_PER_INCH;
  y_resolution = (double)png_get_y_pixels_per_meter(png_ptr, info_ptr) * METER_PER_INCH;
  //Damon: end

}

void PNG_close(FILE* fp, png_structp png_ptr, png_infop info_ptr, png_infop end_info) {
  // As PNG_close() might be called when png_read_image() has not yet been
  // used (premature termination), png_read_end() might crash.
  // We therefore omit the call to png_read_end(), as we are not
  // interested in the comment texts following the image data anyway.
  //png_read_end(png_ptr, end_info);
  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  fclose(fp);
}

ImageInfo* PNG_info(char* filename) {
  FILE* fp;
  png_structp png_ptr;
  png_infop info_ptr, end_info;
  png_uint_32 width, height;
  int bit_depth, color_type;
  double x_resolution, y_resolution;
  PNG_info_specific(filename, fp, png_ptr, info_ptr, end_info, width, height, bit_depth, color_type, x_resolution, y_resolution);

  ImageInfo* info = new ImageInfo();
  try {
    // Copy to our own ImageInfo object
    info->m_nrows = height;
    info->m_ncols = width;
    info->m_depth = bit_depth;
    info->m_x_resolution = x_resolution;
    info->m_y_resolution = y_resolution;
    if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_RGB ||
    color_type == PNG_COLOR_TYPE_RGB_ALPHA)
      info->m_ncolors = 3;
    else if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
      info->m_ncolors = 1;
  } catch (std::exception e) {
    delete info;
    throw;
  }
  // PNG_close(fp, png_ptr, info_ptr, end_info);
  return info;
}

template<class T>
void load_PNG_simple(T& image, png_structp& png_ptr) {
  typename T::row_iterator r = image.row_begin();
  for (; r != image.row_end(); ++r)
    png_read_row(png_ptr, (png_bytep)(&(*r)), NULL);
}

template<class T>
void load_PNG_grey16(T& image, png_structp& png_ptr) {
  uint16_t* row = new uint16_t[image.ncols()];
  if (byte_order_little_endian())
    png_set_swap(png_ptr);
  try {
    typename T::row_iterator r = image.row_begin();
    for (; r != image.row_end(); ++r) {
      png_read_row(png_ptr, (png_bytep)row, NULL);
      uint16_t* from = row;
      typename T::col_iterator c = r.begin();
      for (; c != r.end(); ++c, ++from) {
        c.set((int)*from);
      }
    }
  } catch (std::exception e) {
    delete[] row;
    throw;
  }
  delete[] row;
}

template<class T>
void load_PNG_onebit(T& image, png_structp& png_ptr) {
  png_set_invert_mono(png_ptr);
#if PNG_LIBPNG_VER > 10399
  png_set_expand_gray_1_2_4_to_8(png_ptr);
#else
  png_set_gray_1_2_4_to_8(png_ptr);
#endif

  png_bytep row = new png_byte[image.ncols()];
  try {
    typename T::row_iterator r = image.row_begin();
    for (; r != image.row_end(); ++r) {
      png_read_row(png_ptr, row, NULL);
      png_bytep from = row;
      typename T::col_iterator c = r.begin();
      for (; c != r.end(); ++c, ++from) {
        if (*from)
          c.set(pixel_traits<OneBitPixel>::black());
        else
          c.set(pixel_traits<OneBitPixel>::white());
      }
    }
  } catch (std::exception e) {
    delete[] row;
    throw;
  }
  delete[] row;
}

Image* load_PNG(const char* filename, int storage) {
  FILE* fp;
  png_structp png_ptr;
  png_infop info_ptr, end_info;
  png_uint_32 width, height;
  int bit_depth, color_type;
  double x_resolution, y_resolution;
  PNG_info_specific(filename, fp, png_ptr, info_ptr, end_info, width, height, bit_depth, color_type, x_resolution, y_resolution);

  // libpng exception handling
  if (setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
    fclose(fp);
    throw std::runtime_error("error in reading PNG data");
  }

  //Damon
  double reso = (x_resolution + y_resolution) / 2.0;

  //Damon: end
  // if (color_type & PNG_COLOR_MASK_ALPHA)
  png_set_strip_alpha(png_ptr);

  if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_PALETTE ||
      color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
    if (storage == RLE) {
      PNG_close(fp, png_ptr, info_ptr, end_info);
      throw std::runtime_error("Pixel type must be OneBit to use RLE data.");
    }
    if (bit_depth > 8) {
#if PNG_LIBPNG_VER >= 10504
      png_set_scale_16(png_ptr);
#else
      png_set_strip_16(png_ptr);
#endif
    }
    else if (bit_depth < 8) {
      png_set_expand(png_ptr);
    }
    if (color_type == PNG_COLOR_TYPE_PALETTE)
      png_set_palette_to_rgb(png_ptr);
    typedef TypeIdImageFactory<RGB, DENSE> fact;
    fact::image_type* image =
      fact::create(Point(0, 0), Dim(width, height));
    load_PNG_simple(*image, png_ptr);
    //Damon
    image->resolution(reso);
    //Damon: end    
    PNG_close(fp, png_ptr, info_ptr, end_info);
    return image;
  } else if (color_type == PNG_COLOR_TYPE_GRAY ||
             color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
    if (bit_depth == 1) {
      if (storage == DENSE) {
        typedef TypeIdImageFactory<ONEBIT, DENSE> fact;
        fact::image_type* image =
          fact::create(Point(0, 0), Dim(width, height));
        load_PNG_onebit(*image, png_ptr);
        //Damon
        image->resolution(reso);
        //Damon: end    
        PNG_close(fp, png_ptr, info_ptr, end_info);
        return image;
      } else {
        typedef TypeIdImageFactory<ONEBIT, RLE> fact;
        fact::image_type* image =
          fact::create(Point(0, 0), Dim(width, height));
        load_PNG_onebit(*image, png_ptr);
        //Damon
        image->resolution(reso);
        //Damon: end    
        PNG_close(fp, png_ptr, info_ptr, end_info);
        return image;
      } 
    } else if (bit_depth <= 8) {
      if (storage == RLE) {
        PNG_close(fp, png_ptr, info_ptr, end_info);
        throw std::runtime_error("Pixel type must be OneBit to use RLE data.");
      }
      if (bit_depth < 8) {
#if PNG_LIBPNG_VER > 10399
        png_set_expand_gray_1_2_4_to_8(png_ptr);
#else
        png_set_gray_1_2_4_to_8(png_ptr);
#endif
      }
      typedef TypeIdImageFactory<GREYSCALE, DENSE> fact_type;
      fact_type::image_type*
        image = fact_type::create(Point(0, 0), Dim(width, height));
      load_PNG_simple(*image, png_ptr);
      //Damon
      image->resolution(reso);
      //Damon: end  
      PNG_close(fp, png_ptr, info_ptr, end_info);
      return image;
    } else if (bit_depth == 16) {
      if (storage == RLE) {
        PNG_close(fp, png_ptr, info_ptr, end_info);
        throw std::runtime_error("Pixel type must be OneBit to use RLE data.");
      }
      typedef TypeIdImageFactory<GREY16, DENSE> fact_type;
      fact_type::image_type*
        image = fact_type::create(Point(0, 0), Dim(width, height));
      load_PNG_grey16(*image, png_ptr);
      //Damon
      image->resolution(reso);
      //Damon: end  
      PNG_close(fp, png_ptr, info_ptr, end_info);
      return image;
    }
  }
  PNG_close(fp, png_ptr, info_ptr, end_info);
  throw std::runtime_error("PNG file is an unsupported type");
}

template<class P>
struct PNG_saver {
  template<class T>
  void operator()(T& image, png_structp png_ptr) {
    typename T::row_iterator r = image.row_begin();
    for (; r != image.row_end(); ++r)
      png_write_row(png_ptr, (png_bytep)(&(*r)));
  }
};

template<>
struct PNG_saver<OneBitPixel> {
  template<class T>
  void operator()(T& image, png_structp png_ptr) {
    png_bytep row = new png_byte[image.ncols()];
    try {
      typename T::row_iterator r = image.row_begin();
      for (; r != image.row_end(); ++r) {
    png_bytep from = row;
    typename T::col_iterator c = r.begin();
    for (; c != r.end(); ++c, ++from) {
      if (is_black(c.get()))
        *from = 0;
      else
        *from = 255;
    }
    png_write_row(png_ptr, row);
      }
    } catch (std::exception e) {
      delete[] row;
      throw;
    }
    delete[] row;
  }
};

template<>
struct PNG_saver<FloatPixel> {
  template<class T>
  void operator()(T& image, png_structp png_ptr) {
    FloatPixel max = 0;
    max = find_max(image.parent());
    if (max > 0)
      max = 255.0 / max;
    else 
      max = 0;

    png_bytep row = new png_byte[image.ncols()];
    try {
      typename T::row_iterator r = image.row_begin();
      for (; r != image.row_end(); ++r) {
    png_bytep from = row;
    typename T::col_iterator c = r.begin();
    for (; c != r.end(); ++c, ++from) {
      *from = (png_byte)(*c * max);
    }
    png_write_row(png_ptr, row);
      }
    } catch (std::exception e) {
      delete[] row;
      throw;
    }
    delete[] row;
  }
};

template<>
struct PNG_saver<ComplexPixel> {
  template<class T>
  void operator()(T& image, png_structp png_ptr) {
    ComplexPixel temp = find_max(image.parent());
    FloatPixel max;
    if (temp.real() > 0)
      max = 255.0 / temp.real();
    else 
      max = 0;

    png_bytep row = new png_byte[image.ncols()];
    try {
      typename T::row_iterator r = image.row_begin();
      for (; r != image.row_end(); ++r) {
    png_bytep from = row;
    typename T::col_iterator c = r.begin();
    for (; c != r.end(); ++c, ++from) {
      *from = (png_byte)((*c).real() * max);
    }
    png_write_row(png_ptr, row);
      }
    } catch (std::exception e) {
      delete[] row;
      throw;
    }
    delete[] row;
  }
};

template<>
struct PNG_saver<Grey16Pixel> {
  template<class T>
  void operator()(T& image, png_structp png_ptr) {
    //png_bytep row = new png_byte[image.ncols() * 2];
    uint16_t* row = new uint16_t[image.ncols()];
    if (byte_order_little_endian())
      png_set_swap(png_ptr);
    try {
      typename T::row_iterator r = image.row_begin();
      for (; r != image.row_end(); ++r) {
        typename T::col_iterator c = r.begin();
        uint16_t* from = (uint16_t*)row;
        for (; c != r.end(); ++c, ++from)
          *from = (uint16_t)(*c);
        png_write_row(png_ptr, (png_bytep)row);
      }
    } catch (std::exception e) {
      delete[] row;
      throw;
    }
    delete[] row;
  }
};

template<class T>
void save_PNG(T& image, const char* filename) {
  FILE* fp = fopen(filename, "wb");
  if (!fp)
    throw std::invalid_argument("Failed to open image");
  
  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  if (!png_ptr) {
    fclose(fp);
    throw std::runtime_error("Couldn't create PNG header");
  }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
    fclose(fp);
    throw std::runtime_error("Couldn't create PNG header");
  }         

  if (setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_write_struct(&png_ptr, &info_ptr);
    fclose(fp);
    throw std::runtime_error("Unknown PNG error");
  }
  
  png_uint_32 width = image.ncols();
  png_uint_32 height = image.nrows();
  int bit_depth;
  if (image.depth() == 32)
    bit_depth = 16;
  else if (image.depth() == 64)
    bit_depth = 8;
  else if (image.depth() == 128)
    bit_depth = 8;
  else
    bit_depth = image.depth();
  int color_type = (image.ncolors() == 3) ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_GRAY;
  png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, 
           PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
           PNG_FILTER_TYPE_DEFAULT);
  
  //Damon 
  png_uint_32 res_x = (png_uint_32)(image.resolution() / METER_PER_INCH);
  png_uint_32 res_y = (png_uint_32)(image.resolution() / METER_PER_INCH);
  int unit_type = PNG_RESOLUTION_METER;
  png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  //Damon:end

  png_init_io(png_ptr, fp);
  png_write_info(png_ptr, info_ptr);
  png_set_packing(png_ptr);
  
  PNG_saver<typename T::value_type> saver;
  saver(image, png_ptr);
  
  png_write_end(png_ptr, info_ptr);
  png_destroy_write_struct(&png_ptr, &info_ptr);
  fclose(fp);
}

#endif