增加了alpha通道的选项

This commit is contained in:
kura 2024-12-20 15:41:32 +08:00
parent f20b8ebd66
commit 801ce60031

View File

@ -9,12 +9,11 @@
extern "C" {
// 将输入的 JPG/PNG 数据转换为 WebP并返回 WebP 数据
unsigned char *convert_image_to_webp(const uint8_t *input_data, size_t input_size, int target_width, int target_height, float quality_factor, size_t *output_size) {
unsigned char *convert_image_to_webp(const uint8_t *input_data, size_t input_size, int target_width, int target_height, float quality_factor, size_t *output_size, int preserve_alpha = 0) {
int width, height, channels;
// 使用 stb_image 解码输入图像(强制加载为 RGB 而非 RGBA
unsigned char *decoded_data = stbi_load_from_memory(input_data, input_size, &width, &height, &channels, 3); // 强制加载为 RGB
// 使用 stb_image 解码输入图像(根据 preserve_alpha 决定加载通道数)
unsigned char *decoded_data = stbi_load_from_memory(input_data, input_size, &width, &height, &channels, preserve_alpha ? 4 : 3); // 根据是否保留 alpha 通道加载
if (!decoded_data) {
return nullptr; // 图像解码失败
@ -24,7 +23,7 @@ extern "C" {
unsigned char *resized_data = decoded_data;
if (target_width > 0 && target_height > 0) {
// 分配用于存储调整大小后图像的缓冲区
resized_data = (unsigned char *)malloc(target_width * target_height * 3); // RGB 3 通道
resized_data = (unsigned char *)malloc(target_width * target_height * (preserve_alpha ? 4 : 3)); // 根据是否保留 alpha 通道调整缓冲区大小
if (!resized_data) {
// 内存分配失败的处理
@ -35,7 +34,7 @@ extern "C" {
// 使用 stb_image_resize 调整图像大小
int result = stbir_resize_uint8(decoded_data, width, height, 0,
resized_data, target_width, target_height, 0, 3);
resized_data, target_width, target_height, 0, preserve_alpha ? 4 : 3);
if (!result) {
// 如果调整大小失败,释放已分配的内存
@ -51,7 +50,11 @@ extern "C" {
// 使用 libwebp 的有损编码函数WebPEncodeRGB将 RGB 图像编码为 WebP
unsigned char *webp_output = NULL;
if (preserve_alpha) {
*output_size = WebPEncodeRGBA(resized_data, target_width, target_height, target_width * 4, quality_factor, &webp_output);
} else {
*output_size = WebPEncodeRGB(resized_data, target_width, target_height, target_width * 3, quality_factor, &webp_output);
}
// 释放解码后的图像内存
stbi_image_free(decoded_data);