Skip to main content

image_to_ofd/
image_to_ofd.rs

1//! Example: Convert an image (JPEG/PNG/BMP/TIFF) to an OFD document.
2//!
3//! Usage: cargo run --example image_to_ofd <input_image> [output.ofd]
4
5use ofd_rs::{ImageSource, OfdWriter};
6use std::path::Path;
7
8fn main() {
9    let args: Vec<String> = std::env::args().collect();
10    if args.len() < 2 {
11        eprintln!("Usage: {} <input_image> [output.ofd]", args[0]);
12        std::process::exit(1);
13    }
14
15    let input_path = &args[1];
16    let output_path = if args.len() > 2 {
17        args[2].clone()
18    } else {
19        let stem = Path::new(input_path)
20            .file_stem()
21            .and_then(|s| s.to_str())
22            .unwrap_or("output");
23        let parent = Path::new(input_path)
24            .parent()
25            .unwrap_or(Path::new("."));
26        parent.join(format!("{}.ofd", stem)).to_string_lossy().into_owned()
27    };
28
29    let image_bytes = std::fs::read(input_path).expect("failed to read input file");
30
31    // Auto-detect format + dimensions, use ofdrw default ratio (5 px/mm ≈ 127 DPI)
32    let source = ImageSource::auto_detect_default(image_bytes)
33        .expect("unsupported image format or cannot read dimensions");
34
35    println!(
36        "Image: {}x{} mm (page size)",
37        format!("{:.1}", source.page_size.width_mm),
38        format!("{:.1}", source.page_size.height_mm),
39    );
40
41    let ofd_bytes = OfdWriter::from_images(vec![source])
42        .build()
43        .expect("failed to build OFD");
44
45    std::fs::write(&output_path, &ofd_bytes).expect("failed to write OFD file");
46    println!("Created: {} ({} bytes)", output_path, ofd_bytes.len());
47}