75 lines
2.3 KiB
C++
75 lines
2.3 KiB
C++
#pragma warning(push, 0)
|
|
#define STB_IMAGE_IMPLEMENTATION
|
|
#include <stb_image.h>
|
|
#define STB_IMAGE_RESIZE_IMPLEMENTATION
|
|
#include <stb_image_resize2.h>
|
|
#pragma warning(pop)
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <image.h>
|
|
|
|
extern "C" {
|
|
uint32_t* image_load(const char* filename, int* width, int* height) {
|
|
int n;
|
|
unsigned char* data = stbi_load(filename, width, height, &n, 4); // force 4 channels (RGBA)
|
|
if (!data) return nullptr;
|
|
|
|
// Convert RGBA to ARGB
|
|
uint32_t* out = (uint32_t*)malloc(*width * *height * sizeof(uint32_t));
|
|
if (!out) {
|
|
stbi_image_free(data);
|
|
return nullptr;
|
|
}
|
|
for (int i = 0; i < *width * *height; ++i) {
|
|
uint8_t r = data[4*i + 0];
|
|
uint8_t g = data[4*i + 1];
|
|
uint8_t b = data[4*i + 2];
|
|
uint8_t a = data[4*i + 3];
|
|
out[i] = (a << 24) | (r << 16) | (g << 8) | b;
|
|
}
|
|
stbi_image_free(data);
|
|
return out;
|
|
}
|
|
|
|
uint32_t* image_load_resized(const char* filename, int desired_width, int desired_height) {
|
|
int original_width, original_height, n;
|
|
unsigned char* data = stbi_load(filename, &original_width, &original_height, &n, 4);
|
|
if (!data) return nullptr;
|
|
|
|
// Allocate buffer for resized image
|
|
uint32_t* resized = (uint32_t*)malloc(desired_width * desired_height * 4);
|
|
if (!resized) {
|
|
stbi_image_free(data);
|
|
return nullptr;
|
|
}
|
|
|
|
// Resize the image
|
|
stbir_resize_uint8_linear(data, original_width, original_height, 0,
|
|
(unsigned char* )resized, desired_width, desired_height, 0,
|
|
STBIR_RGBA);
|
|
|
|
stbi_image_free(data);
|
|
|
|
// In-place conversion from RGBA to ARGB
|
|
// We iterate backwards to ensure we don't overwrite bytes before reading them,
|
|
// though since we are working within the same 4-byte boundaries, forward works too!
|
|
for (int i = 0; i < desired_width * desired_height; ++i) {
|
|
uint8_t* pixel = (uint8_t*)&resized[i];
|
|
uint8_t r = pixel[0];
|
|
uint8_t g = pixel[1];
|
|
uint8_t b = pixel[2];
|
|
uint8_t a = pixel[3];
|
|
|
|
resized[i] = ((uint32_t)a << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
|
|
}
|
|
|
|
return resized;
|
|
}
|
|
|
|
void image_free(uint32_t* data) {
|
|
free(data);
|
|
}
|
|
|
|
} // extern "C"
|