| 1 |
// For reading and opening files |
| 2 |
use png::text_metadata::{ITXtChunk, ZTXtChunk}; |
| 3 |
use std::env; |
| 4 |
use std::fs::File; |
| 5 |
use std::io::BufWriter; |
| 6 |
|
| 7 |
fn main() { |
| 8 |
let path = env::args() |
| 9 |
.nth(1) |
| 10 |
.expect("Expected a filename to output to."); |
| 11 |
let file = File::create(path).unwrap(); |
| 12 |
let w = &mut BufWriter::new(file); |
| 13 |
|
| 14 |
let mut encoder = png::Encoder::new(w, 2, 1); // Width is 2 pixels and height is 1. |
| 15 |
encoder.set_color(png::ColorType::Rgba); |
| 16 |
encoder.set_depth(png::BitDepth::Eight); |
| 17 |
// Adding text chunks to the header |
| 18 |
encoder |
| 19 |
.add_text_chunk( |
| 20 |
"Testing tEXt".to_string(), |
| 21 |
"This is a tEXt chunk that will appear before the IDAT chunks.".to_string(), |
| 22 |
) |
| 23 |
.unwrap(); |
| 24 |
encoder |
| 25 |
.add_ztxt_chunk( |
| 26 |
"Testing zTXt".to_string(), |
| 27 |
"This is a zTXt chunk that is compressed in the png file.".to_string(), |
| 28 |
) |
| 29 |
.unwrap(); |
| 30 |
encoder |
| 31 |
.add_itxt_chunk( |
| 32 |
"Testing iTXt".to_string(), |
| 33 |
"iTXt chunks support all of UTF8. Example: हिंदी.".to_string(), |
| 34 |
) |
| 35 |
.unwrap(); |
| 36 |
|
| 37 |
let mut writer = encoder.write_header().unwrap(); |
| 38 |
|
| 39 |
let data = [255, 0, 0, 255, 0, 0, 0, 255]; // An array containing a RGBA sequence. First pixel is red and second pixel is black. |
| 40 |
writer.write_image_data(&data).unwrap(); // Save |
| 41 |
|
| 42 |
// We can add a tEXt/zTXt/iTXt at any point before the encoder is dropped from scope. These chunks will be at the end of the png file. |
| 43 |
let tail_ztxt_chunk = ZTXtChunk::new( |
| 44 |
"Comment".to_string(), |
| 45 |
"A zTXt chunk after the image data.".to_string(), |
| 46 |
); |
| 47 |
writer.write_text_chunk(&tail_ztxt_chunk).unwrap(); |
| 48 |
|
| 49 |
// The fields of the text chunk are public, so they can be mutated before being written to the file. |
| 50 |
let mut tail_itxt_chunk = ITXtChunk::new("Author".to_string(), "सायंतन खान".to_string()); |
| 51 |
tail_itxt_chunk.compressed = true; |
| 52 |
tail_itxt_chunk.language_tag = "hi".to_string(); |
| 53 |
tail_itxt_chunk.translated_keyword = "लेखक".to_string(); |
| 54 |
writer.write_text_chunk(&tail_itxt_chunk).unwrap(); |
| 55 |
} |