带有可选 webp 编码功能的 Rust

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

我正在尝试在我的图像处理工具中加入 2022 年 9 月 10 日 添加的 webp 编码器

所以我的 cargo.toml 文件具有附加功能

   image = {version =  "0.24.6", features = ["webp-encoder"]}

并按原样使用它

   let fout = &mut BufWriter::new(File::create(path)?);

    webp::WebPEncoder::new(fout).write_image(buf, width, height, color),

其中 buf 是 image.as_bytes().

它通过以下方式保释:

Err(Unsupported(UnsupportedError { 格式:Exact(WebP),种类: 颜色(L8) }))

任何人都使用这个新的编码器。

image rust webp
1个回答
1
投票

根据文档

WebPEncoder
仅支持
ColorType::Rgb8
ColorType::Rgba8
的编码:

格式 编码
WebP Rgb8, Rgba8

所以你需要使用其中之一而不是

ColorType::L8
。 当然,如果您的图像不在
Rgb8
/
Rgba8
中,您必须先转换它,据我所知,您必须经过
DynamicImage
:

use std::io::BufWriter;

use image::{codecs::webp, ColorType, DynamicImage, EncodableLayout, ImageEncoder};

fn main() {
    // should work with any image type really, not just `GrayImage`.
    let gray_image = image::GrayImage::new(10, 20);
    let rgb_image = DynamicImage::from(gray_image).into_rgb8();
    let buf = rgb_image.as_bytes();
    let f_out = &mut BufWriter::new(Vec::new());
    webp::WebPEncoder::new(f_out)
        .write_image(buf, 10, 20, ColorType::Rgb8)
        .unwrap();
}
© www.soinside.com 2019 - 2024. All rights reserved.