MayaFlux 0.3.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches

◆ load() [1/2]

std::optional< ImageData > MayaFlux::IO::ImageReader::load ( const std::filesystem::path &  path,
int  desired_channels = 4 
)
static

Load image from file (static utility)

Parameters
pathImage file path
desired_channelsForce channel count (0 = keep original, 4 = RGBA)
Returns
Image data or nullopt on failure

Definition at line 262 of file ImageReader.cpp.

263{
264 if (!std::filesystem::exists(path)) {
266 "Image file not found: {}", path.string());
267 return std::nullopt;
268 }
269
270 std::ifstream file(path, std::ios::binary | std::ios::ate);
271 if (!file.is_open()) {
273 "Failed to open image file: {}", path.string());
274 return std::nullopt;
275 }
276
277 std::streamsize file_size = file.tellg();
278 file.seekg(0, std::ios::beg);
279
280 std::vector<unsigned char> file_buffer(file_size);
281 if (!file.read(reinterpret_cast<char*>(file_buffer.data()), file_size)) {
283 "Failed to read image file: {}", path.string());
284 return std::nullopt;
285 }
286 file.close();
287
288 int width {}, height {}, channels {};
289
290 if (desired_channels == 0) {
291 stbi_info_from_memory(file_buffer.data(), static_cast<int>(file_buffer.size()),
292 &width, &height, &channels);
293 if (channels == 3) {
294 desired_channels = 4;
295 }
296 }
297
298 unsigned char* pixels = stbi_load_from_memory(
299 file_buffer.data(),
300 static_cast<int>(file_buffer.size()),
301 &width, &height, &channels,
302 desired_channels);
303
304 if (!pixels) {
306 "Failed to decode image: {} - {}",
307 path.string(), stbi_failure_reason());
308 return std::nullopt;
309 }
310
311 int result_channels = (desired_channels != 0) ? desired_channels : channels;
312
314 "Loaded image: {} ({}x{}, {} channels{})",
315 path.filename().string(), width, height, result_channels,
316 (channels == 3 && result_channels == 4) ? " [RGB→RGBA]" : "");
317
318 ImageData result;
319 size_t data_size = static_cast<size_t>(width) * height * result_channels;
320 result.pixels.resize(data_size);
321 std::memcpy(result.pixels.data(), pixels, data_size);
322
323 result.width = width;
324 result.height = height;
325 result.channels = result_channels;
326
327 switch (result_channels) {
328 case 1:
329 result.format = Portal::Graphics::ImageFormat::R8;
330 break;
331 case 2:
333 break;
334 case 4:
336 break;
337 default:
339 "Unsupported channel count: {}", result_channels);
340 stbi_image_free(pixels);
341 return std::nullopt;
342 }
343
344 stbi_image_free(pixels);
345 return result;
346}
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
@ FileIO
Filesystem I/O operations.
@ IO
Networking, file handling, streaming.

References MayaFlux::Journal::FileIO, MayaFlux::Journal::IO, MF_ERROR, MF_INFO, MayaFlux::IO::ImageData::pixels, MayaFlux::Portal::Graphics::R8, MayaFlux::Portal::Graphics::RG8, and MayaFlux::Portal::Graphics::RGBA8.