png.cpp 18.8 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
/**
 * @file io/cxx/ImagePngFile.cc
 * @date Fri Oct 12 12:08:00 2012 +0200
 * @author Laurent El Shafey <laurent.el-shafey@idiap.ch>
Manuel Günther's avatar
Manuel Günther committed
5
 * @author Manuel Gunther <siebenkopf@googlemail.com>
André Anjos's avatar
André Anjos committed
6
7
8
9
 *
 * @brief Implements an image format reader/writer using libpng.
 *
 * Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
Manuel Günther's avatar
Manuel Günther committed
10
 * Copyright (c) 2016, Regents of the University of Colorado on behalf of the University of Colorado Colorado Springs.
André Anjos's avatar
André Anjos committed
11
12
 */

Manuel Günther's avatar
Manuel Günther committed
13
14
#ifdef HAVE_LIBPNG

André Anjos's avatar
André Anjos committed
15
16
17
18
19
20
21
22
23
#include <boost/filesystem.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <string>

24
#include <bob.core/logging.h>
Manuel Günther's avatar
Manuel Günther committed
25
#include <bob.io.image/png.h>
André Anjos's avatar
André Anjos committed
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

extern "C" {
#include <png.h>
}

// The png_jmpbuf() macro, used in error handling, became available in
// libpng version 1.0.6. In order to be able to run the code with older
// versions of libpng, we define the following macro (but only if it
// is not already defined by libpng!).
#ifndef png_jmpbuf
#  define png_jmpbuf(png_ptr) ((png_ptr)->png_jmpbuf)
#endif


static boost::shared_ptr<std::FILE> make_cfile(const char *filename, const char *flags)
{
  std::FILE* fp = std::fopen(filename, flags);
  if(fp == 0) {
    boost::format m("the file `%s' could not be opened - verify permissions and availability");
    m % filename;
    throw std::runtime_error(m.str());
  }
  return boost::shared_ptr<std::FILE>(fp, std::fclose);
}

51
52
53
54
55
56
/**
 * ERROR HANDLING
 */
static void my_png_error(png_structp png_ptr, png_const_charp message){
  // error handling -> raise an exception
  boost::format m("In image '%s' fatal PNG error has occurred -> %s");
57
  m % reinterpret_cast<char*>(png_get_error_ptr(png_ptr)) % message;
58
59
60
61
62
  throw std::runtime_error(m.str());
}

static void my_png_warning(png_structp png_ptr, png_const_charp message){
  // warning handling -> emit debug message
63
  bob::core::debug << "In image '" << reinterpret_cast<char*>(png_get_error_ptr(png_ptr)) << "' PNG warning has occured -> " << message << std::endl;
64
65
}

André Anjos's avatar
André Anjos committed
66
67
68
/**
 * LOADING
 */
69
static void im_peek(const std::string& path, bob::io::base::array::typeinfo& info)
André Anjos's avatar
André Anjos committed
70
71
72
73
74
75
76
77
78
79
80
{
  // 1. PNG structure declarations
  png_structp png_ptr;
  png_infop info_ptr;

  // 2. PNG file opening
  boost::shared_ptr<std::FILE> in_file = make_cfile(path.c_str(), "rb");

  // 3. Create and initialize the png_struct. The compiler header file version
  //    is supplied, so that we know if the application was compiled with a
  //    compatible version of the library.
81
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, const_cast<char*>(path.c_str()), my_png_error, my_png_warning);
André Anjos's avatar
André Anjos committed
82
83
84
85
86
87
88
89
90
  if(png_ptr == NULL) throw std::runtime_error("PNG: error while creating read png structure (function png_create_read_struct())");

  // Allocate/initialize the memory for image information.
  info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr == NULL) {
    png_destroy_read_struct(&png_ptr, NULL, NULL);
    throw std::runtime_error("PNG: error while creating info png structure (function png_create_info_struct())");
  }

91
  // 4. Initialize
André Anjos's avatar
André Anjos committed
92
93
  png_init_io(png_ptr, in_file.get());

94
  // 5. The call to png_read_info() gives us all of the information from the
André Anjos's avatar
André Anjos committed
95
96
97
98
99
100
101
102
  // PNG file.
  png_read_info(png_ptr, info_ptr);
  // Get header information
  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
    &interlace_type, NULL, NULL);

