Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CCITT Group 4 / T.6 "fax machine" compression handling example #211

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ authors = ["The image-rs Developers"]
repository = "https://github.com/image-rs/image-tiff"
categories = ["multimedia::images", "multimedia::encoding"]

exclude = ["tests/images/*", "tests/fuzz_images/*"]
exclude = ["tests/images/*", "tests/fuzz_images/*", "examples/*"]

[dependencies]
weezl = "0.1.0"
Expand Down
10 changes: 10 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Examples

Below are some examples of integrating image-tiff with other libraries for additional functionality.

## CCITT Group 4 / T.6 "fax machine" compression support

[This example](group_4) uses the [fax crate](https://github.com/pdf-rs/fax) to provide CCITT Group 4 / T.6 decompression capabilities to
the image-tiff crate in a simple demo that accepts an arbitrary image file as the sole command line argument, then performs
group 4 decompression on the input file if it is a little endian tiff file and writes it out as a `.png` file. Sample files are included
under the data folder.
2 changes: 2 additions & 0 deletions examples/group_4/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
out.png
12 changes: 12 additions & 0 deletions examples/group_4/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "ccitt-group-4-tiff"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

image = "0.24.7"
fax = "0.2.0"
tiff = "0.9.0"
Binary file added examples/group_4/data/patent-drawing.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/group_4/data/patent-drawing.tif
Binary file not shown.
86 changes: 86 additions & 0 deletions examples/group_4/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use std::{fs, env};
use std::io::{Cursor, BufWriter};
use fax::{decoder, decoder::pels, Color};
use image::{ImageError, DynamicImage, GrayImage};
use image::io::Reader as ImageReader;

fn resize_dyn_img_to_png_bytes(dyn_image: DynamicImage) -> Result<Vec<u8>, ImageError> {
let mut image_data = BufWriter::new(Cursor::new(Vec::new()));
dyn_image.write_to(&mut image_data, image::ImageOutputFormat::Png).unwrap();
return Ok(image_data.get_ref().get_ref().to_owned());
}

fn image_preprocess_fax(bytes:Vec<u8>) -> Result<GrayImage, Box<dyn std::error::Error>> {
use tiff::decoder::Decoder;
use tiff::tags::Tag;
let mut decoder = Decoder::new(Cursor::new(bytes.as_slice())).unwrap();
let width = decoder.get_tag_u32(Tag::ImageWidth).unwrap();
let height = decoder.get_tag_u32(Tag::ImageLength).unwrap();
assert_eq!(decoder.get_tag_u32(Tag::Compression).unwrap(), 4);
assert_eq!(decoder.get_tag_u32(Tag::BitsPerSample).unwrap(), 1);

let strip_offsets = decoder.get_tag_u32_vec(Tag::StripOffsets).unwrap();
let strip_lengths = decoder.get_tag_u32_vec(Tag::StripByteCounts).unwrap();

let mut image = GrayImage::new(width, height);

let mut rows = image.rows_mut();
let mut cols_read = 0;
for (&off, &len) in strip_offsets.iter().zip(strip_lengths.iter()) {
decoder.goto_offset(off).unwrap();
let bytes = std::iter::from_fn(|| decoder.read_byte().ok()).take(len as usize);

decoder::decode_g4(bytes, width as u16, None, |transitions| {
let row = rows.next().unwrap();
for (c, px) in pels(transitions, width as u16).zip(row) {
let byte = match c {
Color::Black => 0,
Color::White => 255
};
px.0[0] = byte;
}

cols_read += 1;
});
}

Ok(image)
}

pub fn read_bytes_to_png_bytes(bytes:Vec<u8>,) -> Result<Vec<u8>, ImageError>{
if bytes.len() > 3 && bytes[0] == 73 && bytes[1] == 73 // little endian, fine for POC
&& bytes[2] == 42{
let image = image_preprocess_fax(bytes).unwrap();
return resize_dyn_img_to_png_bytes(image.into());
}

let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?;

match reader.decode(){
Ok(img) => {
return resize_dyn_img_to_png_bytes(img);
}
Err(e) => {
eprint!("Error decoding image: {}", e);
return Err(e);
}
};
}

pub fn read_image_to_png_bytes(path: &String) -> Result<Vec<u8>, ImageError>{
let bytes = fs::read(path).unwrap();
return read_bytes_to_png_bytes(bytes);
}

fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 1{
let path = &args[1];
let image_bytes = read_image_to_png_bytes(path).unwrap();
std::fs::write("out.png", &image_bytes).unwrap();
println!("Image converted to out.png, {} bytes in final PNG representation", image_bytes.len());
}
else{
println!("Usage - this_executable <path/to/input-image.any>");
}
}