allow requesting file type, try to guess right quality

This commit is contained in:
tastytea 2022-06-11 06:14:20 +02:00
parent 6aa3b40faa
commit 78a7184250
Signed by: tastytea
SSH Key Fingerprint: SHA256:FBkvrOlhq5use1XEttyUGT4bUTDVA1ar9SgIc9P03cM
4 changed files with 40 additions and 1 deletions

View File

@ -71,7 +71,25 @@ void write(Magick::Image &img,
const std::optional<std::string_view> magick_force) {
std::string magick{magick_force.value_or(img.magick())};
std::transform(magick.begin(), magick.end(), magick.begin(), ::tolower);
const auto quality{[&img, &magick]() -> size_t {
if (img.quality() != 0) {
return img.quality(); // same as source
}
if (magick == "png") {
return 100; // highest compression
}
if (magick == "webp") {
if (img.magick() == "WEBP" || img.magick() == "PNG"
|| img.magick() == "GIF" || img.magick() == "SVG") {
return 100; // lossless
}
}
return 0; // default
}()};
img.magick(magick);
img.quality(quality);
Magick::Blob buffer;
img.write(&buffer);

View File

@ -34,7 +34,7 @@ namespace libravatarserv::image {
// write image with headers to stdout
void write(Magick::Image &img,
std::optional<std::string_view> magick_force = nullptr);
std::optional<std::string_view> magick_force = {});
} // namespace libravatarserv::image

View File

@ -20,6 +20,7 @@
#include "types.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <stdexcept>
@ -47,6 +48,25 @@ request_t parse(const std::string_view uri) {
std::transform(uri.begin() + offset, uri.begin() + pos, req.hash.begin(),
::tolower);
if (const auto pos_dot{req.hash.find('.')}; pos_dot != std::string::npos) {
std::string magick{req.hash.substr(pos_dot + 1)};
req.hash = req.hash.substr(0, pos_dot);
if (magick == "jpg") {
magick = "jpeg";
}
constexpr std::array<std::string_view, 4> allowed{
{"jpeg", "png", "gif", "webp"}
};
if (std::any_of(allowed.begin(), allowed.end(),
[magick](const std::string_view supplied) {
return magick == supplied;
})) {
req.magick = magick;
}
}
std::cout << req.hash << " - " << req.magick << '\n';
if (req.hash.size() == 64 && hash::is_valid(req.hash)) {
req.algo = algorithm_t::SHA256;
} else if (req.hash.size() == 32 && hash::is_valid(req.hash)) {

View File

@ -31,6 +31,7 @@ struct request_t {
algorithm_t algo;
std::int16_t size;
std::string fallback;
std::string magick;
};
} // namespace libravatarserv