win32加载图片获得像素值

时间:2023-03-09 09:50:42
win32加载图片获得像素值

  在写光栅渲染器时,需要加载图片获得像素以便进行纹理插值,试了几种方法发现下面这种比价简单,效率也可以接受

  Texture2D是我自己定义的类,其中m_pixelBuffer是一个动态二维数组,每个元素为ZCFLOAT3(自定义类型用来保存颜色rgb值)。

 #include "LoadBitmap.h"
#include <windows.h>
#include <gdiplus.h> #include <iostream>
#include <fstream>
#include <sstream> #pragma comment(lib, "gdiplus.lib")
using namespace std;
using namespace Gdiplus; Texture2D MathUtil::LoadBitmapToColorArray(wstring filePath)
{
GdiplusStartupInput gdiplusstartupinput;
ULONG_PTR gdiplustoken;
GdiplusStartup(&gdiplustoken, &gdiplusstartupinput, nullptr); Bitmap* bmp = new Bitmap(filePath.c_str());
if (!bmp)
{
MessageBox(nullptr, "error", "picture path is null!", MB_OK);
delete bmp;
GdiplusShutdown(gdiplustoken);
return Texture2D(,);
}
else
{
UINT height = bmp->GetHeight();
UINT width = bmp->GetWidth();
//Texture2D
Texture2D texture(width, height); Color color; for (int y = ; y < height; y++)
for (int x = ; x < width; x++)
{
bmp->GetPixel(x, y, &color); texture.m_pixelBuffer[x][y] = ZCFLOAT3(
color.GetRed() / .f,
color.GetGreen() / .f,
color.GetBlue() / .f
);
} delete bmp;
GdiplusShutdown(gdiplustoken);
return texture;
} }