有没有一种方法可以使用创建白色图像的图像箱来创建泛型函数?

时间:2020-05-04 18:28:15

标签: image types rust

我正在尝试创建一个泛型函数以在锈中创建白色图像。

到目前为止,我已经尝试过:

use imageproc::drawing::draw_filled_rect_mut;
use image::buffer::ConvertBuffer;
use image::{GenericImage, ImageBuffer, Pixel, RgbaImage, Rgba};
use imageproc::rect::Rect;

pub(crate) fn create_square_image<I, P>(source_img: &I, size: u32) -> ImageBuffer<P, Vec<u8>>
where
    I: GenericImage<Pixel = P>,
    I: ConvertBuffer<ImageBuffer<P, Vec<u8>>>,
    P: Pixel<Subpixel = u8>
{
    let (width, height) = source_img.dimensions();

    let mut block_image = create_white_image(size, size);

    let delta_x = (size - width) / 2;
    let delta_y = (size - height) / 2;

    for y in 0..height {
        let target_y = y + delta_y;
        if target_y >= size {
            continue;
        }
        for x in 0..width {
            let target_x = x + delta_x;
            if target_x >= size {
                continue;
            }
            let pixel = source_img.get_pixel(x, y);
            block_image.put_pixel(x, y, pixel)
        }
    }

    block_image
}

pub(crate) fn create_white_image<P>(width: u32, height: u32) -> ImageBuffer<P, Vec<u8>>
where
    P: Pixel<Subpixel = u8> + 'static,
    RgbaImage: ConvertBuffer<ImageBuffer<P, Vec<u8>>>
{
    let mut image = ImageBuffer::new(width, height);
    draw_filled_rect_mut(&mut image, Rect::at(0, 0).of_size(width, height), Rgba([255, 255, 255, 255]));

    image.convert()
}

在尝试构建时,它给了我这样的错误:

error[E0277]: the trait bound `P: image::color::FromColor<image::color::Rgba<u8>>` is not satisfied
   --> src\util.rs:217:27
    |
217 |     let mut block_image = create_white_image(size, size);
    |                           ^^^^^^^^^^^^^^^^^^ the trait `image::color::FromColor<image::color::Rgba<u8>>` is not implemented for `P`

我想如果我也对FromColor进行类型约束,那会没事的,但是由于某些原因,它没有被板条箱公开。

有什么我想念的吗?

活动工具链:

stable-x86_64-pc-windows-gnu (default)
rustc 1.43.0 (4fb7144ed 2020-04-20)

cargo.toml依赖项:

[dependencies]
image = "0.23.4"
imageproc = "0.20.0"

0 个答案:

没有答案