1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "precomp.hpp"
47 /****************************************************************************************\
48 This part of the file implements PNG codec on base of libpng library,
49 in particular, this code is based on example.c from libpng
50 (see otherlibs/_graphics/readme.txt for copyright notice)
51 and png2bmp sample from libpng distribution (Copyright (C) 1999-2001 MIYASAKA Masaru)
52 \****************************************************************************************/
54 #undef HAVE_UNISTD_H //to avoid redefinition
55 #ifndef _LFS64_LARGEFILE
56 # define _LFS64_LARGEFILE 0
58 #ifndef _FILE_OFFSET_BITS
59 # define _FILE_OFFSET_BITS 0
62 #ifdef HAVE_LIBPNG_PNG_H
63 #include <libpng/png.h>
69 #include "grfmt_png.hpp"
71 #if defined _MSC_VER && _MSC_VER >= 1200
72 // interaction between '_setjmp' and C++ object destruction is non-portable
73 #pragma warning( disable: 4611 )
76 // the following defines are a hack to avoid multiple problems with frame ponter handling and setjmp
77 // see http://gcc.gnu.org/ml/gcc/2011-10/msg00324.html for some details
78 #define mingw_getsp(...) 0
79 #define __builtin_frame_address(...) 0
84 /////////////////////// PngDecoder ///////////////////
86 PngDecoder::PngDecoder()
88 m_signature = "\x89\x50\x4e\x47\xd\xa\x1a\xa";
91 m_info_ptr = m_end_info = 0;
93 m_buf_supported = true;
98 PngDecoder::~PngDecoder()
103 ImageDecoder PngDecoder::newDecoder() const
105 return new PngDecoder;
108 void PngDecoder::close()
118 png_structp png_ptr = (png_structp)m_png_ptr;
119 png_infop info_ptr = (png_infop)m_info_ptr;
120 png_infop end_info = (png_infop)m_end_info;
121 png_destroy_read_struct( &png_ptr, &info_ptr, &end_info );
122 m_png_ptr = m_info_ptr = m_end_info = 0;
127 void PngDecoder::readDataFromBuf( void* _png_ptr, uchar* dst, size_t size )
129 png_structp png_ptr = (png_structp)_png_ptr;
130 PngDecoder* decoder = (PngDecoder*)(png_get_io_ptr(png_ptr));
131 CV_Assert( decoder );
132 const Mat& buf = decoder->m_buf;
133 if( decoder->m_buf_pos + size > buf.cols*buf.rows*buf.elemSize() )
135 png_error(png_ptr, "PNG input buffer is incomplete");
138 memcpy( dst, &decoder->m_buf.data[decoder->m_buf_pos], size );
139 decoder->m_buf_pos += size;
142 bool PngDecoder::readHeader()
147 png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );
151 png_infop info_ptr = png_create_info_struct( png_ptr );
152 png_infop end_info = png_create_info_struct( png_ptr );
155 m_info_ptr = info_ptr;
156 m_end_info = end_info;
159 if( info_ptr && end_info )
161 if( setjmp( png_jmpbuf( png_ptr ) ) == 0 )
164 png_set_read_fn(png_ptr, this, (png_rw_ptr)readDataFromBuf );
167 m_f = fopen( m_filename.c_str(), "rb" );
169 png_init_io( png_ptr, m_f );
172 if( !m_buf.empty() || m_f )
174 png_uint_32 wdth, hght;
175 int bit_depth, color_type;
177 png_read_info( png_ptr, info_ptr );
179 png_get_IHDR( png_ptr, info_ptr, &wdth, &hght,
180 &bit_depth, &color_type, 0, 0, 0 );
183 m_height = (int)hght;
184 m_color_type = color_type;
185 m_bit_depth = bit_depth;
187 if( bit_depth <= 8 || bit_depth == 16 )
191 case PNG_COLOR_TYPE_RGB:
192 case PNG_COLOR_TYPE_PALETTE:
195 case PNG_COLOR_TYPE_RGB_ALPHA:
201 if( bit_depth == 16 )
202 m_type = CV_MAKETYPE(CV_16U, CV_MAT_CN(m_type));
217 bool PngDecoder::readData( Mat& img )
220 AutoBuffer<uchar*> _buffer(m_height);
221 uchar** buffer = _buffer;
222 int color = img.channels() > 1;
223 uchar* data = img.data;
224 int step = (int)img.step;
226 if( m_png_ptr && m_info_ptr && m_end_info && m_width && m_height )
228 png_structp png_ptr = (png_structp)m_png_ptr;
229 png_infop info_ptr = (png_infop)m_info_ptr;
230 png_infop end_info = (png_infop)m_end_info;
232 if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )
236 if( img.depth() == CV_8U && m_bit_depth == 16 )
237 png_set_strip_16( png_ptr );
238 else if( !isBigEndian() )
239 png_set_swap( png_ptr );
241 if(img.channels() < 4)
243 /* observation: png_read_image() writes 400 bytes beyond
244 * end of data when reading a 400x118 color png
245 * "mpplus_sand.png". OpenCV crashes even with demo
246 * programs. Looking at the loaded image I'd say we get 4
247 * bytes per pixel instead of 3 bytes per pixel. Test
248 * indicate that it is a good idea to always ask for
249 * stripping alpha.. 18.11.2004 Axel Walthelm
251 png_set_strip_alpha( png_ptr );
254 if( m_color_type == PNG_COLOR_TYPE_PALETTE )
255 png_set_palette_to_rgb( png_ptr );
257 if( m_color_type == PNG_COLOR_TYPE_GRAY && m_bit_depth < 8 )
258 #if (PNG_LIBPNG_VER_MAJOR*10000 + PNG_LIBPNG_VER_MINOR*100 + PNG_LIBPNG_VER_RELEASE >= 10209) || \
259 (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR == 0 && PNG_LIBPNG_VER_RELEASE >= 18)
260 png_set_expand_gray_1_2_4_to_8( png_ptr );
262 png_set_gray_1_2_4_to_8( png_ptr );
265 if( CV_MAT_CN(m_type) > 1 && color )
266 png_set_bgr( png_ptr ); // convert RGB to BGR
268 png_set_gray_to_rgb( png_ptr ); // Gray->RGB
270 png_set_rgb_to_gray( png_ptr, 1, 0.299, 0.587 ); // RGB->Gray
272 png_read_update_info( png_ptr, info_ptr );
274 for( y = 0; y < m_height; y++ )
275 buffer[y] = data + y*step;
277 png_read_image( png_ptr, buffer );
278 png_read_end( png_ptr, end_info );
289 /////////////////////// PngEncoder ///////////////////
292 PngEncoder::PngEncoder()
294 m_description = "Portable Network Graphics files (*.png)";
295 m_buf_supported = true;
299 PngEncoder::~PngEncoder()
304 bool PngEncoder::isFormatSupported( int depth ) const
306 return depth == CV_8U || depth == CV_16U;
309 ImageEncoder PngEncoder::newEncoder() const
311 return new PngEncoder;
315 void PngEncoder::writeDataToBuf(void* _png_ptr, uchar* src, size_t size)
319 png_structp png_ptr = (png_structp)_png_ptr;
320 PngEncoder* encoder = (PngEncoder*)(png_get_io_ptr(png_ptr));
321 CV_Assert( encoder && encoder->m_buf );
322 size_t cursz = encoder->m_buf->size();
323 encoder->m_buf->resize(cursz + size);
324 memcpy( &(*encoder->m_buf)[cursz], src, size );
328 void PngEncoder::flushBuf(void*)
332 bool PngEncoder::write( const Mat& img, const vector<int>& params )
334 png_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );
335 png_infop info_ptr = 0;
337 int y, width = img.cols, height = img.rows;
338 int depth = img.depth(), channels = img.channels();
340 AutoBuffer<uchar*> buffer;
342 if( depth != CV_8U && depth != CV_16U )
347 info_ptr = png_create_info_struct( png_ptr );
351 if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )
355 png_set_write_fn(png_ptr, this,
356 (png_rw_ptr)writeDataToBuf, (png_flush_ptr)flushBuf);
360 f = fopen( m_filename.c_str(), "wb" );
362 png_init_io( png_ptr, f );
365 int compression_level = -1; // Invalid value to allow setting 0-9 as valid
366 int compression_strategy = Z_RLE; // Default strategy
367 bool isBilevel = false;
369 for( size_t i = 0; i < params.size(); i += 2 )
371 if( params[i] == CV_IMWRITE_PNG_COMPRESSION )
373 compression_level = params[i+1];
374 compression_level = MIN(MAX(compression_level, 0), Z_BEST_COMPRESSION);
376 if( params[i] == CV_IMWRITE_PNG_STRATEGY )
378 compression_strategy = params[i+1];
379 compression_strategy = MIN(MAX(compression_strategy, 0), Z_FIXED);
381 if( params[i] == CV_IMWRITE_PNG_BILEVEL )
383 isBilevel = params[i+1] != 0;
389 if( compression_level >= 0 )
391 png_set_compression_level( png_ptr, compression_level );
395 // tune parameters for speed
396 // (see http://wiki.linuxquestions.org/wiki/Libpng)
397 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);
398 png_set_compression_level(png_ptr, Z_BEST_SPEED);
400 png_set_compression_strategy(png_ptr, compression_strategy);
402 png_set_IHDR( png_ptr, info_ptr, width, height, depth == CV_8U ? isBilevel?1:8 : 16,
403 channels == 1 ? PNG_COLOR_TYPE_GRAY :
404 channels == 3 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGBA,
405 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
406 PNG_FILTER_TYPE_DEFAULT );
408 png_write_info( png_ptr, info_ptr );
411 png_set_packing(png_ptr);
413 png_set_bgr( png_ptr );
415 png_set_swap( png_ptr );
417 buffer.allocate(height);
418 for( y = 0; y < height; y++ )
419 buffer[y] = img.data + y*img.step;
421 png_write_image( png_ptr, buffer );
422 png_write_end( png_ptr, info_ptr );
430 png_destroy_write_struct( &png_ptr, &info_ptr );