103
  // 6. Clean up after the read, and free any memory allocated
André Anjos's avatar
André Anjos committed
104
105
106
  png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

  // Set depth and number of dimensions
107
  info.dtype = (bit_depth <= 8 ? bob::io::base::array::t_uint8 : bob::io::base::array::t_uint16);
108
  info.nd = color_type & PNG_COLOR_MASK_COLOR ? 3 : 2;
André Anjos's avatar
André Anjos committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  if(info.nd == 2)
  {
    info.shape[0] = height;
    info.shape[1] = width;
  }
  else
  {
    info.shape[0] = 3;
    info.shape[1] = height;
    info.shape[2] = width;
  }
  info.update_strides();
}

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
static uint16_t switch_endianess(const uint16_t p){
  return p / 256 + p % 256 * 256;
}

template <typename T> static
void imbuffer_to_gray(const size_t size, const T* im, T* g)
{
  std::copy(im, im+size, g);
}

template <>
void imbuffer_to_gray(const size_t size, const uint16_t* im, uint16_t* g)
{
  for(size_t k=0; k<size; ++k)
  {
    *g++ = switch_endianess(*im++);
  }
}



André Anjos's avatar
André Anjos committed
144
template <typename T> static
145
void im_load_gray(png_structp png_ptr, bob::io::base::array::interface& b)
André Anjos's avatar
André Anjos committed
146
{
147
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
148
149
150
151
152
153
154
155
156
157
  const size_t height = info.shape[0];
  const size_t width = info.shape[1];

#ifdef PNG_READ_INTERLACING_SUPPORTED
  // Turn on interlace handling.
  int number_passes = png_set_interlace_handling(png_ptr);
#else
  int number_passes = 1;
#endif // PNG_READ_INTERLACING_SUPPORTED

158
159
160
161
  // Allocate array to contain a row of pixels
  boost::shared_array<T> row(new T[width]);
  png_bytep row_pointer = reinterpret_cast<png_bytep>(row.get());

André Anjos's avatar
André Anjos committed
162
163
164
165
166
167
168
  // Read the image (one row at a time)
  // This can deal with interlacing
  for(int pass=0; pass<number_passes; ++pass)
  {
    // Loop over the rows
    for(size_t y=0; y<height; ++y)
    {
169
170
      png_read_row(png_ptr, row_pointer, NULL);
      imbuffer_to_gray(width, reinterpret_cast<T*>(row_pointer), reinterpret_cast<T*>(b.ptr())+y*width);
André Anjos's avatar
André Anjos committed
171
172
173
174
175
    }
  }
}

template <typename T> static
176
void imbuffer_to_rgb(const size_t size, const T* im, T* r, T* g, T* b)
André Anjos's avatar
André Anjos committed
177
178
179
{
  for(size_t k=0; k<size; ++k)
  {
180
181
182
    *r++ = *im++;
    *g++ = *im++;
    *b++ = *im++;
André Anjos's avatar
André Anjos committed
183
184
185
  }
}

186
187
188
189
190
191
192
193
194
195
196
197
template <>
void imbuffer_to_rgb(const size_t size, const uint16_t* im, uint16_t* r, uint16_t* g, uint16_t* b)
{
  for(size_t k=0; k<size; ++k)
  {
    *r++ = switch_endianess(*im++);
    *g++ = switch_endianess(*im++);
    *b++ = switch_endianess(*im++);
  }
}


André Anjos's avatar
André Anjos committed
198
template <typename T> static
199
void im_load_color(png_structp png_ptr, bob::io::base::array::interface& b)
André Anjos's avatar
André Anjos committed
200
{
201
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
202
203
204
205
206
207
  const size_t height = info.shape[1];
  const size_t width = info.shape[2];
  const size_t frame_size = height * width;
  const size_t row_color_stride = width;

  // Allocate array to contains a row of RGB-like pixels
208
  boost::shared_array<T> row(new T[3*width]);
André Anjos's avatar
André Anjos committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
  png_bytep row_pointer = reinterpret_cast<png_bytep>(row.get());

#ifdef PNG_READ_INTERLACING_SUPPORTED
  // Turn on interlace handling.
  int number_passes = png_set_interlace_handling(png_ptr);
#else
  int number_passes = 1;
#endif // PNG_READ_INTERLACING_SUPPORTED

  // Read the image (one row at a time)
  // This can deal with interlacing
  T *element_r;
  T *element_g;
  T *element_b;
  for(int pass=0; pass<number_passes; ++pass)
  {
    element_r = reinterpret_cast<T*>(b.ptr());
    element_g = element_r + frame_size;
    element_b = element_g + frame_size;
    // Loop over the rows
    for(size_t y=0; y<height; ++y)
    {
      png_read_row(png_ptr, row_pointer, NULL);
232
      imbuffer_to_rgb(row_color_stride, reinterpret_cast<T*>(row_pointer), element_r, element_g, element_b);
André Anjos's avatar
André Anjos committed
233
234
235
236
237
238
239
      element_r += row_color_stride;
      element_g += row_color_stride;
      element_b += row_color_stride;
    }
  }
}

240
static void im_load(const std::string& filename, bob::io::base::array::interface& b)
André Anjos's avatar
André Anjos committed
241
242
243
244
245
246
247
248
249
250
251
{
  // 1. PNG structure declarations
  png_structp png_ptr;
  png_infop info_ptr;

  // 2. PNG file opening
  boost::shared_ptr<std::FILE> in_file = make_cfile(filename.c_str(), "rb");

  // 3. Create and initialize the png_struct with the desired error handler
  // functions. The compiler header file version is supplied, so that we
  // know if the application was compiled with a compatible version of the library.
252
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, const_cast<char*>(filename.c_str()), my_png_error, my_png_warning);
André Anjos's avatar
André Anjos committed
253
254
255
256
257
258
259
260
261
  if(png_ptr == NULL) throw std::runtime_error("PNG: error while creating read png structure (function png_create_read_struct())");

  // Allocate/initialize the memory for image informatio
  info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr == NULL) {
    png_destroy_read_struct(&png_ptr, NULL, NULL);
    throw std::runtime_error("PNG: error while creating info png structure (function png_create_info_struct())");
  }

262
  // 4. Initialize
André Anjos's avatar
André Anjos committed
263
264
  png_init_io(png_ptr, in_file.get());

265
  // 5. The call to png_read_info() gives us all of the information from the
André Anjos's avatar
André Anjos committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  // PNG file.
  png_read_info(png_ptr, info_ptr);
  // Get header information
  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
       &interlace_type, NULL, NULL);

  // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
  // byte into separate bytes (useful for paletted and grayscale images).
  png_set_packing(png_ptr);

  // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel
  if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    png_set_expand_gray_1_2_4_to_8(png_ptr);
  else if(color_type == PNG_COLOR_TYPE_PALETTE)
    png_set_palette_to_rgb(png_ptr);
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
  // skip the alpha channel
  if ((color_type & PNG_COLOR_MASK_ALPHA) || png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    png_set_strip_alpha(png_ptr);

  // Check color type
  switch (color_type){
    // I think that should be all, but in case a new version comes up with a different color space...
    case PNG_COLOR_TYPE_GRAY:
    case PNG_COLOR_TYPE_GRAY_ALPHA:
    case PNG_COLOR_TYPE_RGB:
    case PNG_COLOR_TYPE_PALETTE:
    case PNG_COLOR_TYPE_RGB_ALPHA:
      break;
    default:
      throw std::runtime_error("PNG: codec does not support images with color spaces different than GRAY, GRAY+alpha, RGB, RGB+alpha or Indexed colors (Palette)");
André Anjos's avatar
André Anjos committed
298
299
  }

300
  // 6. Read content
301
302
  const bob::io::base::array::typeinfo& info = b.type();
  if(info.dtype == bob::io::base::array::t_uint8) {
André Anjos's avatar
André Anjos committed
303
    if(info.nd == 2) im_load_gray<uint8_t>(png_ptr, b);
304
    else if(info.nd == 3) im_load_color<uint8_t>(png_ptr, b);
André Anjos's avatar
André Anjos committed
305
306
307
308
309
310
311
    else {
      png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
      boost::format m("the image in file `%s' has a number of dimensions for which this png codec has no support for: %s");
      m % info.str();
      throw std::runtime_error(m.str());
    }
  }
312
  else if(info.dtype == bob::io::base::array::t_uint16) {
André Anjos's avatar
André Anjos committed
313
    if(info.nd == 2) im_load_gray<uint16_t>(png_ptr, b);
314
    else if( info.nd == 3) im_load_color<uint16_t>(png_ptr, b);
André Anjos's avatar
André Anjos committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    else {
      png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
      boost::format m("the image in file `%s' has a number of dimensions for which this png codec has no support for: %s");
      m % info.str();
      throw std::runtime_error(m.str());
    }
  }
  else {
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
    boost::format m("the image in file `%s' has a data type this png codec has no support for: %s");
    m % info.str();
    throw std::runtime_error(m.str());
  }

  // 8. Clean up after the read, and free any memory allocated
  // Read rest of file, and get additional chunks in info_ptr
  png_read_end(png_ptr, NULL);
  png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
}


/**
 * SAVING
 */
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

template <typename T> static
void gray_to_imbuffer(const size_t size, const T* g, T* im)
{
  std::copy(g, g+size, im);
}

template <>
void gray_to_imbuffer(const size_t size, const uint16_t* g, uint16_t* im)
{
  for (size_t k=0; k<size; ++k)
  {
    *im++ = switch_endianess(*g++);
  }
}
 
André Anjos's avatar
André Anjos committed
355
template <typename T>
356
static void im_save_gray(const bob::io::base::array::interface& b, png_structp png_ptr)
André Anjos's avatar
André Anjos committed
357
{
358
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
359
360
361
362
  const size_t height = info.shape[0];
  const size_t width = info.shape[1];

  const T* row_pointer = reinterpret_cast<const T*>(b.ptr());
363
364
365
366

  // An array to store one row of pixels
  boost::shared_array<T> row(new T[width]);
  png_bytep array_ptr = reinterpret_cast<png_bytep>(row.get());
André Anjos's avatar
André Anjos committed
367
368
369
370

  // Save one row at a time
  for(size_t y=0; y<height; ++y)
  {
371
372
    gray_to_imbuffer(width, row_pointer, reinterpret_cast<T*>(array_ptr));
    png_write_row(png_ptr, array_ptr);
André Anjos's avatar
André Anjos committed
373
374
375
376
377
378
379
380
381
    row_pointer += width;
  }
}

template <typename T> static
void rgb_to_imbuffer(const size_t size, const T* r, const T* g, const T* b, T* im)
{
  for (size_t k=0; k<size; ++k)
  {
382
383
384
    *im++ = *r++;
    *im++ = *g++;
    *im++ = *b++;
André Anjos's avatar
André Anjos committed
385
386
387
  }
}

388
389
390
391
392
393
394
395
396
397
398
399
template <>
void rgb_to_imbuffer(const size_t size, const uint16_t* r, const uint16_t* g, const uint16_t* b, uint16_t* im)
{
  for (size_t k=0; k<size; ++k)
  {
    *im++ = switch_endianess(*r++);
    *im++ = switch_endianess(*g++);
    *im++ = switch_endianess(*b++);
  }
}


André Anjos's avatar
André Anjos committed
400
template <typename T>
401
static void im_save_color(const bob::io::base::array::interface& b, png_structp png_ptr)
André Anjos's avatar
André Anjos committed
402
{
403
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
  const size_t height = info.shape[1];
  const size_t width = info.shape[2];
  const size_t frame_size = height * width;
  const size_t row_color_stride = width;

  // Allocate array for a row as an RGB-like array
  boost::shared_array<T> row(new T[3*width]);
  png_bytep array_ptr = reinterpret_cast<png_bytep>(row.get());

  // pointer to a single row (png_bytep is a typedef to unsigned char or char)
  const T *element_r = static_cast<const T*>(b.ptr());
  const T *element_g = element_r + frame_size;
  const T *element_b = element_g + frame_size;
  for(size_t y=0; y<height; ++y)
  {
    rgb_to_imbuffer(row_color_stride, element_r, element_g, element_b, reinterpret_cast<T*>(array_ptr));
    png_write_row(png_ptr, array_ptr);
    element_r += row_color_stride;
    element_g += row_color_stride;
    element_b += row_color_stride;
  }
}

