如何编码Rust Piston图像并将结果存储在内存中? [英] How do I encode a Rust Piston image and get the result in memory?

查看:149
本文介绍了如何编码Rust Piston图像并将结果存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用活塞image来生成图像.

I am using the Piston image package to generate images.

fn get_image() -> image::DynamicImage {
    image::DynamicImage::ImageRgba8(image::ImageBuffer::new(512, 512))
}

我有一个 hyper Web服务器,我想从中为其提供动态生成的服务图片.

I have a hyper web server, from which I would like to serve dynamically-generated images.

基于对

Based on the answer to How to create an in-memory object that can be used as a Reader or Writer in Rust?, I thought I might be able to use a Cursor<Vec<u8>> as the destination. However, image only seems to provide a method to write to a filename, not a Writer like my cursor.

在仔细阅读了image的文档之后,我希望可以使用某种方法来使用

After looking through image's documentation, I hoped there might be some way to use the image::png::PNGEncoder struct directly. It provides a public method encode(self, data: &[u8], width: u32, height: u32, color: ColorType) -> Result<()>. However, I wasn't sure what the data argument is supposed to be, and I couldn't find any public declarations of the ColorTypes used by ImageBuffer.

(&Get, "/image.png") => {
    let v = {
        let generated = get_image();
        let mut encoded_image = Cursor::new(Vec::new());
        let (width, heigth) = generated.dimensions();
        {
            let encoder = image::png::PNGEncoder::new(&encoded_image);
            encoder.encode(unimplemented!("what goes here?"));
        }
        encoded_image.get_mut()
    };

    Box::new(futures::future::ok(
        Response::new()
            .with_header(ContentLength(v.len() as u64))
            .with_body(v.clone()),
    ))
}

如何编码活塞GenericImage 转换为PNG等格式并将结果存储在内存中?

How do I encode a Piston GenericImage to a format like PNG and get the result in memory?

推荐答案

fn getImage() -> image::DynamicImage 

您有一个DynamicImage.

图像似乎仅提供一种写入文件名的方法

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

我假设您的意思是 DynamicImage::save .

I assume you mean DynamicImage::save.

save之前的方法是 write_to :

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");

不需要Cursor.

如何将活塞GenericImage编码为PNG等格式?

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

我不知道这样做的最佳方法.我可能会将普通图像复制到DynamicImage中,然后按照上述说明进行操作.

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.

这篇关于如何编码Rust Piston图像并将结果存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