roo_e/client/src/gui/image.c
2022-06-24 18:41:27 -05:00

51 lines
1.1 KiB
C

#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "thirdparty/stb_image.h"
#include "image.h"
#define PIXEL_COMPONENTS 3
SurfaceT *imageLoad(char *filename) {
int w; // These unspecified ints are intentional.
int h;
int n;
int32_t r;
int32_t x;
int32_t y;
SurfaceT *i = NULL;
SurfaceT *t = surfaceGet();
unsigned char *raw = NULL;
char *cached = NULL;
// Has this image been cached?
cached = utilFileExtensionChange(filename, "");
i = surfaceLoad(cached);
if (!i) {
// Nope. Decode PNG and save raw.
r = stbi_info(filename, &w, &h, &n);
if (r) {
raw = stbi_load(filename, &w, &h, &n, PIXEL_COMPONENTS);
if (raw) {
i = surfaceCreate(w, h);
surfaceSet(i);
n = 0;
for (y=0; y<h; y++) {
for (x=0; x<w; x++) {
surfacePixelSet(x, y, surfaceColorMake(raw[n], raw[n + 1], raw[n + 2]));
n += PIXEL_COMPONENTS;
}
}
surfaceSet(t);
stbi_image_free(raw);
surfaceSave(i, cached);
}
}
}
DEL(cached);
return i;
}