如何在c++中将图像编码为webp?

问题描述 投票:0回答:1

我需要一种将img类型(jpg、png)的二进制数据转换为webp的方法。

首先我尝试使用 libwebp api,但对于编码,我需要图像的 RGB 表示和许多其他内容。对我来说很舒服的是使用 cwebp.exe 程序,但为此我需要使用 CreateProcess 并首先将我的二进制 img 数据保存到文件中,然后将此文件放入 cwebp 参数中,我认为这不是“正确”的方法。 所以我的问题是如何将二进制 .jpg 或 .png 数据编码为 .webp 数据?我不需要调整大小或其他图像操作之类的东西。 对我来说理想的是:

const std::string& data = GetImgData();
const std::string& webp = ImgToWebp(data.c_str(), data.size());
c++ image webp
1个回答
1
投票

“要在 C++ 中将图像编码为 WebP,您可以使用 libwebp 库。它提供了将图像转换为 WebP 格式所需的功能。首先,确保您已安装 libwebp 并正确链接到您的项目。这是一个简单的示例,说明如何将图像转换为 WebP 格式。可能会用它:

c++
#include <webp/encode.h>
#include <vector>
#include <fstream>

std::vector<uint8_t> ReadImage(const std::string& filepath) {
    // Open file in binary mode and read contents into a vector
    std::ifstream file(filepath, std::ios::binary);
    return std::vector<uint8_t>(std::istreambuf_iterator<char>(file), {});
}

bool WriteImage(const std::string& filepath, const uint8_t* data, size_t size) {
    // Open file in binary mode and write data
    std::ofstream file(filepath, std::ios::binary);
    file.write(reinterpret_cast<const char*>(data), size);
    return file.good();
}

int main() {
    // Example: replace with actual paths and image data
    std::string input_path = "input_image.jpg";
    std::string output_path = "output_image.webp";

    // Read the input image
    std::vector<uint8_t> image_data = ReadImage(input_path);

    // Encode to WebP
    uint8_t* output_data;
    size_t output_size = WebPEncodeRGB(image_data.data(), width, height, stride, quality_factor, &output_data);
    if (output_size == 0) {
        // Handle error
        return -1;
    }

    // Write the WebP image data to a file
    bool success = WriteImage(output_path, output_data, output_size);
    WebPFree(output_data); // Free the WebP image data

    return success ? 0 : -1;
}

在此代码中,您需要将 input_path、width、height、stride 和quality_factor 替换为您的实际图像数据和所需的 WebP 输出设置。函数WebPEncodeRGB用于RGB图像;如果您有不同的格式(例如 RGBA),则需要使用适当的 libwebp 函数。确保您通过使用 WebPFree 释放内存来正确处理由 WebPEncodeRGB 分配的内存。

请调整此示例以适应您的图像数据和文件处理需求的具体情况。”

© www.soinside.com 2019 - 2024. All rights reserved.