Safe, idiomatic Rust bindings to SANE
(Scanner Access Now Easy), the scanner API of Linux, the BSDs and macOS.
Find flatbed scanners, document feeders and multifunction printers, set the
resolution, mode and scan area, and get the page as raw bytes or as an
image ready to save as PNG or JPEG, or to
feed to OCR.
use libsane::{Sane, well_known}; let sane = Sane::init()?; let mut scanner = sane.open("test:0")?; // or a name from sane.devices() scanner.set_value(well_known::MODE, well_known::MODE_COLOR)?; scanner.set_value(well_known::RESOLUTION, 300)?; // dpi scanner.scan()?.to_image()?.save("page.png")?; // `image` feature
Scanned by scan_to_png from SANE's virtual test scanner: no hardware needed to try it.
- Every SANE scanner. USB and network scanners from HP, Canon, Epson,
Brother, Fujitsu, Kodak and many more, through the
backends of sane-backends,
including driverless eSCL/AirScan devices with
sane-airscan. - Safe by construction. The SANE rules are enforced by types: one
initialization per process, devices closed before
sane_exit, buffers sized from the option descriptors.unsafecode lives in a single module of small, documented functions, and the code that decodes SANE's C structures runs under Miri. - Typed options. Bool, int, fixed-point, string and button options with
their constraints (range, word list, string list) and capabilities; the
option list reloads itself when the backend reports
SANE_INFO_RELOAD_OPTIONS. - Every way to read a scan. Chunks through
std::io::Read, a wholeFrameof raw bytes and parameters, or animage::DynamicImage. Gray, RGB, 1/8/16-bit, three-pass scanners and hand scanners with an unknown height are handled, as are document feeders, page after page. - Typed errors. Every
SANE_Statusmaps to anErrorvariant (Jammed,NoDocs,CoverOpen...); no panic crosses the FFI boundary. - Tested without a scanner. The test suite drives SANE's virtual
testbackend in CI, option types, frame formats and error codes included.
| Crate | Description |
|---|---|
libsane |
The safe API: devices, options, scans, frames, images. Start here. |
sane-sys |
Raw FFI to libsane, generated with bindgen and linked through pkg-config. |
-
Install libsane, pkg-config and libclang (for bindgen):
System Command Debian, Ubuntu sudo apt install libsane-dev pkg-config libclang-devFedora sudo dnf install sane-backends-devel pkgconf-pkg-config clang-develArch Linux sudo pacman -S sane pkgconf clangmacOS (Homebrew) brew install sane-backends pkg-config llvmIf libsane is installed somewhere else, point
PKG_CONFIG_PATHto the directory that holdssane-backends.pc. -
Add the crate, with the
imagefeature to get images:cargo add libsane --features image
-
List the scanners and scan a page:
use libsane::Sane; fn main() -> Result<(), Box<dyn std::error::Error>> { let sane = Sane::init()?; let devices = sane.devices(false)?; for device in &devices { println!("{}: {} {} ({})", device.name, device.vendor, device.model, device.kind); } let mut scanner = sane.open_device(devices.first().ok_or("no scanner found")?)?; let frame = scanner.scan()?; println!("{}x{} pixels", frame.width(), frame.height()); frame.to_image()?.save("scan.png")?; Ok(()) }
No scanner at hand? SANE ships a virtual one. Uncomment test in
/etc/sane.d/dll.conf, or point SANE_CONFIG_DIR to a directory whose
dll.conf lists it, like libsane/tests/sane.d, and
open test:0:
SANE_CONFIG_DIR=libsane/tests/sane.d cargo run -p libsane --example scan_to_png --features image -- test:0 scan.png
- Blocking API. SANE calls block, sometimes for seconds (discovery, lamp
warm-up, scanning). From async code, run the session on a blocking thread,
for example with
tokio::task::spawn_blocking. - One session per process.
Sane::initreturnsError::AlreadyInitializedwhile anotherSaneexists; dropping it callssane_exit, after which SANE can be initialized again. - Threads. libsane is not thread-safe: a
Sanecan move to another thread but cannot be shared, and its devices stay on its thread. - Document feeders.
Scan::next_pagescans the next sheet without ending the batch, and returnsfalsewhen the feeder is empty. - Windows. SANE is not available on Windows, which uses WIA and TWAIN instead.
libsaneAPI documentation on docs.rssane-sysAPI documentation on docs.rs- The SANE standard for the meaning of every option and status
Tasks are defined in mise.toml and mirror CI:
mise install # Rust toolchain and tools mise bootstrap packages apply # libsane-dev, pkg-config, libclang (Debian, Ubuntu) mise run check # format, clippy, tests, example mise run miri # unit tests under Miri mise run doc # documentation as docs.rs builds it
Pull request titles follow Conventional Commits and become the changelog; releases are described in RELEASING.md.
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
sane-sys/include/sane/sane.h is an unmodified copy of SANE's public-domain
header, used only to build the documentation on docs.rs.