Pages

Thursday, October 8, 2009

Load PNG- JPEG-images

Нужно воспользоваться GDI+.
Простейший пример можно взять в MSDN:
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
#pragma comment (lib,"gdiplus.lib")
using namespace Gdiplus;

INT main()
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

Image* image = new Image(L"two.jpg");
printf("The width of the image is %u.\n", image->GetWidth());
printf("The height of the image is %u.\n", image->GetHeight());

delete image;
GdiplusShutdown(gdiplusToken);
return 0;
}

Код:
#include <windows.h>
#include <gdiplus.h>
#pragma comment (lib,"gdiplus.lib")
using namespace Gdiplus;

подключает GDI+ к проэкту. Инициализация GDI+:
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

В конце работать нужно выполнить:
GdiplusShutdown(gdiplusToken);

Этот код загружает и PNG-файлы.
Если картинка находится в ресурсе, как всегда, нужно повозиться:
Image* LoadPicture(UINT nResID)
{
HMODULE hModule = GetModuleHandle(NULL);
HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(nResID), L"Binary");
if (hResource == NULL)
return NULL;

HGLOBAL hImage = LoadResource(hModule, hResource);
if (hImage == NULL)
return NULL;
LPVOID pImage = LockResource(hImage);
if (pImage == NULL)
return NULL;

Image* pPicture = NULL;
int size = SizeofResource(hModule, hResource);
HGLOBAL hBlock = GlobalAlloc(GHND, size);
if (hBlock != NULL)
{
LPVOID pBlock = GlobalLock(hBlock);
if (pBlock != NULL)
{
memmove(pBlock, pImage, size);
IStream* pStream;
if (CreateStreamOnHGlobal(hBlock, FALSE, &pStream) == S_OK)
pPicture = new Image(pStream);

GlobalUnlock(pBlock);
}
GlobalFree(hBlock);
}
return pPicture;
}

No comments:

Post a Comment