427
static void im_save(const std::string& filename, const bob::io::base::array::interface& array)
André Anjos's avatar
André Anjos committed
428
429
430
431
432
433
434
435
436
{
  // 1. PNG structures
  png_structp png_ptr;
  png_infop info_ptr;

  // 2. Open the file
  boost::shared_ptr<std::FILE> out_file = make_cfile(filename.c_str(), "wb");

  // 3.Create and initialize the png_struct with the desired error handler functions.
437
  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char*>(filename.c_str()), my_png_error, my_png_warning);
André Anjos's avatar
André Anjos committed
438
439
440
441
442
443
444
445
446

  // Allocate/initialize the image information data.
  info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr == NULL)
  {
    png_destroy_write_struct(&png_ptr,  NULL);
    throw std::runtime_error("PNG: error while creating info png structure (function png_create_info_struct())");
  }

447
  // 4. Initialize
André Anjos's avatar
André Anjos committed
448
449
  png_init_io(png_ptr, out_file.get());

450
  // 5. Set the image information here:
André Anjos's avatar
André Anjos committed
451
452
453
454
455
456
  // width and height are up to 2^31
  // bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on the color_type selected
  // color_type is one of PNG_COLOR_TYPE_GRAY, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
  // or PNG_COLOR_TYPE_RGB_ALPHA
  // interlace is either PNG_INTERLACE_NONE or PNG_INTERLACE_ADAM7
  // compression_type and filter_type MUST currently be PNG_COMPRESSION_TYPE_DEFAULT and PNG_FILTER_TYPE_DEFAULT
457
  const bob::io::base::array::typeinfo& info = array.type();
André Anjos's avatar
André Anjos committed
458
459
  png_uint_32 height = (info.nd == 2 ? info.shape[0] : info.shape[1]);
  png_uint_32 width = (info.nd == 2 ? info.shape[1] : info.shape[2]);
460
  int bit_depth = (info.dtype == bob::io::base::array::t_uint8 ? 8 : 16);
André Anjos's avatar
André Anjos committed
461
462
463
464
465
466
467
468
469
470
  png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
    (info.nd == 2 ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_RGB),
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

  // Write the file header information.
  png_write_info(png_ptr, info_ptr);

  // Pack pixels into bytes
  png_set_packing(png_ptr);

471
  // 6. Writes content
472
  if(info.dtype == bob::io::base::array::t_uint8) {
André Anjos's avatar
André Anjos committed
473
474
475
476
477
478
479
480
481
482
483
484
    if(info.nd == 2) im_save_gray<uint8_t>(array, png_ptr);
    else if(info.nd == 3) {
      if(info.shape[0] != 3)
      {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        throw std::runtime_error("PNG: color image does not have 3 planes on 1st. dimension");
      }
      im_save_color<uint8_t>(array, png_ptr);
    }
    else
    {
      png_destroy_write_struct(&png_ptr, &info_ptr);
Manuel Günther's avatar
Manuel Günther committed
485
      boost::format m("the image in file `%s' has a number of dimensions for which this png codec has no support for: %s");
André Anjos's avatar
André Anjos committed
486
487
488
489
      m % filename % info.str();
      throw std::runtime_error(m.str());
    }
  }
490
  else if(info.dtype == bob::io::base::array::t_uint16) {
André Anjos's avatar
André Anjos committed
491
492
493
494
495
496
497
498
499
500
501
502
    if(info.nd == 2) im_save_gray<uint16_t>(array, png_ptr);
    else if(info.nd == 3) {
      if(info.shape[0] != 3)
      {
      png_destroy_write_struct(&png_ptr, &info_ptr);
        throw std::runtime_error("PNG: color image does not have 3 planes on 1st. dimension");
      }
      im_save_color<uint16_t>(array, png_ptr);
    }
    else
    {
      png_destroy_write_struct(&png_ptr, &info_ptr);
Manuel Günther's avatar
Manuel Günther committed
503
      boost::format m("the image in file `%s' has a number of dimensions for which this png codec has no support for: %s");
André Anjos's avatar
André Anjos committed
504
505
506
507
508
509
      m % filename % info.str();
      throw std::runtime_error(m.str());
    }
  }
  else {
    png_destroy_write_struct(&png_ptr, &info_ptr);
Manuel Günther's avatar
Manuel Günther committed
510
    boost::format m("the image in file `%s' has a data type this png codec has no support for: %s");
André Anjos's avatar
André Anjos committed
511
512
513
514
515
516
517
518
519
520
521
522
    m % filename % info.str();
    throw std::runtime_error(m.str());
  }

  // It is REQUIRED to call this to finish writing the rest of the file
  png_write_end(png_ptr, NULL);

  // Clean up after the write, and free any memory allocated
  png_destroy_write_struct(&png_ptr, &info_ptr);
}


