GDI +提供了一个Image类,您可以使用此类读取一种格式的图像文件,然后将该文件保存为另一种格式。但是如果我想解码一个jpeg文件(已经加载到内存中),我该怎么办?
答案 0 :(得分:1)
您可以使用SHCreateMemStream
和Gdiplus::Image::FromStream
#include <Window.h>
#include <Gdiplus.h>
#include <Shlwapi.h>
#include <atlbase.h>
...
CComPtr<IStream> stream;
stream.Attach(SHCreateMemStream(buf, bufsize));
Gdiplus::Image *image = Gdiplus::Image::FromStream(stream);
buf
包含jpeg数据(或任何其他兼容的图像格式),bufsize
是该数据的长度。
SHCreateMemStream
需要"Shlwapi.lib"
库。
示例:
void foo(HDC hdc)
{
//Read jpeg from input file in to buf:
HANDLE hfile = CreateFile(L"test.jpg",
GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (!hfile) return;
DWORD bufsize = GetFileSize(hfile, NULL);
BYTE *buf = new BYTE[bufsize];
DWORD temp;
ReadFile(hfile, buf, bufsize, &temp, 0);
//convert buf to IStream
CComPtr<IStream> stream;
stream.Attach(SHCreateMemStream(buf, bufsize));
//Read from IStream
Gdiplus::Bitmap *image = Gdiplus::Bitmap::FromStream(stream);
if (image)
{
Gdiplus::Graphics g(hdc);
g.DrawImage(image, 0, 0);
delete image;
}
delete[]buf;
CloseHandle(hfile);
}
编辑:评论中提到的更简单的方法:
IStream* stream = SHCreateMemStream(buf, bufsize);
Gdiplus::Image *image = Gdiplus::Image::FromStream(stream);
...
stream->Release();