// SPDX-FileCopyrightText: 2024 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #include #include #include #include #include #include "../common/JFJochException.h" #include "../common/CompressedImage.h" #include "JFJochJPEG.h" // The encoder is the vendored stb_image_write, compiled into this file only and with static linkage, // so no JPEG symbol or header leaves it. File output is compiled out - the image goes to memory. #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_STATIC #define STBI_WRITE_NO_STDIO #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4244 4505) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif #include "stb/stb_image_write.h" #if defined(_MSC_VER) #pragma warning(pop) #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif static void AppendToString(void *context, void *data, int size) { static_cast(context)->append(static_cast(data), size); } std::string WriteJPEGToMem(const CompressedImage& image, int quality) { if (image.GetMode() != CompressedImageMode::RGB) throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Only RGB images allowed for JPEG saving"); // 65535 is the JPEG format's limit; stb also indexes the pixels with an int. const int64_t width = image.GetWidth(); const int64_t height = image.GetHeight(); if (width <= 0 || height <= 0 || width > 65535 || height > 65535 || width * height * 3 > INT_MAX) throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Image size not supported by JPEG encoder"); std::vector buffer; image.GetUncompressed(buffer); std::string ret; if (stbi_write_jpg_to_func(AppendToString, &ret, static_cast(width), static_cast(height), 3, buffer.data(), std::clamp(quality, 1, 100)) == 0) throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "JPEG encoding failed"); return ret; }