///////////////////////////////////////////////////////
| 499 | |
| 500 | //////////////////////////////////////////////////////////// |
| 501 | std::optional<std::vector<std::uint8_t>> Image::saveToMemory(std::string_view format) const |
| 502 | { |
| 503 | // Make sure the image is not empty |
| 504 | if (!m_pixels.empty() && m_size.x > 0 && m_size.y > 0) |
| 505 | { |
| 506 | // Choose function based on format |
| 507 | const std::string specified = toLower(std::string(format)); |
| 508 | const Vector2i convertedSize = Vector2i(m_size); |
| 509 | |
| 510 | std::vector<std::uint8_t> buffer; |
| 511 | |
| 512 | if (specified == "bmp") |
| 513 | { |
| 514 | // BMP format |
| 515 | if (stbi_write_bmp_to_func(bufferFromCallback, &buffer, convertedSize.x, convertedSize.y, 4, m_pixels.data())) |
| 516 | return buffer; |
| 517 | } |
| 518 | else if (specified == "tga") |
| 519 | { |
| 520 | // TGA format |
| 521 | if (stbi_write_tga_to_func(bufferFromCallback, &buffer, convertedSize.x, convertedSize.y, 4, m_pixels.data())) |
| 522 | return buffer; |
| 523 | } |
| 524 | else if (specified == "png") |
| 525 | { |
| 526 | // PNG format |
| 527 | if (stbi_write_png_to_func(bufferFromCallback, &buffer, convertedSize.x, convertedSize.y, 4, m_pixels.data(), 0)) |
| 528 | return buffer; |
| 529 | } |
| 530 | else if (specified == "jpg" || specified == "jpeg") |
| 531 | { |
| 532 | // JPG format |
| 533 | if (stbi_write_jpg_to_func(bufferFromCallback, &buffer, convertedSize.x, convertedSize.y, 4, m_pixels.data(), 90)) |
| 534 | return buffer; |
| 535 | } |
| 536 | else if (specified == "qoi") |
| 537 | { |
| 538 | qoi_desc desc; |
| 539 | desc.width = m_size.x; |
| 540 | desc.height = m_size.y; |
| 541 | desc.channels = 4; |
| 542 | desc.colorspace = QOI_LINEAR; |
| 543 | |
| 544 | int dataSize = 0; |
| 545 | if (const auto ptr = MallocPtr(qoi_encode(m_pixels.data(), &desc, &dataSize))) |
| 546 | { |
| 547 | // Copy the returned data into the buffer |
| 548 | const auto* source = static_cast<std::uint8_t*>(ptr.get()); |
| 549 | buffer.reserve(static_cast<size_t>(dataSize)); |
| 550 | std::copy(source, source + dataSize, std::back_inserter(buffer)); |
| 551 | return buffer; |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | err() << "Failed to save image with format " << std::quoted(format) << std::endl; |
| 557 | return std::nullopt; |
| 558 | } |
no test coverage detected