srctree

Robin Linden parent 1a3807ef a4f293a4
img: Support printing GIF dimensions in the example

inlinesplit
img/img_example.cpp added: 38, removed: 9, total 29
@@ -2,6 +2,7 @@
//
// SPDX-License-Identifier: BSD-2-Clause
 
#include "img/gif.h"
#include "img/png.h"
 
#include <SFML/Graphics/Image.hpp>
@@ -14,12 +15,16 @@
#include <cstddef>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
 
using namespace std::literals;
 
using Image = std::variant<img::Gif, img::Png>;
 
int main(int argc, char **argv) {
if (argc != 2 && argc != 3) {
std::cerr << "Usage: " << (argv[0] ? argv[0] : "<bin>") << " [--metadata] <image_file>\n";
@@ -34,31 +39,55 @@ int main(int argc, char **argv) {
return 1;
}
 
auto img = img::Png::from(std::move(fs));
if (!img) {
std::cerr << "Unable to parse " << file_name << " as a png\n";
auto maybe_img = [&]() -> std::optional<Image> {
if (auto png = img::Png::from(fs)) {
return *png;
}
 
fs.clear();
fs.seekg(0);
 
if (auto gif = img::Gif::from(fs)) {
return *gif;
}
 
return std::nullopt;
}();
 
if (!maybe_img) {
std::cerr << "Unable to parse " << file_name << " as an image\n";
return 1;
}
 
auto img = *maybe_img;
auto [width, height] = std::visit([](auto const &v) { return std::pair{v.width, v.height}; }, img);
 
if (argc == 3 && argv[1] == "--metadata"sv) {
std::cout << "Dimensions: " << img->width << 'x' << img->height << '\n';
std::cout << "Dimensions: " << width << 'x' << height << '\n';
return 0;
}
 
if (img->bytes.size() != (static_cast<std::size_t>(img->width) * img->height * 4)) {
if (!std::holds_alternative<img::Png>(img)) {
std::cerr << "Only --metadata is supported for this file-type\n";
return 1;
}
 
auto const &bytes = std::get<img::Png>(img).bytes;
 
if (bytes.size() != (static_cast<std::size_t>(width) * height * 4)) {
std::cerr << "Unsupported pixel format, expected 32-bit rgba pixels\n";
return 1;
}
 
auto const &desktop = sf::VideoMode::getDesktopMode();
std::uint32_t window_width = std::clamp(img->width, 100u, desktop.width);
std::uint32_t window_height = std::clamp(img->height, 100u, desktop.height);
std::uint32_t window_width = std::clamp(width, 100u, desktop.width);
std::uint32_t window_height = std::clamp(height, 100u, desktop.height);
sf::RenderWindow window{sf::VideoMode{window_width, window_height}, "img"};
window.setVerticalSyncEnabled(true);
window.setActive(true);
 
sf::Image sf_image{};
sf_image.create(img->width, img->height, img->bytes.data());
sf_image.create(width, height, bytes.data());
sf::Texture texture{};
texture.loadFromImage(sf_image);
sf::Sprite sprite{};