Rust plotters crate的例子似乎只展示了如何将图像直接保存到文件中,如何将生成的图像保存为变量中的字节?
kmbjn2e31#
一个基于default plotters的例子。
use plotters::prelude::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut buffer_ = vec![0; 640 * 480 * 3]; { let root = BitMapBackend::with_buffer(&mut buffer_, (640, 480)).into_drawing_area(); root.fill(&WHITE)?; let mut chart = ChartBuilder::on(&root) .caption("y=x^2", ("sans-serif", 50).into_font()) .margin(5) .x_label_area_size(30) .y_label_area_size(30) .build_cartesian_2d(-1f32..1f32, -0.1f32..1f32)?; chart.configure_mesh().draw()?; chart .draw_series(LineSeries::new( (-50..=50).map(|x| x as f32 / 50.0).map(|x| (x, x * x)), &RED, ))? .label("y = x^2") .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED)); chart .configure_series_labels() .background_style(WHITE.mix(0.8)) .border_style(BLACK) .draw()?; root.present()?; } let image = image::RgbImage::from_raw(640, 480, buffer_).unwrap(); let mut bytes: Vec<u8> = Vec::new(); image.write_to( &mut std::io::Cursor::new(&mut bytes), image::ImageOutputFormat::Png, )?; // and save to a file: // use std::io::Write; // let mut x = std::fs::File::create("teste.png").unwrap(); // x.write_all(&bytes).unwrap(); Ok(()) }
字符串Cargo.toml
[package] name = "some-crate" version = "0.1.0" edition = "2021" [dependencies] plotters = "0.3" image = { version = "0.24", features = ["png"] }
型
1条答案
按热度按时间kmbjn2e31#
一个基于default plotters的例子。
字符串
Cargo.toml
型