我正在做的是使用 turbojpeg 读取灰度 jpeg,使用其数据创建 Gdiplus::Bitmap 并尝试使用 Gdiplus::Graphics 绘制它。一切都很好,直到我尝试绘制图像 - 我得到Unhandled exception at 0x74123193 in program.exe: 0xC0000005: Access violation reading location 0x04ac7848.
Bitmap 显然是正确创建的 - Bitmap::lastResult == Ok
。我的代码如下所示:
// Initialize GDI+.
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// creating program window
Graphics = new Gdiplus::Graphics(GetDC(hwnd));
Graphics->SetCompositingMode( Gdiplus::CompositingModeSourceCopy );
Graphics->SetCompositingQuality( Gdiplus::CompositingQualityHighSpeed );
Graphics->SetPixelOffsetMode( Gdiplus::PixelOffsetModeNone );
Graphics->SetSmoothingMode( Gdiplus::SmoothingModeNone );
Graphics->SetInterpolationMode( Gdiplus::InterpolationModeDefault );
// loading jpeg using turbojpeg
std::vector<unsigned char> data;
int width,
height;
std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary);
long begin,end;
begin = (long)ifs.tellg();
ifs.seekg (0, std::ios::end);
end = (long)ifs.tellg();
long size = end - begin;
ifs.seekg(0);
std::vector<char> jpegdata(size);
unsigned char* dataptr = reinterpret_cast<unsigned char*>(&jpegdata[0]);
ifs.read(&jpegdata[0], jpegdata.size());
tjhandle handle = tjInitDecompress();
tjDecompressHeader(handle, dataptr, jpegdata.size(), &width, &height);
data.resize(width * height);
tjDecompress2(handle, dataptr, jpegdata.size(), &data[0], width, width, height, TJPF_GRAY, 0);
tjDestroy(handle);
// creating Gdiplus::Bitmap
Gdiplus::Bitmap *bitmap = new Gdiplus::Bitmap(width,
height,
width * 8,
PixelFormat8bppIndexed,
(BYTE*)&data[0]);
// drawing bitmap
Graphics->DrawImage(bitmap, 0, 0);
异常被抛出
Graphics->DrawImage(bitmap, 0, 0);
这种行为的原因是什么?我究竟做错了什么?
edit
将正确的步幅设置为 user1837009 建议修复了异常。
我使用这个特殊的构造函数是有原因的——我需要让图像数据尽可能原始、灰度、每像素 8 位来进行一些转换。而且我相当确定这就是我data
在调用tjDecompress2
. 不幸的是,似乎不支持 8 位灰度像素格式,只有 PixelFormat16bppGrayScale,即 16 位。关于如何解决这个问题的任何想法?