Skip to content

Instantly share code, notes, and snippets.

@yorung
Created February 28, 2015 04:45
Show Gist options
  • Save yorung/a15ede3bef5676320877 to your computer and use it in GitHub Desktop.
Save yorung/a15ede3bef5676320877 to your computer and use it in GitHub Desktop.
Load OpenGL textures using GDI+
namespace Gdiplus {
using std::min;
using std::max;
}
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
static GLuint LoadTextureViaOS(const char* name)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
WCHAR wc[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));
Gdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);
int w = (int)image->GetWidth();
int h = (int)image->GetHeight();
Gdiplus::Rect rc(0, 0, w, h);
Gdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;
image->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);
std::vector<uint32_t> col;
col.resize(w * h);
for (int y = 0; y < h; y++) {
memcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);
for (int x = 0; x < w; x++) {
uint32_t& c = col[y * w + x];
c = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);
}
}
image->UnlockBits(bitmapData);
delete bitmapData;
delete image;
Gdiplus::GdiplusShutdown(gdiplusToken);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
@superwills
Copy link

I have a complete working example here https://bobobobo.wordpress.com/2021/09/17/gdi-to-opengl/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment