MayaFlux 0.2.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 229 of file ImageReader.cpp.

230{
231 if (!std::filesystem::exists(path)) {
233 "Image file not found: {}", path.string());
234 return std::nullopt;
235 }
236
237 std::ifstream file(path, std::ios::binary | std::ios::ate);
238 if (!file.is_open()) {
240 "Failed to open image file: {}", path.string());
241 return std::nullopt;
242 }
243
244 std::streamsize file_size = file.tellg();
245 file.seekg(0, std::ios::beg);
246
247 std::vector<unsigned char> file_buffer(file_size);
248 if (!file.read(reinterpret_cast<char*>(file_buffer.data()), file_size)) {
250 "Failed to read image file: {}", path.string());
251 return std::nullopt;
252 }
253 file.close();
254
255 int width {}, height {}, channels {};
256 unsigned char* pixels = stbi_load_from_memory(
257 file_buffer.data(),
258 static_cast<int>(file_buffer.size()),
259 &width, &height, &channels,
260 desired_channels);
261
262 if (!pixels) {
264 "Failed to decode image: {} - {}",
265 path.string(), stbi_failure_reason());
266 return std::nullopt;
267 }
268
270 switch (channels) {
271 case 1:
273 break;
274 case 2:
276 break;
277 case 3:
279 break;
280 case 4:
282 break;
283 default:
285 "Unsupported channel count: {}", channels);
286 stbi_image_free(pixels);
287 return std::nullopt;
288 }
289
290 ImageData result;
291
292 size_t data_size = static_cast<long>(width * height) * channels;
293 result.pixels.resize(data_size);
294 std::memcpy(result.pixels.data(), pixels, data_size);
295
296 result.width = width;
297 result.height = height;
298 result.format = format;
299
300 stbi_image_free(pixels);
301
303 "Loaded image: {} ({}x{}, {} channels)",
304 path.filename().string(), width, height, channels);
305
306 return result;
307}
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
@ FileIO
Filesystem I/O operations.
std::string format(format_string< std::remove_cvref_t< Args >... > fmt_str, Args &&... args)
Definition Format.hpp:30
@ IO
Networking, file handling, streaming.
ImageFormat
User-friendly image format enum.

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