///////////////////////////////////////////////////////
| 360 | |
| 361 | //////////////////////////////////////////////////////////// |
| 362 | bool Image::loadFromStream(InputStream& stream) |
| 363 | { |
| 364 | // Make sure that the stream's reading position is at the beginning |
| 365 | if (!stream.seek(0).has_value()) |
| 366 | { |
| 367 | err() << "Failed to seek image stream" << std::endl; |
| 368 | return false; |
| 369 | } |
| 370 | |
| 371 | // Read a (possible) QOI magic number |
| 372 | std::array<char, 4> qoiMagicNumber{}; |
| 373 | const auto qoiMagicCount = stream.read(qoiMagicNumber.data(), qoiMagicNumber.size()); |
| 374 | |
| 375 | const auto seekToStartResult = stream.seek(0); |
| 376 | if (!seekToStartResult.has_value()) |
| 377 | { |
| 378 | err() << "Failed to seek back the image stream" << std::endl; |
| 379 | return false; |
| 380 | } |
| 381 | |
| 382 | // Read the QOI file if it's valid |
| 383 | if (qoiMagicCount.has_value() && isQoiMagicNumber(std::string_view(qoiMagicNumber.data(), *qoiMagicCount))) |
| 384 | { |
| 385 | if (const auto streamSize = stream.getSize(); streamSize.has_value()) |
| 386 | { |
| 387 | // Read in the file contents since QOI doesn't support streams |
| 388 | std::vector<char> buffer(*streamSize); |
| 389 | const auto readDataSize = stream.read(buffer.data(), *streamSize); |
| 390 | |
| 391 | qoi_desc formatDesc = {}; |
| 392 | if (const auto ptr = MallocPtr(qoi_decode(buffer.data(), static_cast<int>(*readDataSize), &formatDesc, 4))) |
| 393 | { |
| 394 | const Vector2u imageSize = {formatDesc.width, formatDesc.height}; |
| 395 | resize(imageSize, static_cast<const uint8_t*>(ptr.get())); |
| 396 | return true; |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // Setup the stb_image callbacks |
| 402 | stbi_io_callbacks callbacks; |
| 403 | callbacks.read = read; |
| 404 | callbacks.skip = skip; |
| 405 | callbacks.eof = eof; |
| 406 | |
| 407 | // Load the image and get a pointer to the pixels in memory |
| 408 | Vector2i imageSize; |
| 409 | int channels = 0; |
| 410 | if (const auto ptr = StbPtr( |
| 411 | stbi_load_from_callbacks(&callbacks, &stream, &imageSize.x, &imageSize.y, &channels, STBI_rgb_alpha))) |
| 412 | { |
| 413 | resize(Vector2u(imageSize), ptr.get()); |
| 414 | return true; |
| 415 | } |
| 416 | |
| 417 | // Error, failed to load the image |
| 418 | err() << "Failed to load image from stream. Reason: " << stbi_failure_reason() << std::endl; |
| 419 | return false; |
no test coverage detected