Manuel Günther's avatar
Manuel Günther committed
523
524
525
526
527
528
529
530
531
532
533
534
535
/**
 * PNG class
*/
bob::io::image::PNGFile::PNGFile(const char* path, char mode)
: m_filename(path),
  m_newfile(true)
{
  //checks if file exists
  if (mode == 'r' && !boost::filesystem::exists(path)) {
    boost::format m("file `%s' is not readable");
    m % path;
    throw std::runtime_error(m.str());
  }
André Anjos's avatar
André Anjos committed
536

Manuel Günther's avatar
Manuel Günther committed
537
538
539
540
541
542
543
544
  if (mode == 'r' || (mode == 'a' && boost::filesystem::exists(path))) {
    im_peek(path, m_type);
    m_length = 1;
    m_newfile = false;
  } else {
    m_length = 0;
    m_newfile = true;
  }
André Anjos's avatar
André Anjos committed
545

Manuel Günther's avatar
Manuel Günther committed
546
}
André Anjos's avatar
André Anjos committed
547

Manuel Günther's avatar
Manuel Günther committed
548
549
550
void bob::io::image::PNGFile::read(bob::io::base::array::interface& buffer, size_t index) {
  if (m_newfile)
    throw std::runtime_error("uninitialized image file cannot be read");
André Anjos's avatar
André Anjos committed
551

Manuel Günther's avatar
Manuel Günther committed
552
  if (!buffer.type().is_compatible(m_type)) buffer.set(m_type);
André Anjos's avatar
André Anjos committed
553

Manuel Günther's avatar
Manuel Günther committed
554
555
  if (index != 0)
    throw std::runtime_error("cannot read image with index > 0 -- there is only one image in an image file");
André Anjos's avatar
André Anjos committed
556

Manuel Günther's avatar
Manuel Günther committed
557
558
559
  if(!buffer.type().is_compatible(m_type)) buffer.set(m_type);
  im_load(m_filename, buffer);
}
André Anjos's avatar
André Anjos committed
560

Manuel Günther's avatar
Manuel Günther committed
561
562
563
564
565
566
567
568
size_t bob::io::image::PNGFile::append(const bob::io::base::array::interface& buffer) {
  if (m_newfile) {
    im_save(m_filename, buffer);
    m_type = buffer.type();
    m_newfile = false;
    m_length = 1;
    return 0;
  }
André Anjos's avatar
André Anjos committed
569

Manuel Günther's avatar
Manuel Günther committed
570
571
  throw std::runtime_error("image files only accept a single array");
}
André Anjos's avatar
André Anjos committed
572

Manuel Günther's avatar
Manuel Günther committed
573
574
575
576
577
578
void bob::io::image::PNGFile::write(const bob::io::base::array::interface& buffer) {
  //overwriting position 0 should always work
  if (m_newfile) {
    append(buffer);
    return;
  }
André Anjos's avatar
André Anjos committed
579

Manuel Günther's avatar
Manuel Günther committed
580
581
  throw std::runtime_error("image files only accept a single array");
}
André Anjos's avatar
André Anjos committed
582
583


Manuel Günther's avatar
Manuel Günther committed
584
std::string bob::io::image::PNGFile::s_codecname = "bob.image_png";
André Anjos's avatar
André Anjos committed
585

586
boost::shared_ptr<bob::io::base::File> make_png_file (const char* path, char mode) {
Manuel Günther's avatar
Manuel Günther committed
587
  return boost::make_shared<bob::io::image::PNGFile>(path, mode);
André Anjos's avatar
André Anjos committed
588
}
Manuel Günther's avatar
Manuel Günther committed
589
590

#endif // HAVE_LIBPNG