libravatarserv/src/image.cpp

74 lines
2.4 KiB
C++

/* This file is part of libravatarserv.
* Copyright © 2022 tastytea <tastytea@tastytea.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "image.hpp"
#include "types.hpp"
#include <identiconpp.hpp>
#include <Magick++/Blob.h>
#include <Magick++/Image.h>
#include <algorithm>
#include <cstdint>
#include <ios>
#include <iostream>
namespace libravatarserv::image {
void write(Magick::Image &img) {
string magick{img.magick()};
std::transform(magick.begin(), magick.end(), magick.begin(), ::tolower);
Magick::Blob buffer;
img.write(&buffer);
std::cout << "Content-Type: image/" << magick << '\n';
std::cout << "Content-Length: " << buffer.length() << "\n\n";
std::cout.write(static_cast<const char *>(buffer.data()),
static_cast<std::streamsize>(buffer.length()));
}
Magick::Image generate_identicon(const request_t &req) {
const auto padwidth{[&req]() -> std::uint8_t {
if (req.size < 60) {
return 0;
}
return static_cast<std::uint8_t>(std::max(req.size / 10, 10));
}()};
Identiconpp identicon(5, 5, Identiconpp::algorithm::sigil, "fefefeff",
{
// The same colors ivatar uses.
"2d4fffff", // Blue
"feb42cff", // Yellow
"e279eaff", // Bright pink
"1eb3fdff", // Cyan
"E84D41ff", // Red
"31CB73ff", // Green
"8D45AAff" // Dark pink
},
{padwidth, padwidth});
Magick::Image img{
identicon.generate(req.hash, static_cast<std::uint8_t>(req.size))};
img.magick("PNG");
return img;
}
} // namespace libravatarserv::image