Created
July 24, 2022 21:38
-
-
Save audinue/58584346735114629dd02be93a4f6478 to your computer and use it in GitHub Desktop.
Load bitmap using GDI+ in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <windows.h> | |
#include <gdiplus.h> | |
Bitmap* loadBitmap(char* file) | |
{ | |
int length = strlen(file) + 1; | |
wchar_t* fileW = (wchar_t*) malloc(length * sizeof(wchar_t)); | |
if (!fileW) | |
die("Unable to allocate wide string"); | |
if (mbstowcs(fileW, file, length) == -1) | |
die("Unable to create wide string"); | |
GpBitmap* gpBitmap; | |
if (GdipCreateBitmapFromFile(fileW, &gpBitmap) != Ok) | |
die("Unable to create bitmap"); | |
int width; | |
int height; | |
if (GdipGetImageWidth(gpBitmap, &width) != Ok || GdipGetImageHeight(gpBitmap, &height) != Ok) | |
die("Unable to get bitmap dimension"); | |
char* bytes = malloc(width * height * 4); | |
if (!bytes) | |
die("Unable to allocate bytes"); | |
BitmapData data = { .Scan0 = bytes, .Stride = width * 4 }; | |
GpRect rect = { .Width = width, .Height = height }; | |
if (GdipBitmapLockBits(gpBitmap, &rect, ImageLockModeRead | ImageLockModeUserInputBuf, PixelFormat32bppARGB, &data) != Ok) | |
die("Unable to lock bitmap"); | |
Bitmap* bitmap = (Bitmap*) malloc(sizeof(Bitmap)); | |
if (!bitmap) | |
die("Unable to allocate bitmap"); | |
bitmap->bytes = bytes; | |
bitmap->width = width; | |
bitmap->height = height; | |
GdipDisposeImage(gpBitmap); | |
free(fileW); | |
return bitmap; | |
} | |
// Need some initialization | |
ULONG_PTR token; | |
GdiplusStartupInput input = { .GdiplusVersion = 1 }; | |
GdiplusStartup(&token, &input, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment