imx - Rust Image Processing Library
A comprehensive Rust library for image processing, manipulation, and visualization.
Features
- 🖼️ Image Processing: Remove letterboxing, handle transparency, process in batch
- 🔄 Format Support: JPEG, PNG, WebP, JXL (JPEG XL)
- 🔢 Numeric Utilities: Safe type conversions for image data
- 📊 XY Plotting: Create image grid plots with labels
- ⚡ High Performance: Async/await support for parallel processing
- 🧰 File Utilities: File type detection, error handling
Installation
Add the following to your Cargo.toml
:
Logging Configuration
This library uses the log
crate for logging and outputs detailed information about processing steps.
Configure a logger (e.g., env_logger
, simplelog
) in your application:
// Example with env_logger
use ;
Core Function Reference
Image Processing Functions
remove_letterbox
Removes black borders (letterboxing) from an image by automatically detecting and cropping them.
async
- Arguments:
path
- Path to the image file - Returns:
Result<()>
indicating success or failure - Behavior: Uses a threshold value of 0 (exact black) for letterbox detection
- Error Cases: Image cannot be opened or saved
- Performance: Processes the entire image; higher resolution images will take longer
remove_letterbox_with_threshold
Similar to remove_letterbox
but allows specifying a threshold value to detect borders.
async
- Arguments:
path
- Path to the image filethreshold
- Threshold value (0-255) for detecting letterbox borders
- Details: Pixels with RGB values below this threshold are considered part of the letterbox
- Use Cases: Useful for images with slightly off-black letterboxing
remove_transparency
Replaces transparent pixels with black, opaque pixels.
async
- Arguments:
path
- Path to the image file - Behavior: Scans the image and replaces any pixel with 0 alpha with black (RGB 0,0,0) and full opacity
- When to Use: Helpful when converting to formats that don't support transparency or when removing transparent regions
get_image_dimensions
Retrieves the width and height of an image.
- Arguments:
path
- Path to the image file - Returns: A tuple of
(width, height)
asu32
values - Error Cases: Image cannot be opened or is corrupt
process_image
Generic function to apply any async image processing operation to a file.
async
- Arguments:
path
- Path to the image file to processprocessor
- Async function that performs the actual image processing
- Features: Handles file existence checks and error propagation
- Advanced Usage: Allows implementing custom image processors
is_image_file
Determines if a file is an image by checking both extension and file contents.
- Arguments:
path
- Path to check - Behavior: Checks for valid image extension, then verifies file contents via magic numbers
- Security: Prevents processing of files with incorrect extensions (security measure)
detect_image_format
Detects image format from file contents using magic numbers.
- Arguments:
buffer
- Byte buffer containing the file header - Returns: The detected format or None if unknown
- Supported Formats: JPEG, PNG, WebP, JXL
- Buffer Size: Requires at least 12 bytes of the file header
Format Conversion Functions
convert_image
Converts an image from one format to another with format-specific options.
async
- Arguments:
input_path
- Path to the input imageoutput_path
- Path where the converted image should be savedoptions
- Optional format-specific conversion options
- Supported Formats: JPEG, PNG, WebP, and others supported by the
image
crate - Quality Control: Options allow setting compression quality, lossless mode
- Directory Creation: Automatically creates destination directory if it doesn't exist
convert_images_batch
Converts multiple images in a batch operation.
async
- Arguments:
input_paths
- List of input image pathsoutput_dir
- Directory where converted images should be savedoutput_format
- Target format for conversionoptions
- Optional format-specific conversion options
- Behavior: Processes each image, maintaining original filenames with new extensions
- Progress Reporting: Logs progress information during batch processing
- Performance: Serial processing - doesn't execute conversions in parallel
detect_format_from_extension
Detects image format from file extension.
- Arguments:
path
- Path to check for format - Returns:
Some(ImageFormat)
if a supported format is detected,None
otherwise - Case Sensitivity: Extension matching is case-insensitive
ImageFormatOptions
Struct for configuring image format conversion options.
- Default Factory Methods:
ImageFormatOptions::default()
- 85% quality, lossy compressionImageFormatOptions::jpeg()
- 85% quality, lossy compressionImageFormatOptions::png()
- 100% quality, lossless compressionImageFormatOptions::webp()
- 85% quality, lossy compression
- Customization Methods:
.with_quality(quality: u8)
- Set specific quality level.with_lossless(lossless: bool)
- Toggle lossless compression.with_option(key: &str, value: &str)
- Add format-specific option
JPEG XL Functions
is_jxl_file
Checks if a file is a JPEG XL image by examining its file extension.
- Arguments:
path
- Path to the file to check - Behavior: Performs a case-insensitive check for the ".jxl" extension
- Limitations: Only checks extension, not file contents
- When to Use: Quick filtering of files by extension
convert_jxl_to_png
Converts a JPEG XL image to PNG format.
async
- Arguments:
input_path
- Path to the input JXL fileoutput_path
- Path where the PNG file should be saved
- Process:
- Reads the JXL file from disk
- Decodes the JXL data using
jxl-oxide
- Converts the pixel data to RGBA format
- Saves the result as a PNG file
- Supported: Both RGB and RGBA JXL images
- Alpha Handling: For RGB images, alpha channel is set to fully opaque
process_jxl_file
Processes a JXL file with an optional custom processor function.
async
- Arguments:
input_path
- Path to the JXL fileprocessor
- Optional function to process the decoded PNG
- Behavior: Converts JXL to temporary PNG file, applies processor, then cleans up
- Advanced Usage: Allows custom transformations of JXL files
- Cleanup: Automatically removes temporary files
Numeric Functions
f32_to_i32
Safely converts an f32 to i32, with proper rounding and range clamping.
- Arguments:
x
- The f32 value to convert - Returns: The converted i32 value, properly rounded and clamped
- Special Cases:
- NaN values are converted to 0
- Values outside i32's range are clamped to
i32::MIN
ori32::MAX
- Values are rounded to the nearest integer using banker's rounding
- Safety Guarantees: No undefined behavior or panics
i32_to_u32
Safely converts an i32 to u32, clamping negative values to 0.
- Arguments:
x
- The i32 value to convert - Returns: The converted u32 value, with negative inputs clamped to 0
- Use Cases: Working with unsigned quantities like array indices or dimensions
u32_to_i32
Safely converts a u32 to i32, clamping values exceeding i32::MAX.
- Arguments:
x
- The u32 value to convert - Returns: The converted i32 value, with large values clamped to i32::MAX
- Safety: Prevents truncation errors and undefined behavior
f32_to_u8
Safely converts an f32 to u8, with proper rounding and range clamping.
- Arguments:
x
- The f32 value to convert - Returns: The converted u8 value, properly rounded and clamped to 0-255
- Use Cases: Converting floating-point color values to byte representation
- Special Cases: NaN becomes 0, values outside range are clamped
i32_to_f32_for_pos
Converts an i32 to f32, optimized for image positioning calculations.
- Arguments:
x
- The i32 value to convert - Returns: The converted f32 value
- Use Cases: Calculating positions in drawing operations
- Precision: Preserves exact integer values within f32's safe integer range
f32_to_u32
Safely converts an f32 to u32, with proper rounding and range clamping.
- Arguments:
x
- The f32 value to convert - Returns: The converted u32 value, properly rounded and clamped
- Safety: Handles NaN, negative values, and overflow cases
XY Plotting Functions
create_plot
Creates an image grid plot with optional row and column labels.
- Arguments:
config
- Configuration for the plot - Returns: Result indicating success or failure
- Features:
- Arranges images in a grid layout
- Adds row and column labels
- Automatically scales images to uniform size
- Handles text rendering with emoji support
- Saves the plot as a PNG image
- Layout: Automatically calculates optimal layout based on image dimensions
PlotConfig
Configuration struct for creating image grid plots.
- Defaults:
top_padding
: 40 pixelsleft_padding
: 40 pixelscolumn_label_alignment
: Centerrow_label_alignment
: Centerdebug_mode
: falsefont_size
: None (use default font size)
- Labels: Support multiline text using '\n' as separator
- Customization: All fields can be configured to customize the plot
LabelAlignment
Enum for specifying label alignment in plots.
- Use Cases: Controls positioning of text labels relative to images
- Default:
Center
alignment for both row and column labels
Layout Engine Functions
Layout
Represents the complete layout of a plot for rendering.
- Components:
- Collection of layout elements (images, labels, padding)
- Total dimensions of the layout
- Methods:
new(width: u32, height: u32)
- Creates a new empty layoutadd_element(element: LayoutElement)
- Adds an element to the layoutrender_debug()
- Renders a debug visualization of the layout
LayoutElement
Represents different types of elements in a layout.
- Types:
Image
- An image to be displayed in the gridRowLabel
- A label for a row of imagesColumnLabel
- A label for a column of imagesPadding
- Empty space in the layout
- Debug Visualization: Each type is color-coded in debug mode
LayoutRect
Represents a rectangular region in the layout.
- Coordinates: (x,y) represent the top-left corner of the rectangle
- Dimensions: Width and height define the size of the rectangle
- Signed Coordinates: Allows for elements partially outside the visible area
Examples
Basic Image Processing
use Path;
use Result;
use ;
async
Image Format Conversion
use ;
use Result;
use ;
use ImageFormat;
async
JXL Processing
use Path;
use Result;
use ;
async
Creating Image Grid Plots
use PathBuf;
use Result;
use ;
Safe Numeric Conversions
use ;
Best Practices
Path Handling
Always use platform-agnostic path handling:
use Path;
// Good
let img_path = new.join;
// Avoid platform-specific separators
// let img_path = "images/photo.jpg"; // Works on Unix but not Windows
Using Async Functions
Ensure your runtime is configured for async functions:
use Runtime;
// Setup a basic tokio runtime
let rt = new.unwrap;
rt.block_on;
Layout Algorithm
The library uses a sophisticated layout algorithm for grid plots:
- Images are arranged in a grid with specified number of rows
- Columns are calculated automatically based on image count and rows
- All images are scaled to maintain uniform size in the grid
- Row labels are placed on the left side, aligned to the row
- Column labels are placed above each column
- Padding is added around all elements for visual spacing
For debugging layouts, set debug_mode: true
in your PlotConfig
to see a color-coded visualization of the calculated layout.