| 1 | |
| 2 | extern crate image as png; |
| 3 | |
| 4 | extern crate exr; |
| 5 | |
| 6 | /// Read an arbitrary image, crop away transparent pixels, |
| 7 | /// then write the cropped result to another file. |
| 8 | pub fn main() { |
| 9 | use exr::prelude::*; |
| 10 | |
| 11 | let path = "tests/images/valid/custom/oh crop.exr"; |
| 12 | |
| 13 | // loads any image (excluding deep data) |
| 14 | let image: FlatImage = read_all_flat_layers_from_file(path) |
| 15 | .expect("this file exists in the exrs repository. download that?"); |
| 16 | |
| 17 | // construct a cropped image |
| 18 | let image = Image { |
| 19 | attributes: image.attributes, |
| 20 | |
| 21 | // crop each layer |
| 22 | layer_data: image.layer_data.into_iter().map(|layer|{ |
| 23 | println!("cropping layer {:#?}", layer); |
| 24 | |
| 25 | // find the alpha channel of the layer |
| 26 | let alpha_channel_index = layer.channel_data.list.iter() |
| 27 | .position(|channel| channel.name.eq_case_insensitive("A")); |
| 28 | |
| 29 | // if has alpha, crop it where alpha is zero |
| 30 | if let Some(alpha_channel_index) = alpha_channel_index { |
| 31 | layer.crop_where(|pixel: FlatSamplesPixel| pixel[alpha_channel_index].is_zero()) |
| 32 | .or_crop_to_1x1_if_empty() // do not remove empty layers from image, because it could result in an image without content |
| 33 | .reallocate_cropped() // actually perform the crop operation |
| 34 | } |
| 35 | else { |
| 36 | // return the original layer, as no alpha channel can be used for cropping |
| 37 | layer |
| 38 | } |
| 39 | |
| 40 | }).collect::<Layers<_>>(), |
| 41 | }; |
| 42 | |
| 43 | image.write().to_file("cropped.exr").unwrap(); |
| 44 | println!("cropped file to cropped.exr"); |
| 45 | } |
| 46 |