| 1 |
/// Tests "editing"/re-encoding of an image: |
| 2 |
/// decoding, editing, re-encoding |
| 3 |
use std::fs::File; |
| 4 |
use std::io::{BufReader, BufWriter}; |
| 5 |
use std::path::Path; |
| 6 |
|
| 7 |
use png::DecodingError::LimitsExceeded; |
| 8 |
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>; |
| 9 |
|
| 10 |
fn main() -> BoxResult<()> { |
| 11 |
// # Decode |
| 12 |
// Read test image from pngsuite |
| 13 |
let path_in = Path::new(r"./tests/pngsuite/basi0g01.png"); |
| 14 |
// The decoder is a build for reader and can be used to set various decoding options |
| 15 |
// via `Transformations`. The default output transformation is `Transformations::IDENTITY`. |
| 16 |
let decoder = png::Decoder::new(BufReader::new(File::open(path_in)?)); |
| 17 |
let mut reader = decoder.read_info()?; |
| 18 |
// Allocate the output buffer. |
| 19 |
let png_info = reader.info(); |
| 20 |
let mut buf = vec![0; reader.output_buffer_size().ok_or(LimitsExceeded)?]; |
| 21 |
println!("{png_info:?}"); |
| 22 |
|
| 23 |
// # Encode |
| 24 |
let path_out = Path::new(r"./target/test_modified.png"); |
| 25 |
let file = File::create(path_out)?; |
| 26 |
let ref mut w = BufWriter::new(file); |
| 27 |
|
| 28 |
// Get defaults for interlaced parameter. |
| 29 |
let mut info_out = png_info.clone(); |
| 30 |
let info_default = png::Info::default(); |
| 31 |
|
| 32 |
// Edit previous info |
| 33 |
info_out.interlaced = info_default.interlaced; |
| 34 |
let mut encoder = png::Encoder::with_info(w, info_out)?; |
| 35 |
encoder.set_depth(png_info.bit_depth); |
| 36 |
|
| 37 |
// Edit some attribute |
| 38 |
encoder.add_text_chunk( |
| 39 |
"Testing tEXt".to_string(), |
| 40 |
"This is a tEXt chunk that will appear before the IDAT chunks.".to_string(), |
| 41 |
)?; |
| 42 |
|
| 43 |
// Save picture with changed info |
| 44 |
let mut writer = encoder.write_header()?; |
| 45 |
let mut counter = 0u8; |
| 46 |
while let Ok(info) = reader.next_frame(&mut buf) { |
| 47 |
let bytes = &buf[..info.buffer_size()]; |
| 48 |
writer.write_image_data(&bytes)?; |
| 49 |
counter += 1; |
| 50 |
println!("Written frame: {}", counter); |
| 51 |
} |
| 52 |
Ok(()) |
| 53 |
} |