Path: blob/master/modules/imgcodecs/src/grfmt_png.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.13// Copyright (C) 2009, Willow Garage Inc., all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "precomp.hpp"4344#ifdef HAVE_PNG4546/****************************************************************************************\47This part of the file implements PNG codec on base of libpng library,48in particular, this code is based on example.c from libpng49(see otherlibs/_graphics/readme.txt for copyright notice)50and png2bmp sample from libpng distribution (Copyright (C) 1999-2001 MIYASAKA Masaru)51\****************************************************************************************/5253#ifndef _LFS64_LARGEFILE54# define _LFS64_LARGEFILE 055#endif56#ifndef _FILE_OFFSET_BITS57# define _FILE_OFFSET_BITS 058#endif5960#ifdef HAVE_LIBPNG_PNG_H61#include <libpng/png.h>62#else63#include <png.h>64#endif65#include <zlib.h>6667#include "grfmt_png.hpp"6869#if defined _MSC_VER && _MSC_VER >= 120070// interaction between '_setjmp' and C++ object destruction is non-portable71#pragma warning( disable: 4611 )72#endif7374// the following defines are a hack to avoid multiple problems with frame ponter handling and setjmp75// see http://gcc.gnu.org/ml/gcc/2011-10/msg00324.html for some details76#define mingw_getsp(...) 077#define __builtin_frame_address(...) 07879namespace cv80{8182/////////////////////// PngDecoder ///////////////////8384PngDecoder::PngDecoder()85{86m_signature = "\x89\x50\x4e\x47\xd\xa\x1a\xa";87m_color_type = 0;88m_png_ptr = 0;89m_info_ptr = m_end_info = 0;90m_f = 0;91m_buf_supported = true;92m_buf_pos = 0;93m_bit_depth = 0;94}959697PngDecoder::~PngDecoder()98{99close();100}101102ImageDecoder PngDecoder::newDecoder() const103{104return makePtr<PngDecoder>();105}106107void PngDecoder::close()108{109if( m_f )110{111fclose( m_f );112m_f = 0;113}114115if( m_png_ptr )116{117png_structp png_ptr = (png_structp)m_png_ptr;118png_infop info_ptr = (png_infop)m_info_ptr;119png_infop end_info = (png_infop)m_end_info;120png_destroy_read_struct( &png_ptr, &info_ptr, &end_info );121m_png_ptr = m_info_ptr = m_end_info = 0;122}123}124125126void PngDecoder::readDataFromBuf( void* _png_ptr, uchar* dst, size_t size )127{128png_structp png_ptr = (png_structp)_png_ptr;129PngDecoder* decoder = (PngDecoder*)(png_get_io_ptr(png_ptr));130CV_Assert( decoder );131const Mat& buf = decoder->m_buf;132if( decoder->m_buf_pos + size > buf.cols*buf.rows*buf.elemSize() )133{134png_error(png_ptr, "PNG input buffer is incomplete");135return;136}137memcpy( dst, decoder->m_buf.ptr() + decoder->m_buf_pos, size );138decoder->m_buf_pos += size;139}140141bool PngDecoder::readHeader()142{143volatile bool result = false;144close();145146png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );147148if( png_ptr )149{150png_infop info_ptr = png_create_info_struct( png_ptr );151png_infop end_info = png_create_info_struct( png_ptr );152153m_png_ptr = png_ptr;154m_info_ptr = info_ptr;155m_end_info = end_info;156m_buf_pos = 0;157158if( info_ptr && end_info )159{160if( setjmp( png_jmpbuf( png_ptr ) ) == 0 )161{162if( !m_buf.empty() )163png_set_read_fn(png_ptr, this, (png_rw_ptr)readDataFromBuf );164else165{166m_f = fopen( m_filename.c_str(), "rb" );167if( m_f )168png_init_io( png_ptr, m_f );169}170171if( !m_buf.empty() || m_f )172{173png_uint_32 wdth, hght;174int bit_depth, color_type, num_trans=0;175png_bytep trans;176png_color_16p trans_values;177178png_read_info( png_ptr, info_ptr );179180png_get_IHDR( png_ptr, info_ptr, &wdth, &hght,181&bit_depth, &color_type, 0, 0, 0 );182183m_width = (int)wdth;184m_height = (int)hght;185m_color_type = color_type;186m_bit_depth = bit_depth;187188if( bit_depth <= 8 || bit_depth == 16 )189{190switch(color_type)191{192case PNG_COLOR_TYPE_RGB:193case PNG_COLOR_TYPE_PALETTE:194png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);195if( num_trans > 0 )196m_type = CV_8UC4;197else198m_type = CV_8UC3;199break;200case PNG_COLOR_TYPE_GRAY_ALPHA:201case PNG_COLOR_TYPE_RGB_ALPHA:202m_type = CV_8UC4;203break;204default:205m_type = CV_8UC1;206}207if( bit_depth == 16 )208m_type = CV_MAKETYPE(CV_16U, CV_MAT_CN(m_type));209result = true;210}211}212}213}214}215216if( !result )217close();218219return result;220}221222223bool PngDecoder::readData( Mat& img )224{225volatile bool result = false;226AutoBuffer<uchar*> _buffer(m_height);227uchar** buffer = _buffer.data();228bool color = img.channels() > 1;229230png_structp png_ptr = (png_structp)m_png_ptr;231png_infop info_ptr = (png_infop)m_info_ptr;232png_infop end_info = (png_infop)m_end_info;233234if( m_png_ptr && m_info_ptr && m_end_info && m_width && m_height )235{236if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )237{238int y;239240if( img.depth() == CV_8U && m_bit_depth == 16 )241png_set_strip_16( png_ptr );242else if( !isBigEndian() )243png_set_swap( png_ptr );244245if(img.channels() < 4)246{247/* observation: png_read_image() writes 400 bytes beyond248* end of data when reading a 400x118 color png249* "mpplus_sand.png". OpenCV crashes even with demo250* programs. Looking at the loaded image I'd say we get 4251* bytes per pixel instead of 3 bytes per pixel. Test252* indicate that it is a good idea to always ask for253* stripping alpha.. 18.11.2004 Axel Walthelm254*/255png_set_strip_alpha( png_ptr );256} else257png_set_tRNS_to_alpha( png_ptr );258259if( m_color_type == PNG_COLOR_TYPE_PALETTE )260png_set_palette_to_rgb( png_ptr );261262if( (m_color_type & PNG_COLOR_MASK_COLOR) == 0 && m_bit_depth < 8 )263#if (PNG_LIBPNG_VER_MAJOR*10000 + PNG_LIBPNG_VER_MINOR*100 + PNG_LIBPNG_VER_RELEASE >= 10209) || \264(PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR == 0 && PNG_LIBPNG_VER_RELEASE >= 18)265png_set_expand_gray_1_2_4_to_8( png_ptr );266#else267png_set_gray_1_2_4_to_8( png_ptr );268#endif269270if( (m_color_type & PNG_COLOR_MASK_COLOR) && color )271png_set_bgr( png_ptr ); // convert RGB to BGR272else if( color )273png_set_gray_to_rgb( png_ptr ); // Gray->RGB274else275png_set_rgb_to_gray( png_ptr, 1, 0.299, 0.587 ); // RGB->Gray276277png_set_interlace_handling( png_ptr );278png_read_update_info( png_ptr, info_ptr );279280for( y = 0; y < m_height; y++ )281buffer[y] = img.data + y*img.step;282283png_read_image( png_ptr, buffer );284png_read_end( png_ptr, end_info );285286result = true;287}288}289290close();291return result;292}293294295/////////////////////// PngEncoder ///////////////////296297298PngEncoder::PngEncoder()299{300m_description = "Portable Network Graphics files (*.png)";301m_buf_supported = true;302}303304305PngEncoder::~PngEncoder()306{307}308309310bool PngEncoder::isFormatSupported( int depth ) const311{312return depth == CV_8U || depth == CV_16U;313}314315ImageEncoder PngEncoder::newEncoder() const316{317return makePtr<PngEncoder>();318}319320321void PngEncoder::writeDataToBuf(void* _png_ptr, uchar* src, size_t size)322{323if( size == 0 )324return;325png_structp png_ptr = (png_structp)_png_ptr;326PngEncoder* encoder = (PngEncoder*)(png_get_io_ptr(png_ptr));327CV_Assert( encoder && encoder->m_buf );328size_t cursz = encoder->m_buf->size();329encoder->m_buf->resize(cursz + size);330memcpy( &(*encoder->m_buf)[cursz], src, size );331}332333334void PngEncoder::flushBuf(void*)335{336}337338bool PngEncoder::write( const Mat& img, const std::vector<int>& params )339{340png_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );341png_infop info_ptr = 0;342FILE * volatile f = 0;343int y, width = img.cols, height = img.rows;344int depth = img.depth(), channels = img.channels();345volatile bool result = false;346AutoBuffer<uchar*> buffer;347348if( depth != CV_8U && depth != CV_16U )349return false;350351if( png_ptr )352{353info_ptr = png_create_info_struct( png_ptr );354355if( info_ptr )356{357if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )358{359if( m_buf )360{361png_set_write_fn(png_ptr, this,362(png_rw_ptr)writeDataToBuf, (png_flush_ptr)flushBuf);363}364else365{366f = fopen( m_filename.c_str(), "wb" );367if( f )368png_init_io( png_ptr, (png_FILE_p)f );369}370371int compression_level = -1; // Invalid value to allow setting 0-9 as valid372int compression_strategy = IMWRITE_PNG_STRATEGY_RLE; // Default strategy373bool isBilevel = false;374375for( size_t i = 0; i < params.size(); i += 2 )376{377if( params[i] == IMWRITE_PNG_COMPRESSION )378{379compression_strategy = IMWRITE_PNG_STRATEGY_DEFAULT; // Default strategy380compression_level = params[i+1];381compression_level = MIN(MAX(compression_level, 0), Z_BEST_COMPRESSION);382}383if( params[i] == IMWRITE_PNG_STRATEGY )384{385compression_strategy = params[i+1];386compression_strategy = MIN(MAX(compression_strategy, 0), Z_FIXED);387}388if( params[i] == IMWRITE_PNG_BILEVEL )389{390isBilevel = params[i+1] != 0;391}392}393394if( m_buf || f )395{396if( compression_level >= 0 )397{398png_set_compression_level( png_ptr, compression_level );399}400else401{402// tune parameters for speed403// (see http://wiki.linuxquestions.org/wiki/Libpng)404png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);405png_set_compression_level(png_ptr, Z_BEST_SPEED);406}407png_set_compression_strategy(png_ptr, compression_strategy);408409png_set_IHDR( png_ptr, info_ptr, width, height, depth == CV_8U ? isBilevel?1:8 : 16,410channels == 1 ? PNG_COLOR_TYPE_GRAY :411channels == 3 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGBA,412PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,413PNG_FILTER_TYPE_DEFAULT );414415png_write_info( png_ptr, info_ptr );416417if (isBilevel)418png_set_packing(png_ptr);419420png_set_bgr( png_ptr );421if( !isBigEndian() )422png_set_swap( png_ptr );423424buffer.allocate(height);425for( y = 0; y < height; y++ )426buffer[y] = img.data + y*img.step;427428png_write_image( png_ptr, buffer.data() );429png_write_end( png_ptr, info_ptr );430431result = true;432}433}434}435}436437png_destroy_write_struct( &png_ptr, &info_ptr );438if(f) fclose( (FILE*)f );439440return result;441}442443}444445#endif446447/* End of file. */448449450