Debian Codegraph @

.cargo/vendor/exr/examples/1b_convert_exr_to_png.rs

raw
1
2 extern crate image as png;
3
4 // exr imports
5 extern crate exr;
6
7 /// Converts one rgba exr with one layer to one png, or fail.
8 fn main() {
9 use exr::prelude::*;
10 use exr::prelude as exrs;
11
12 // read from the exr file directly into a new `png::RgbaImage` image without intermediate buffers
13 let reader = exrs::read()
14 .no_deep_data()
15 .largest_resolution_level()
16 .rgba_channels(
17 |resolution, _channels: &RgbaChannels| -> png::RgbaImage {
18 png::ImageBuffer::new(
19 resolution.width() as u32,
20 resolution.height() as u32
21 )
22 },
23
24 // set each pixel in the png buffer from the exr file
25 |png_pixels, position, (r,g,b,a): (f32,f32,f32,f32)| { // TODO implicit argument types!
26 png_pixels.put_pixel(
27 position.x() as u32, position.y() as u32,
28 png::Rgba([tone_map(r), tone_map(g), tone_map(b), (a * 255.0) as u8])
29 );
30 }
31 )
32 .first_valid_layer()
33 .all_attributes();
34
35 // an image that contains a single layer containing an png rgba buffer
36 let image: Image<Layer<SpecificChannels<png::RgbaImage, RgbaChannels>>> = reader
37 .from_file("generated_rgba.exr")
38 .expect("run the `1_write_rgba` example to generate the required file");
39
40
41 /// compress any possible f32 into the range of [0,1].
42 /// and then convert it to an unsigned byte.
43 fn tone_map(linear: f32) -> u8 {
44 // TODO does the `image` crate expect gamma corrected data?
45 let clamped = (linear - 0.5).tanh() * 0.5 + 0.5;
46 (clamped * 255.0) as u8
47 }
48
49 // save the png buffer to a png file
50 let png_buffer = &image.layer_data.channel_data.pixels;
51 png_buffer.save("rgb.png").unwrap();
52 println!("created image rgb.png")
53 }