bool imencode( const String& ext, InputArray _image, std::vector<uchar>& buf, const std::vector<int>& params ) { CV_TRACE_FUNCTION(); Mat image = _image.getMat(); int channels = image.channels(); CV_Assert( channels == 1 || channels == 3 || channels == 4 ); ImageEncoder encoder = findEncoder( ext ); if( !encoder ) CV_Error( CV_StsError, "could not find encoder for the specified extension" ); if( !encoder->isFormatSupported(image.depth()) ) { CV_Assert( encoder->isFormatSupported(CV_8U) ); Mat temp; image.convertTo(temp, CV_8U); image = temp; } bool code; if( encoder->setDestination(buf) ) { code = encoder->write(image, params); encoder->throwOnEror(); CV_Assert( code ); } else { 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 ); long pos = ftell(f); buf.resize((size_t)pos); fseek( f, 0, SEEK_SET ); buf.resize(fread( &buf[0], 1, buf.size(), f )); fclose(f); remove(filename.c_str()); } return code; }
bool imencode( const string& ext, const Mat& image, vector<uchar>& buf, const vector<int>& params ) { Mat temp; const Mat* pimage = ℑ int channels = image.channels(); CV_Assert( channels == 1 || channels == 3 || channels == 4 ); ImageEncoder encoder = findEncoder( ext ); if( encoder.empty() ) CV_Error( CV_StsError, "could not find encoder for the specified extension" ); if( !encoder->isFormatSupported(image.depth()) ) { CV_Assert( encoder->isFormatSupported(CV_8U) ); image.convertTo(temp, CV_8U); pimage = &temp; } bool code; if( encoder->setDestination(buf) ) { code = encoder->write(image, params); CV_Assert( code ); } else { char fnamebuf[L_tmpnam]; const char* filename = tmpnam(fnamebuf); if(filename[0] == '\\') filename++; code = encoder->setDestination(filename); CV_Assert( code ); code = encoder->write(image, params); CV_Assert( code ); FILE* f = fopen( filename, "rb" ); CV_Assert(f != 0); fseek( f, 0, SEEK_END ); long pos = ftell(f); buf.resize((size_t)pos); fseek( f, 0, SEEK_SET ); buf.resize(fread( &buf[0], 1, buf.size(), f )); fclose(f); remove(filename); } return code; }
static bool imwrite_( const string& filename, const Mat& image, const vector<int>& params, bool flipv ) { Mat temp; const Mat* pimage = ℑ CV_Assert( image.channels() == 1 || image.channels() == 3 || image.channels() == 4 ); ImageEncoder encoder = findEncoder( filename ); if( encoder.empty() ) CV_Error( CV_StsError, "could not find a writer for the specified extension" ); if( !encoder->isFormatSupported(image.depth()) ) { CV_Assert( encoder->isFormatSupported(CV_8U) ); image.convertTo( temp, CV_8U ); pimage = &temp; } if( flipv ) { flip(*pimage, temp, 0); pimage = &temp; } encoder->setDestination( filename ); bool code = encoder->write( *pimage, params ); // CV_Assert( code ); return code; }