diff --git a/modules/highgui/src/grfmt_base.cpp b/modules/highgui/src/grfmt_base.cpp index 405cf8b88f..bd9d98e2f4 100644 --- a/modules/highgui/src/grfmt_base.cpp +++ b/modules/highgui/src/grfmt_base.cpp @@ -123,6 +123,15 @@ ImageEncoder BaseImageEncoder::newEncoder() const return ImageEncoder(); } +void BaseImageEncoder::throwOnEror() const +{ + if(!m_last_error.empty()) + { + std::string msg = "Raw image encoder error: " + m_last_error; + CV_Error( CV_BadImageSize, msg.c_str() ); + } +} + } /* End of file. */ diff --git a/modules/highgui/src/grfmt_base.hpp b/modules/highgui/src/grfmt_base.hpp index 8c0130556d..49420f431a 100644 --- a/modules/highgui/src/grfmt_base.hpp +++ b/modules/highgui/src/grfmt_base.hpp @@ -100,12 +100,16 @@ public: virtual string getDescription() const; virtual ImageEncoder newEncoder() const; + virtual void throwOnEror() const; + protected: string m_description; string m_filename; vector* m_buf; bool m_buf_supported; + + string m_last_error; }; } diff --git a/modules/highgui/src/grfmt_jpeg.cpp b/modules/highgui/src/grfmt_jpeg.cpp index 521517639f..3dedf440de 100644 --- a/modules/highgui/src/grfmt_jpeg.cpp +++ b/modules/highgui/src/grfmt_jpeg.cpp @@ -537,8 +537,10 @@ ImageEncoder JpegEncoder::newEncoder() const return new JpegEncoder; } -bool JpegEncoder::write( const Mat& img, const vector& params ) +bool JpegEncoder::write( const Mat& img, const vector& params ) { + m_last_error.clear(); + struct fileWrapper { FILE* f; @@ -633,6 +635,14 @@ bool JpegEncoder::write( const Mat& img, const vector& params ) } _exit_: + + if(!result) + { + char jmsg_buf[JMSG_LENGTH_MAX]; + jerr.pub.format_message((j_common_ptr)&cinfo, jmsg_buf); + m_last_error = jmsg_buf; + } + jpeg_destroy_compress( &cinfo ); return result; diff --git a/modules/highgui/src/loadsave.cpp b/modules/highgui/src/loadsave.cpp index 667c2d16e7..6658b1335e 100644 --- a/modules/highgui/src/loadsave.cpp +++ b/modules/highgui/src/loadsave.cpp @@ -426,6 +426,7 @@ bool imencode( const string& ext, InputArray _image, if( encoder->setDestination(buf) ) { code = encoder->write(image, params); + encoder->throwOnEror(); CV_Assert( code ); } else @@ -433,8 +434,11 @@ bool imencode( const string& ext, InputArray _image, string filename = tempfile(); code = encoder->setDestination(filename); CV_Assert( code ); + code = encoder->write(image, params); + encoder->throwOnEror(); CV_Assert( code ); + FILE* f = fopen( filename.c_str(), "rb" ); CV_Assert(f != 0); fseek( f, 0, SEEK_END ); diff --git a/modules/highgui/test/test_grfmt.cpp b/modules/highgui/test/test_grfmt.cpp index 5159a25a48..7226ebf7cb 100644 --- a/modules/highgui/test/test_grfmt.cpp +++ b/modules/highgui/test/test_grfmt.cpp @@ -282,3 +282,12 @@ TEST(Highgui_ImreadVSCvtColor, regression) } #endif +#ifdef HAVE_JPEG +TEST(Highgui_Jpeg, encode_empty) +{ + cv::Mat img; + std::vector jpegImg; + + ASSERT_THROW(cv::imencode(".jpg", img, jpegImg), cv::Exception); +} +#endif