Skip to main content

write_jpeg

Function write_jpeg 

Source
pub fn write_jpeg(
    path: impl AsRef<Path>,
    width: u32,
    height: u32,
    pixels: &[u8],
    quality: u8,
    background: Color,
) -> Result<()>
Available on crate feature jpeg only.
Expand description

Write pixels (RGBA8 with straight alpha, length width * height * 4) to path as a JPEG.

See write_jpeg_to for how quality and background are treated.

Examples found in repository?
examples/image_formats.rs (line 85)
35fn main() {
36    let (w, h) = (900u32, 500u32);
37    let dpi = 96.0;
38
39    let comp = || Composition::empty(1, 1).place(1, 1, Span::cell(), Patch::new("panel"));
40
41    let xs: Vec<f64> = (0..60).map(|i| i as f64 * 1.7).collect();
42    let ys: Vec<f64> = xs
43        .iter()
44        .map(|x| 50.0 + 25.0 * (x * 0.07).sin() - 0.15 * x)
45        .collect();
46
47    let mut plot = Plot::new(&comp(), "panel").bind("x", "x").bind("y", "y");
48    plot.add_geom(
49        PointGeom::builder()
50            .set("x", xs)
51            .set("y", ys)
52            .set("fill", rgb8(70, 120, 220))
53            .set("size", 6.0_f64)
54            .build(),
55    );
56    plot.set_title("One render, four formats");
57    plot.add_axis(Axis::rail("x", AxisPlacement::Cartesian(AxisSide::Bottom)));
58    plot.add_axis(Axis::rail("y", AxisPlacement::Cartesian(AxisSide::Left)));
59
60    let mut view = PlotComposition::new(&comp())
61        .add_scale("x", scale::continuous(0.0..=100.0))
62        .add_scale("y", scale::continuous(20.0..=80.0))
63        .with_plot(plot);
64
65    let mut renderer = VelloRenderer::new().expect("vello renderer init");
66    {
67        let scene = renderer.scene();
68        scene.clear();
69        view.render(scene, Size::new(w as f64, h as f64), dpi);
70    }
71
72    let mut pixels = vec![0u8; (w * h * 4) as usize];
73    renderer
74        .render_to_buffer(w, h, TRANSPARENT, &mut pixels)
75        .expect("render");
76
77    let dir = std::env::current_dir().unwrap().join("examples");
78    let png = dir.join("image_formats.png");
79    let jpg = dir.join("image_formats.jpg");
80    let tif = dir.join("image_formats.tiff");
81    let webp = dir.join("image_formats.webp");
82
83    write_png(&png, w, h, &pixels).expect("write png");
84    // Quality 90, composited onto the light background the plot theme assumes.
85    write_jpeg(&jpg, w, h, &pixels, 90, rgb8(248, 248, 252)).expect("write jpeg");
86    write_tiff(&tif, w, h, &pixels, TiffCompression::Deflate).expect("write tiff");
87    write_webp(&webp, w, h, &pixels).expect("write webp");
88
89    for path in [&png, &jpg, &tif, &webp] {
90        let bytes = std::fs::metadata(path).expect("stat").len();
91        println!(
92            "wrote {} ({:.1} KiB)",
93            path.display(),
94            bytes as f64 / 1024.0
95        );
96    }
97}