Boost GIL:将图像写入内存缓冲区失败问题排查
Boost.GIL写入内存缓冲区为空问题排查
问题描述
应用中周期性接收uint8_t数组形式的8位灰度图像,需转换为JPEG格式存入内存缓冲区(无法写入硬盘)。使用Boost.GIL v1.74时,写入文件正常,但写入内存缓冲区后缓冲区为空。相关代码如下:
#include <iostream> #include <fstream> #include <vector> #include <array> #include <boost/gil/extension/io/jpeg.hpp> //[...] uint8_t img[]; // 存储gray8_pixel_t格式的图像数据 int width; // 图像宽度 int height; // 图像高度 //[...] boost::gil::gray8c_view_t src = interleaved_view( width, height, (const boost::gil::gray8_pixel_t *) img, width); // 写入文件:正常工作 boost::gil::write_view("out.jpg", src, boost::gil::jpeg_tag()); // 写入内存缓冲区:out_buffer为空 std::stringstream out_buffer(std::ios::in | std::ios::binary); boost::gil::write_view(out_buffer, src, boost::gil::jpeg_tag()); // 检查缓冲区 out_buffer.seekg(0, std::ios::end); int size = out_buffer.tellg(); out_buffer.seekg(0, out_buffer.beg); // 尝试将缓冲区写入文件 std::ofstream output("myfile.jpg", std::ios::binary); output << out_buffer.rdbuf(); output.close();
错误原因
创建std::stringstream时指定了std::ios::in模式,该模式为只读模式,导致boost::gil::write_view无法向缓冲区写入数据,最终缓冲区为空。而文件写入正常是因为std::ofstream默认使用写模式,不受此影响。
解决方案
- 修正
std::stringstream的构造模式,使用写模式(std::ios::out)结合二进制模式(std::ios::binary):
std::stringstream out_buffer(std::ios::out | std::ios::binary); boost::gil::write_view(out_buffer, src, boost::gil::jpeg_tag());
- (可选)优化缓冲区大小检查逻辑:使用针对输出流的
seekp()和tellp()函数,替代输入流的seekg()和tellg(),逻辑更规范:
// 正确获取缓冲区大小 out_buffer.seekp(0, std::ios::end); std::streampos size = out_buffer.tellp(); out_buffer.seekp(0, std::ios::beg); // 重置到缓冲区开头
内容的提问来源于stack exchange,提问作者albezanc
相关产品推荐
相关产品推荐

