tomato-testing/src/image_loader_sdl_bmp.cpp

80 lines
1.7 KiB
C++
Raw Normal View History

2023-07-30 16:00:55 +02:00
#include "./image_loader_sdl_bmp.hpp"
#include <SDL3/SDL.h>
2023-08-02 19:24:51 +02:00
#include <iostream>
#include <cassert>
2023-08-02 19:24:51 +02:00
2023-07-30 16:00:55 +02:00
ImageLoaderSDLBMP::ImageInfo ImageLoaderSDLBMP::loadInfoFromMemory(const uint8_t* data, uint64_t data_size) {
ImageInfo res;
2024-03-28 17:13:44 +01:00
auto* ios = SDL_IOFromConstMem(data, data_size);
2023-07-30 16:00:55 +02:00
2024-10-05 15:44:29 +02:00
SDL_Surface* surf = SDL_LoadBMP_IO(ios, true);
2023-07-30 16:00:55 +02:00
if (surf == nullptr) {
return res;
}
assert(surf->w >= 0);
assert(surf->h >= 0);
2023-07-30 16:00:55 +02:00
res.width = surf->w;
res.height = surf->h;
res.file_ext = "bmp";
2023-07-30 16:00:55 +02:00
SDL_DestroySurface(surf);
return res;
}
ImageLoaderSDLBMP::ImageResult ImageLoaderSDLBMP::loadFromMemoryRGBA(const uint8_t* data, uint64_t data_size) {
2024-03-28 17:13:44 +01:00
auto* ios = SDL_IOFromConstMem(data, data_size);
2023-07-30 16:00:55 +02:00
2024-10-05 15:44:29 +02:00
SDL_Surface* surf = SDL_LoadBMP_IO(ios, true);
2023-07-30 16:00:55 +02:00
if (surf == nullptr) {
return {};
2023-07-30 16:00:55 +02:00
}
2024-07-18 12:22:15 +02:00
SDL_Surface* conv_surf = SDL_ConvertSurface(surf, SDL_PIXELFORMAT_RGBA32);
2023-07-30 16:00:55 +02:00
SDL_DestroySurface(surf);
if (conv_surf == nullptr) {
return {};
2023-07-30 16:00:55 +02:00
}
assert(conv_surf->w >= 0);
assert(conv_surf->h >= 0);
2023-07-30 16:00:55 +02:00
if (conv_surf->w > 16*1024 || conv_surf->h > 10*1024) {
std::cerr << "IL_SDLBMP error: image too large\n";
return {};
}
ImageResult res;
if (SDL_MUSTLOCK(conv_surf)) {
2024-09-09 11:49:32 +02:00
if (!SDL_LockSurface(conv_surf)) {
std::cerr << "IL_SDLBMP error: " << SDL_GetError() << "\n";
SDL_DestroySurface(conv_surf);
return {};
}
}
res.width = conv_surf->w;
res.height = conv_surf->h;
res.file_ext = "bmp";
2023-07-30 16:00:55 +02:00
auto& new_frame = res.frames.emplace_back();
new_frame.ms = 0;
new_frame.data = {(const uint8_t*)conv_surf->pixels, ((const uint8_t*)conv_surf->pixels) + (conv_surf->w*conv_surf->h*4)};
2023-07-30 16:00:55 +02:00
if (SDL_MUSTLOCK(conv_surf)) {
SDL_UnlockSurface(conv_surf);
}
2023-07-30 16:00:55 +02:00
SDL_DestroySurface(conv_surf);
2023-08-02 19:24:51 +02:00
std::cout << "IL_SDLBMP: loaded img " << res.width << "x" << res.height << "\n";
2023-07-30 16:00:55 +02:00
return res;
}