简体   繁体   English

如何使用 rust-image 按程序生成图像?

[英]How do I procedurally generate images using rust-image?

I'd like to learn Rust and thought it would be fun to procedurally generate images.我想学习 Rust 并认为程序生成图像会很有趣。 I've no idea where to start though... piston/rust-image ?我不知道从哪里开始……活塞/锈蚀图像 But even with that where should I begin?但即便如此,我应该从哪里开始呢?

The place to begin is the docs and the repository .开始的地方是docsrepository

It's not immediately obvious from the landing page of the documentation, but the core type in image is ImageBuffer .从文档的登录页面ImageBuffer并不是很明显,但是image的核心类型是ImageBuffer

The new function allows one to construct an ImageBuffer representing an image with the given/width, storing pixels of a given type (eg RGB , or that with transparency ). new函数允许构造一个ImageBuffer表示具有给定/宽度的图像,存储给定类型的像素(例如RGB具有透明度的像素)。 One can use methods like pixels_mut , get_pixel_mut and put_pixel (the latter are below pixels_mut in the documentation) to modify the image.可以使用pixels_mutget_pixel_mutput_pixel (后者在文档中的pixels_mut下方)来修改图像。 Eg例如

extern crate image;

use image::{ImageBuffer, Rgb};

const WIDTH: u32 = 10;
const HEIGHT: u32 = 10;

fn main() {
    // a default (black) image containing Rgb values
    let mut image = ImageBuffer::<Rgb<u8>>::new(WIDTH, HEIGHT);

    // set a central pixel to white
    image.get_pixel_mut(5, 5).data = [255, 255, 255];

    // write it out to a file
    image.save("output.png").unwrap();
}

which looks like:看起来像:输出

The repo is particularly useful as a starting point, because it contains examples, in particular, it has an example of programmatically generating an image .该 repo 作为起点特别有用,因为它包含示例,特别是它有一个以编程方式生成图像的示例 When using a new library, I'll open the docs, and, if confused, the repo specifically to look for examples.使用新库时,我将打开文档,如果感到困惑,我将打开 repo 专门查找示例。

As @huon answer is 6 years old, I was getting errors reproducing the result, so I wrote this,由于@huon 回答是 6 岁,我在重现结果时出错,所以我写了这个,

use image::{ImageBuffer, RgbImage};

const WIDTH:u32 = 10;
const HEIGHT:u32 = 10;

fn main() {
    let mut image: RgbImage = ImageBuffer::new(WIDTH, HEIGHT);
    *image.get_pixel_mut(5, 5) = image::Rgb([255,255,255]);
    image.save("output.png").unwrap();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM