gpt4 book ai didi

c++ - GDI+:绘制位图时出现未处理的异常

转载 作者:行者123 更新时间:2023-11-28 03:12:10 31 4
gpt4 key购买 nike

我正在做的是使用 turbojpeg 读取灰度 jpeg,使用其数据创建 Gdiplus::Bitmap 并尝试使用 Gdiplus::Graphics 绘制它。一切都很好,直到我尝试绘制图像 - 我在 program.exe 中的 0x74123193 处得到 Unhandled exception: 0xC0000005: Access violation reading location 0x04ac7848. 位图显然已正确创建 - 位图::lastResult == 好的。我的代码如下所示:

// 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);

这种行为的原因是什么?我做错了什么?

编辑

按照 user1837009 的建议设置正确的步幅修复了异常。

我使用这个特殊的构造函数是有原因的——我需要尽可能原始的图像数据,灰度,每像素 8 位来进行一些转换。我相当确定这就是我在调用 tjDecompress2 后在 data 变量中拥有的内容。不幸的是,似乎不支持 8 位灰度像素格式,仅支持 16 位的 PixelFormat16bppGrayScale。关于如何解决这个问题的任何想法?

最佳答案

这里有几处错误:

  1. Jpeg 文件是包含压缩数据的复杂文件。您正在读入整个文件,并将其视为基本位图。这根本不可能工作(这类似于将 CD 放在老式乙烯基留声机上,并想知道为什么它没有发出任何/正确的声音)。
  2. 位图的步长是一行像素与下一行像素之间的距离(以字节为单位)。
  3. 我不相信,即使 jpeg 数据是正确的,您的图像也将具有像素格式 PixelFormat8bppIndexed

要解决上述问题中的 2 点和 3 点非常简单(使用正确的步幅和正确的像素格式)。修复点 1 意味着您必须以理智的方式读入 JPEG 图像。

但是,当然有一个更简单的解决方案:使用 Bitmap.Bitmap(const WCHAR*, BOOL) ,它将直接加载 JPEG 图像,而无需处理与“如何解码 JPEG 图像”相关的任何事情。

关于c++ - GDI+:绘制位图时出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18150089/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com