How do I encode a Rust Piston image and get the result in memory?

给你一囗甜甜゛ 提交于 2019-11-29 15:38:01
fn getImage() -> image::DynamicImage 

You have a DynamicImage.

image only seems to provide a method to write to a filename

I assume you mean DynamicImage::save.

The method immediately before save is write_to:

pub fn write_to<W: Write, F: Into<ImageOutputFormat>>(
    &self, 
    w: &mut W, 
    format: F
) -> ImageResult<()>

This accepts any generic writer:

let mut buf = Vec::new();

get_image()
    .write_to(&mut buf, image::ImageOutputFormat::PNG)
    .expect("Unable to write");

There's no need for a Cursor.


How do I encode a Piston GenericImage to a format like PNG?

I have no idea the best way to do this. I'd probably copy the generic image into a DynamicImage and then follow the above instructions.

I've adapted OP's code based on the image crate docs. It looks possible to make the original code to work. There is no need for Cursor but one needs to create a "by reference" adaptor for the instance of Write implemented by Vec.

// This code have not been tested or even compiled
let v = {
    let generated = get_image();
    let mut encoded_image = Vec::new();
    let (width, height) = generated.dimensions();
    {
        image::png::PNGEncoder::new(encoded_image.by_ref())
            .encode(
                generated.raw_pixels(), 
                width, 
                height,
                generated.color()
            ).expected("error encoding pixels as PNG");
    }
    encoded_image
};

Here is the code I actually used in my project. I get a reference to the raw pixels passed in as an &[u8] slice. Each pixel represents an 8 bit grayscale value. Here is a function that encodes the pixels into an in memory PNG image.

pub fn create_png(pixels: &[u8], dimensions: (usize, usize)) -> Result<Vec<u8>> {
    let mut png_buffer = Vec::new();
    PNGEncoder::new(png_buffer.by_ref())
        .encode(
            pixels,
            dimensions.0 as u32,
            dimensions.1 as u32,
            ColorType::Gray(8),
        ).expect("error encoding pixels as PNG");

    Ok(png_buffer)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!