aboutsummaryrefslogtreecommitdiff
path: root/vendor/exr/examples/7_crop_alpha_any_image.rs
blob: 726beda6f496665b3d1aff92d7a1c933c6eb4b7b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
extern crate image as png;

extern crate exr;

/// Read an arbitrary image, crop away transparent pixels,
/// then write the cropped result to another file.
pub fn main() {
    use exr::prelude::*;

    let path = "tests/images/valid/custom/oh crop.exr";

    // loads any image (excluding deep data)
    let image: FlatImage = read_all_flat_layers_from_file(path)
        .expect("this file exists in the exrs repository. download that?");

    // construct a cropped image
    let image = Image {
        attributes: image.attributes,

        // crop each layer
        layer_data: image.layer_data.into_iter().map(|layer|{
            println!("cropping layer {:#?}", layer);

            // find the alpha channel of the layer
            let alpha_channel_index = layer.channel_data.list.iter()
                .position(|channel| channel.name.eq_case_insensitive("A"));

            // if has alpha, crop it where alpha is zero
            if let Some(alpha_channel_index) = alpha_channel_index {
                layer.crop_where(|pixel: FlatSamplesPixel| pixel[alpha_channel_index].is_zero())
                    .or_crop_to_1x1_if_empty() // do not remove empty layers from image, because it could result in an image without content
                    .reallocate_cropped() // actually perform the crop operation
            }
            else {
                // return the original layer, as no alpha channel can be used for cropping
                layer
            }

        }).collect::<Layers<_>>(),
    };

    image.write().to_file("cropped.exr").unwrap();
    println!("cropped file to cropped.exr");
}