diff --git a/convert_image_to_webp.cpp b/convert_image_to_webp.cpp index 104f117..df3f96d 100644 --- a/convert_image_to_webp.cpp +++ b/convert_image_to_webp.cpp @@ -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; - *output_size = WebPEncodeRGB(resized_data, target_width, target_height, target_width * 3, quality_factor, &webp_output); + 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);