### Install Ratatui Image with Minimal Setup Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/README.md Configure ratatui-image for a minimal setup, enabling only Crossterm and Halfblocks features. ```toml [dependencies] ratatui-image = { version = "11", default-features = false, features = ["image-defaults", "crossterm"] } ``` -------------------------------- ### Example Usage of Image Widget Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Demonstrates creating a pre-sized protocol and rendering it as an Image widget within a Ratatui terminal. Requires image loading and picker setup. ```rust use ratatui::{Terminal, backend::TestBackend, layout::Size, Frame}; use ratatui_image::{Image, picker::Picker, Resize}; // Assuming './assets/image.png' exists and is a valid image file // let mut terminal = Terminal::new(TestBackend::new(80, 30))?; // let picker = Picker::halfblocks(); // let dyn_img = image::ImageReader::open("./assets/image.png")?.decode()?; // let proto = picker.new_protocol(dyn_img, Size::new(20, 10), Resize::Fit(None))?; // // terminal.draw(|f| { // f.render_widget(Image::new(&proto), f.area()); // })?; ``` -------------------------------- ### Install Ratatui Image with Default Features Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/README.md Use this configuration to install ratatui-image with default features, including Crossterm and Chafa support. ```toml [dependencies] ratatui-image = "11" image = "0.25" ratatui = "0.30" ``` -------------------------------- ### Crossterm Backend Configuration Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Configure the ratatui-image dependency to use the crossterm terminal backend. This is the default and most common setup. ```toml # Default (recommended) [dependencies] ratatui-image = "11" ``` ```toml # Termion backend [dependencies] ratatui-image = { version = "11", default-features = false, features = ["image-defaults", "termion"] } ``` ```toml # Minimal setup (no default features) [dependencies] ratatui-image = { version = "11", default-features = false, features = ["image-defaults", "crossterm"] } ``` -------------------------------- ### Offset Image Above Viewport Example Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Shows a simple example of rendering an image that starts above the visible viewport using SignedPosition. ```APIDOC ### Offset Image Above Viewport Render an image starting above the visible area: ```rust use ratatui_image::sliced::SignedPosition; // Render image with 3 lines above the viewport let position = SignedPosition::from((0, -3)); ``` ``` -------------------------------- ### Horizontal and Vertical Panning Example Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Illustrates how to implement a pannable image viewer using SignedPosition for both horizontal and vertical scrolling. ```APIDOC ### Horizontal and Vertical Panning Implement a pannable image viewer: ```rust use ratatui_image::sliced::{SlicedImage, SignedPosition}; struct App { scroll_x: i16, scroll_y: i16, sliced_proto: SlicedProtocol, } fn ui(f: &mut Frame<'_>, app: &App) { let position = SignedPosition::from((-app.scroll_x, -app.scroll_y)); f.render_widget(SlicedImage::new(&app.sliced_proto, position), f.area()); } ``` ``` -------------------------------- ### Basic Ratatui Image Usage Example Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/README.md Demonstrates the basic usage of ratatui-image to load and display an image in a Ratatui terminal. Ensure you have an 'image.png' file in the same directory. ```rust use ratatui::{ Terminal, Frame, backend::CrosstermBackend, }; use ratatui_image::{Image, picker::Picker, Resize}; use ratatui::layout::Size; fn main() -> Result<(), Box> { // Detect terminal and font size let picker = Picker::from_query_stdio()?; // Load image let dyn_img = image::ImageReader::open("./image.png")?.decode()?; // Create protocol (one-time operation) let protocol = picker.new_protocol(dyn_img, Size::new(40, 20), Resize::Fit(None))?; // Render let mut terminal = Terminal::new(CrosstermBackend::new(std::io::stdout()))?; terminal.draw(|f| { f.render_widget(Image::new(&protocol), f.area()); })?; Ok(()) } ``` -------------------------------- ### Example: SignedPosition Tuple Conversion Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Demonstrates the conversion of tuples to `SignedPosition` for various offset scenarios. Use `SignedPosition::from` to create positions relative to the viewport. ```rust use ratatui_image::sliced::SignedPosition; let pos = SignedPosition::from((10, -5)); // 10 right, 5 up let pos = SignedPosition::from((0, 0)); // Top-left corner let pos = SignedPosition::from((-3, 8)); // 3 left, 8 down ``` -------------------------------- ### Background Worker Thread Example Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-thread.md Demonstrates how to set up a background worker thread that receives `ResizeRequest`s, performs the `resize_encode` operation, and sends the `ResizeResponse` back to the UI thread. This pattern is essential for non-blocking image processing. ```rust fn worker(rx: Receiver) { while let Ok(resize_req) = rx.recv() { match resize_req.resize_encode() { Ok(response) => { // Send response back to UI thread let _ = result_tx.send(response); } Err(e) => eprintln!("Encoding error: {}", e), } } } ``` -------------------------------- ### Vertical Scrolling Example Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Demonstrates how to render an image that scrolls vertically within a viewport using SignedPosition. ```APIDOC ### Vertical Scrolling Render an image that scrolls vertically within a viewport: ```rust use ratatui::Frame; use ratatui_image::sliced::{SlicedImage, SlicedProtocol, SignedPosition}; use ratatui_image::picker::Picker; struct App { sliced_proto: SlicedProtocol, scroll_offset: i16, } fn ui(f: &mut Frame<'_>, app: &App) { let position = SignedPosition::from((0, -app.scroll_offset)); f.render_widget(SlicedImage::new(&app.sliced_proto, position), f.area()); } // Handle scroll events fn handle_scroll_up(app: &mut App) { app.scroll_offset = (app.scroll_offset - 1).max(-100); } fn handle_scroll_down(app: &mut App) { app.scroll_offset = (app.scroll_offset + 1).min(100); } ``` ``` -------------------------------- ### Non-Blocking Image Resizing with std::sync::mpsc Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/advanced-patterns.md This snippet demonstrates how to offload image resizing and encoding to a background thread using Rust's standard library `mpsc` channels. It shows the setup for a worker thread and the UI loop logic for handling resize requests and responses without blocking the main UI thread. Ensure `ThreadProtocol` is initialized and used correctly. ```rust use ratatui_image::thread::{ThreadProtocol, ResizeRequest}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::thread; struct App { thread_proto: ThreadProtocol, response_rx: Receiver, } fn spawn_worker(resize_rx: Receiver) -> Sender { let (response_tx, response_rx) = channel(); thread::spawn(move || { while let Ok(resize_req) = resize_rx.recv() { match resize_req.resize_encode() { Ok(response) => { let _ = response_tx.send(response); } Err(e) => eprintln!("Encoding failed: {}", e), } } }); response_tx } fn ui_loop(app: &mut App, frame: &mut Frame) { let resize = Resize::Fit(None); // Non-blocking check if app.thread_proto.needs_resize(&resize, frame.area().into()).is_some() { // Resize queued to background thread, UI doesn't block } // Apply any completed resize responses while let Ok(response) = app.response_rx.try_recv() { app.thread_proto.update_resized_protocol(response); } // Render with current state (fast) let image = StatefulImage::default().resize(resize); frame.render_stateful_widget(image, frame.area(), &mut app.thread_proto); } ``` -------------------------------- ### SlicedImage::new Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Creates a new SlicedImage widget. This widget renders a sliced protocol at a specified signed position, enabling images to extend beyond or start before the viewport. ```APIDOC ## SlicedImage::new ### Description Creates a new sliced image widget that renders a sliced protocol at a signed position, allowing the image to extend beyond the viewport or start before it. ### Method Rust function ### Signature `pub fn new(sliced_protocol: &'a SlicedProtocol, position: SignedPosition) -> SlicedImage<'a>` ### Parameters #### Arguments - **sliced_protocol** (`&'a SlicedProtocol`) - Required - Reference to a sliced protocol. - **position** (`SignedPosition`) - Required - Signed (x, y) position relative to the render area. ### Returns - `SlicedImage<'a>` - A widget. ### Example ```rust use ratatui_image::sliced::{SlicedImage, SlicedProtocol, SignedPosition}; use ratatui_image::picker::Picker; use ratatui::layout::Size; let picker = Picker::halfblocks(); let dyn_img = image::ImageReader::open("./image.png")?.decode()?; let sliced = SlicedProtocol::new(&picker, dyn_img, None)?; let mut position = SignedPosition::from((0, 0)); terminal.draw(|f| { f.render_widget(SlicedImage::new(&sliced, position), f.area()); }); ``` ``` -------------------------------- ### Create a Picker with Auto-Detection Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Instantiate a Picker for automatic protocol and font size detection. This is the recommended approach. ```rust use ratatui_image::picker::Picker; // Auto-detect (recommended) let mut picker = Picker::from_query_stdio()?; ``` -------------------------------- ### ThreadProtocol::background_color Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-thread.md Gets the background color used for padding, if set. ```APIDOC ## ThreadProtocol::background_color ### Description Get the background color for padding. ### Method ```rust pub fn background_color(&self) -> Option> ``` ### Returns - **Option>** — The color, or `None` if transparent. ``` -------------------------------- ### Protocol::size Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Get the size (width and height) of the rendered image in terminal cells. ```APIDOC ## Protocol::size ### Description Get the size (width and height) of the rendered image in terminal cells. ### Returns - `Size` — Terminal cell dimensions `(width, height)`. ### Example ```rust let image_size = protocol.size(); println!("Image is {} cells wide and {} cells tall", image_size.width, image_size.height); ``` ``` -------------------------------- ### StatefulProtocol::new Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Creates a new StatefulProtocol instance. It takes the image, terminal font size, an optional background color for padding, and the desired protocol type. ```APIDOC ## StatefulProtocol::new ### Description Create a new stateful protocol from a dynamic image. ### Parameters #### Path Parameters - **image** (DynamicImage) - Required - Source image - **font_size** (FontSize) - Required - Terminal font size for pixel-to-cell conversion - **background_color** (Option>) - Optional - Background for padding (Defaults to Transparent black) - **protocol_type** (StatefulProtocolType) - Required - Which protocol to use ### Returns - **StatefulProtocol** — A stateful protocol instance. ### Example ```rust use ratatui_image::{protocol::{StatefulProtocol, StatefulProtocolType}, FontSize}; use image::DynamicImage; let image = image::ImageReader::open("./image.png")?.decode()?; let font_size = FontSize::new(10, 20); let proto = StatefulProtocol::new( image, font_size, None, StatefulProtocolType::Kitty(StatefulKitty::new(1, false)), ); ``` ``` -------------------------------- ### Configure Terminal Detection with Longer Timeout Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Example of increasing the timeout for terminal detection, useful for slow or remote terminals. ```rust use std::time::Duration; let options = QueryStdioOptions { timeout: Duration::from_secs(5), // Increase for slow terminals blacklist_protocols: vec![], }; let picker = Picker::from_query_stdio_with_options(options)?; ``` -------------------------------- ### StatefulKitty::new Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Creates a new Kitty protocol instance for stateful resizing. This is useful when the image needs to be dynamically resized or updated. ```APIDOC ## StatefulKitty::new ### Description Create a new Kitty protocol for stateful resizing. ### Signature ```rust pub fn new(id: u32, is_tmux: bool) -> StatefulKitty ``` ### Parameters #### Path Parameters - **id** (u32) - Required - Unique image ID - **is_tmux** (bool) - Required - True if inside tmux ### Returns `StatefulKitty` — A stateful protocol. ### Example ```rust use ratatui_image::protocol::kitty::StatefulKitty; let stateful_kitty = StatefulKitty::new(random(), false); ``` ``` -------------------------------- ### Get Image Size Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Retrieves the dimensions of the rendered image in terminal cells. The `Size` struct contains `width` and `height` fields. ```rust let image_size = protocol.size(); println!("Image is {} cells wide and {} cells tall", image_size.width, image_size.height); ``` -------------------------------- ### Configure StatefulImage Resize Strategy Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Set the resize strategy for the `StatefulImage` widget. Choose between `Fit`, `Crop`, or `Scale` to control how the image is displayed. ```rust use ratatui_image::{StatefulImage, Resize}; let image = StatefulImage::default() .resize(Resize::Fit(Some(FilterType::Lanczos3))); ``` -------------------------------- ### Get Picker Capabilities Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Retrieves a list of detected terminal capabilities. This is useful for determining which image rendering protocols are supported by the current terminal. ```rust let picker = Picker::from_query_stdio()?; for cap in picker.capabilities() { println!("{:?}", cap); } ``` -------------------------------- ### Initialize Picker with stdio query Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Automatically detect terminal graphics capabilities and font size by querying stdin/stdout. This is the primary entry point for most applications. Ensure this is called after entering alternate screen but before reading terminal events, and cache the result for performance. ```rust use ratatui_image::picker::Picker; let mut picker = Picker::from_query_stdio()?; println!("Protocol: {:?}", picker.protocol_type()); println!("Font size: {:?}", picker.font_size()); ``` -------------------------------- ### Get Picker font size Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Retrieve the detected or default font size from the Picker. This is crucial for calculating the appropriate cell size for rendering images. ```rust let picker = Picker::from_query_stdio()?; let font_size = picker.font_size(); let cell_size = Size::new( image.width().div_ceil(font_size.width as u32) as u16, image.height().div_ceil(font_size.height as u32) as u16, ); ``` -------------------------------- ### Configure StatefulImage resize strategy Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Configure the resize strategy for the stateful widget using Resize::Fit, Resize::Crop, or Resize::Scale. This method supports method chaining for further configuration. ```rust use ratatui_image::{StatefulImage, protocol::StatefulProtocol, Resize}; let image = StatefulImage::::new() .resize(Resize::Crop(None)); ``` -------------------------------- ### Load and Render Image in Ratatui Source: https://github.com/ratatui/ratatui-image/blob/master/README.md Demonstrates loading an image using the `image` crate, transforming it for terminal display using `ratatui-image`'s `Picker`, and rendering it within a Ratatui `Terminal`. Ensure you have an image file (e.g., './assets/Ada.png') available. ```rust use ratatui::{backend::TestBackend, layout::Size, Terminal, Frame}; use ratatui_image::{Image, picker::Picker, protocol::Protocol, Resize}; struct App { // We need to hold the image data somewhere. image: Protocol, } fn main() -> Result<(), Box> { let backend = TestBackend::new(80, 30); let mut terminal = Terminal::new(backend)?; // Should use `Picker::from_query_stdio()?` to get the font size and protocol, // but we can't put that here because that would break doctests! let mut picker = Picker::halfblocks(); // Load an image with the image crate. let dyn_img = image::ImageReader::open("./assets/Ada.png")?.decode()?; let font_size = picker.font_size(); let size = Size::new( dyn_img.width().div_ceil(font_size.width as u32) as u16, dyn_img.height().div_ceil(font_size.height as u32) as u16, ); // Create the Protocol once, or in other words, transform the image data to Sixels, Kitty // data, iTerm2 base64 PNG data, or some kind of ASCII-art. let image = picker.new_protocol(dyn_img, size, Resize::Fit(None))?; let mut app = App { image }; // This would be your typical `loop {` in a real app: terminal.draw(|f| { let image = Image::new(&app.image); // Rendering the transformed data is now cheap. f.render_widget(image, f.area()); }); Ok(()) } ``` -------------------------------- ### Create StatefulProtocol Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Instantiate a new StatefulProtocol with an image, font size, optional background color, and protocol type. The font size is crucial for pixel-to-cell conversion. ```rust use ratatui_image::protocol::{StatefulProtocol, StatefulProtocolType}; use image::DynamicImage; let image = image::ImageReader::open("./image.png")?.decode()?; let font_size = FontSize::new(10, 20); let proto = StatefulProtocol::new( image, font_size, None, StatefulProtocolType::Kitty(StatefulKitty::new(1, false)), ); ``` -------------------------------- ### Offset Image Above Viewport Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Renders an image starting above the visible area by using a negative `y` value in `SignedPosition`. This is useful for effects where content appears to enter the viewport from above. ```rust use ratatui_image::sliced::SignedPosition; // Render image with 3 lines above the viewport let position = SignedPosition::from((0, -3)); ``` -------------------------------- ### Get Picker protocol type Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Retrieve the currently detected or manually set protocol type from the Picker. This can be used to conditionally render content based on terminal capabilities. ```rust let picker = Picker::from_query_stdio()?; match picker.protocol_type() { ProtocolType::Kitty => println!("Using Kitty protocol"), ProtocolType::Sixel => println!("Using Sixel protocol"), _ => {} } ``` -------------------------------- ### Typical Threaded Rendering Usage Pattern Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-thread.md Illustrates the complete integration of threaded image resizing into a Ratatui application. It covers setting up the communication channels, spawning the worker thread, and handling resize requests within the main UI loop. Ensure proper error handling and communication channels are established for production use. ```rust use ratatui::Frame; use ratatui_image::{ Resize, StatefulImage, thread::{ThreadProtocol, ResizeRequest}, picker::Picker, }; use std::sync::mpsc; struct App { thread_proto: ThreadProtocol, pending_resize: bool, } fn main() -> Result<(), Box> { let picker = Picker::from_query_stdio()?; let image = image::ImageReader::open("./image.png")?.decode()?; let proto = picker.new_resize_protocol(image); let (tx, rx) = mpsc::channel::(); let mut app = App { thread_proto: ThreadProtocol::new(tx, Some(proto)), pending_resize: false, }; // Spawn background worker thread std::thread::spawn(move || { while let Ok(resize_req) = rx.recv() { match resize_req.resize_encode() { Ok(response) => { // In production, send to a separate channel back to UI println!("Resize completed"); } Err(e) => eprintln!("Encoding failed: {}", e), } } }); // Main UI loop loop { terminal.draw(|f| { let resize = Resize::Fit(None); // Check if resize is needed if let Some(size) = app.thread_proto.needs_resize(&resize, f.area().into()) { // Queue resize to background thread app.pending_resize = true; } // Render with current protocol let image = StatefulImage::default().resize(resize); f.render_stateful_widget( image, f.area(), &mut app.thread_proto, ); })?; } } ``` -------------------------------- ### Handle Sixel Encoding Errors Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/errors.md Example of how to handle `Errors::Sixel` when encoding an image. It prints an error message and falls back to the `Halfblocks` protocol if Sixel encoding fails. ```rust match picker.new_protocol(image, size, Resize::Fit(None)) { Ok(proto) => { /* use proto */ } // Use the successfully created protocol Err(Errors::Sixel(msg)) => { eprintln!("Sixel encoding failed: {}", msg); // Fallback to Halfblocks protocol if Sixel fails let fallback_proto = Halfblocks::new(image, size)?; } Err(e) => return Err(e), // Handle other potential errors } ``` -------------------------------- ### Save and Load App Configuration with Serde Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/advanced-patterns.md Defines a serializable `AppConfig` struct for saving and loading user preferences like preferred protocol, font size, and background color. Requires the 'serde' feature. ```rust #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use ratatui_image::picker::ProtocolType; #[derive(Serialize, Deserialize)] struct AppConfig { preferred_protocol: ProtocolType, font_size_override: Option<(u16, u16)>, background_color: Option<[u8; 3]>, } #[cfg(feature = "serde")] impl AppConfig { fn load_from_file(path: &str) -> Result { let contents = std::fs::read_to_string(path)?; Ok(toml::from_str(&contents)?) } fn save_to_file(&self, path: &str) -> Result<()> { let contents = toml::to_string_pretty(self)?; std::fs::write(path, contents)?; Ok(()) } fn apply_to_picker(&self, picker: &mut Picker) { picker.set_protocol_type(self.preferred_protocol); if let Some((w, h)) = self.font_size_override { // Note: FontSize is not configurable post-creation, // this is mainly for initialization } } } ``` -------------------------------- ### Image::new Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Creates a new stateless Image widget. This widget renders a fixed-size image and requires the protocol to be pre-sized. ```APIDOC ## Image::new ### Description Create a new stateless image widget. ### Method `pub fn new(image: &'a Protocol) -> Self` ### Parameters #### Path Parameters - **image** (`&'a Protocol`) - Required - Reference to a pre-sized protocol instance ### Request Example ```rust use ratatui_image::Image; // Assuming 'proto' is a pre-sized Protocol instance let image_widget = Image::new(&proto); ``` ### Response #### Success Response - **Image<'a>** - A widget ready to render with `f.render_widget()`. ``` -------------------------------- ### Image Decoding Error Handling Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/errors.md Handles errors from the 'image' crate during image decoding. This example demonstrates how to catch and report errors related to image file access and format decoding. ```rust match image::ImageReader::open("./image.png") { Ok(reader) => { match reader.decode() { Ok(dyn_img) => { /* process image */ } Err(format_err) => eprintln!("Image decode failed: {}", format_err), } } Err(io_err) => eprintln!("Image file error: {}", io_err), } ``` -------------------------------- ### I/O Error Handling Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/errors.md Handles standard Rust I/O errors that may occur during terminal communication, file operations, or reading/writing to stdin/stdout. This example shows a fallback mechanism to a non-I/O based picker. ```rust match Picker::from_query_stdio() { Ok(picker) => { /* use picker */ } Err(Errors::Io(io_err)) => { eprintln!("Terminal I/O failed: {}", io_err.kind()); let picker = Picker::halfblocks(); // Fallback, no I/O } Err(e) => return Err(e), } ``` -------------------------------- ### Configure ThreadProtocol with tokio::sync::mpsc Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Set up `ThreadProtocol` using `tokio::sync::mpsc` for asynchronous inter-thread communication. Requires the `tokio` feature to be enabled. ```rust use ratatui_image::thread::{ThreadProtocol, ResizeRequest}; use tokio::sync::mpsc; let (tx, mut rx) = mpsc::unbounded_channel::(); let thread_proto = ThreadProtocol::new(tx, Some(protocol)); ``` -------------------------------- ### Initialize Picker with custom stdio query options Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Query terminal capabilities with custom options, allowing blacklisting of specific protocols or setting custom timeouts. This method is useful for fine-tuning the terminal detection process. ```rust use ratatui_image::picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions}; use std::time::Duration; let options = QueryStdioOptions { timeout: Duration::from_secs(3), blacklist_protocols: vec![ProtocolType::Sixel], }; let picker = Picker::from_query_stdio_with_options(options)?; ``` -------------------------------- ### Display Static Image with Image Widget Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/INDEX.md Use the `Image` widget for static image display. Ensure the protocol is created with the desired image, size, and resize strategy. ```rust let protocol = picker.new_protocol(image, size, Resize::Fit(None))?; terminal.draw(|f| f.render_widget(Image::new(&protocol), f.area()))?; ``` -------------------------------- ### Create a Picker with Fallback Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Instantiate a Picker without performing any queries, falling back to a default configuration. ```rust // Fallback (no queries) let mut picker = Picker::halfblocks(); ``` -------------------------------- ### Create Fixed-Size Protocol Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Creates a fixed-size rendering protocol for an `Image` widget. The image is resized once to fit the specified size using a chosen resize strategy. ```rust use ratatui_image::{picker::Picker, Resize}; use ratatui::layout::Size; let picker = Picker::from_query_stdio()?; let dyn_img = image::ImageReader::open("./image.png")?.decode()?; let proto = picker.new_protocol(dyn_img, Size::new(40, 20), Resize::Fit(None))?; ``` -------------------------------- ### Batch Image Loading and Protocol Creation in Rust Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/advanced-patterns.md Efficiently load and process multiple images from a directory, creating protocols for each. Handles common image formats (png, jpg, jpeg) and includes error handling for file operations and image decoding. Requires a `Picker` struct and associated types like `Size`, `Protocol`, and `Resize`. ```rust use std::path::Path; struct ImageBatch { picker: Picker, images: Vec<(String, Protocol)>, } impl ImageBatch { fn new(picker: Picker) -> Self { Self { picker, images: Vec::new(), } } fn load_directory(&mut self, dir: &Path) -> Result<(), Box> { let size = Resize::natural_size( &image::ImageBuffer::new(100, 100).into(), // Dummy for size calculation self.picker.font_size(), ); for entry in std::fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.extension().and_then(|s| s.to_str()) .map_or(false, |s| ["png", "jpg", "jpeg"].contains(&s)) { match image::ImageReader::open(&path) { Ok(reader) => match reader.decode() { Ok(img) => { match self.picker.new_protocol(img, size, Resize::Fit(None)) { Ok(proto) => { self.images.push(( path.file_name() .and_then(|n| n.to_str()) .unwrap_or("unknown") .to_string(), proto, )); } Err(e) => eprintln!("Failed to create protocol: {}", e), } } Err(e) => eprintln!("Failed to decode {}: {}", path.display(), e), }, Err(e) => eprintln!("Failed to open {}: {}", path.display(), e), } } } Ok(()) } } ``` -------------------------------- ### Create Image Widget Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Creates a new stateless Image widget. Requires a reference to a pre-sized protocol instance. ```rust use ratatui_image::{Image, protocol::Protocol}; // Assuming 'proto' is a pre-sized Protocol instance // let proto: Protocol = ...; // let image_widget = Image::new(&proto); ``` -------------------------------- ### Create a new StatefulImage widget Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Use this to create a new instance of the StatefulImage widget with default resize behavior. It's parameterized over a type implementing ResizeEncodeRender. ```rust use ratatui_image::{StatefulImage, protocol::StatefulProtocol}; ``` ```rust pub const fn new() -> Self ``` ```rust use ratatui::Frame; use ratatui_image::{StatefulImage, protocol::StatefulProtocol, Resize}; struct App { image_state: StatefulProtocol, } fn ui(f: &mut Frame<'_>, app: &mut App) { let image = StatefulImage::::new(); f.render_stateful_widget(image, f.area(), &mut app.image_state); } ``` -------------------------------- ### Chafa Library Configuration Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Configure the chafa library integration for enhanced image rendering. Options include dynamic linking, static linking, or no chafa usage for primitive halfblocks. ```toml # With chafa dynamic linking (default) [dependencies] ratatui-image = "11" ``` ```toml # With chafa static linking [dependencies] ratatui-image = { version = "11", default-features = false, features = ["image-defaults", "crossterm", "chafa-static"] } ``` ```toml # Without chafa (primitive halfblocks only) [dependencies] ratatui-image = { version = "11", default-features = false, features = ["image-defaults", "crossterm"] } ``` -------------------------------- ### Create Stateful Kitty Protocol Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Instantiate a StatefulKitty protocol for dynamic image resizing within the terminal. Requires a unique image ID and a flag for tmux environments. ```rust use ratatui_image::protocol::kitty::StatefulKitty; let stateful_kitty = StatefulKitty::new(random(), false); ``` -------------------------------- ### Responsive UI with ThreadProtocol Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md For a reactive UI, utilize `ThreadProtocol` to queue operations like resizing to a background thread. This prevents the UI from freezing and maintains responsiveness during potentially long-running tasks. ```rust // Queue resize to background thread if thread_proto.needs_resize(&resize, area.into()).is_some() { // UI remains responsive } ``` -------------------------------- ### Create Stateful Protocol for Resizing Images Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Creates a stateful protocol for a `StatefulImage` widget. The image will be resized dynamically at render time to match the available area. ```rust use ratatui_image::picker::Picker; let picker = Picker::from_query_stdio()?; let dyn_img = image::ImageReader::open("./image.png")?.decode()?; let proto = picker.new_resize_protocol(dyn_img); struct App { image_state: StatefulProtocol, } ``` -------------------------------- ### Create SlicedProtocol with Explicit Size and Resize Strategy Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Use this function when you need to specify the exact terminal size and how the image should be resized to fit that size. Supports 'Fit', 'Crop', or 'Scale' resize strategies. ```rust use ratatui_image::sliced::SlicedProtocol; use ratatui_image::{picker::Picker, Resize}; use ratatui::layout::Size; let picker = Picker::halfblocks(); let image = image::ImageReader::open("./image.png")?.decode()?; let sliced = SlicedProtocol::new_with_resize( &picker, image, Size::new(80, 30), Resize::Fit(None), )?; ``` -------------------------------- ### Set Transparent Background (Sixel) Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Configure the Sixel protocol to use a transparent background by passing `None` to `set_background_color`. ```rust picker.set_background_color(None) ``` -------------------------------- ### Create ThreadProtocol with tokio::sync::mpsc Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-thread.md Instantiate a ThreadProtocol using a tokio MPSC unbounded channel sender. The background tokio task receives and processes resize requests asynchronously. ```rust use ratatui_image::thread::ThreadProtocol; use tokio::sync::mpsc; let (tx, mut rx) = mpsc::unbounded_channel(); let thread_proto = ThreadProtocol::new(tx, Some(protocol)); // In a tokio task: while let Some(resize_req) = rx.recv().await { let response = resize_req.resize_encode()?; } ``` -------------------------------- ### Optional Feature Configuration Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Enable optional features for ratatui-image, such as `serde` for serialization/deserialization or `tokio` for asynchronous operations. ```toml # With serde support [dependencies] ratatui-image = { version = "11", features = ["serde"] } ``` ```toml # With tokio support [dependencies] ratatui-image = { version = "11", features = ["tokio"] } ``` ```toml # Full features [dependencies] ratatui-image = { version = "11", features = ["serde", "tokio"] } ``` -------------------------------- ### Picker::from_query_stdio_with_options Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Queries the terminal with custom options, allowing blacklisting of specific protocols or custom timeouts for capability detection. ```APIDOC ## Picker::from_query_stdio_with_options ### Description Query terminal with custom options, allowing blacklisting of specific protocols or custom timeouts. ### Method `pub fn from_query_stdio_with_options(options: QueryStdioOptions) -> Result` ### Parameters #### Request Body - **options** (`QueryStdioOptions`) - Required - Query configuration ### QueryStdioOptions Fields ```rust pub struct QueryStdioOptions { pub timeout: Duration, pub blacklist_protocols: Vec, } ``` ### Returns `Result` — Configured picker or error. ### Throws Same as `from_query_stdio()`. ### Example ```rust use ratatui_image::picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions}; use std::time::Duration; let options = QueryStdioOptions { timeout: Duration::from_secs(3), blacklist_protocols: vec![ProtocolType::Sixel], }; let picker = Picker::from_query_stdio_with_options(options)?; ``` ``` -------------------------------- ### ProtocolType Next Method Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/types.md Cycles through the available ProtocolType variants in the order: Halfblocks -> Sixel -> Kitty -> Iterm2 -> Halfblocks. Useful for sequential selection or cycling through terminal capabilities. ```rust pub fn next(&self) -> ProtocolType { match self { ProtocolType::Halfblocks => ProtocolType::Sixel, ProtocolType::Sixel => ProtocolType::Kitty, ProtocolType::Kitty => ProtocolType::ITerm2, ProtocolType::ITerm2 => ProtocolType::Halfblocks, } } ``` -------------------------------- ### Custom Image Format Support Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Configure specific image format support by disabling default features and enabling only the required formats via the `image` crate. This minimizes dependencies. ```toml # Only PNG support (minimal dependencies) [dependencies] ratatui-image = { version = "11", default-features = false, features = ["crossterm"] } image = { version = "0.25", features = ["png"] } ``` ```toml # PNG and JPEG only [dependencies] image = { version = "0.25", features = ["png", "jpeg"] } ``` -------------------------------- ### Serde Feature Flag Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/README.md Enable the `serde` feature to allow saving `ProtocolType` to configuration files. ```toml # With serde (save ProtocolType to config) [dependencies] ratatui-image = { version = "11", features = ["serde"] } ``` -------------------------------- ### Picker::new_protocol Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-picker.md Creates a fixed-size protocol for the `Image` widget. The image is resized once during creation to fit the specified dimensions. ```APIDOC ## Picker::new_protocol ### Description Create a fixed-size protocol for the `Image` widget. The image is resized once at creation time to fit the given size. ### Method `new_protocol` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (`DynamicImage`) - Required - Source image from the `image` crate. - **size** (`Size`) - Required - Target size in terminal cells. - **resize** (`Resize`) - Required - Resize strategy: `Fit`, `Crop`, or `Scale`. ### Request Example ```rust use ratatui_image::{picker::Picker, Resize}; use ratatui::layout::Size; let picker = Picker::from_query_stdio()?; let dyn_img = image::ImageReader::open("./image.png")?.decode()?; let proto = picker.new_protocol(dyn_img, Size::new(40, 20), Resize::Fit(None))?; ``` ### Response #### Success Response (200) - **Return Value** (`Result`) - A ready-to-render protocol. #### Response Example None ### Throws - Protocol-specific errors (e.g., `Errors::Sixel()`) - `Errors::Image()` for image format errors ``` -------------------------------- ### Load Image Asynchronously with Tokio Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/advanced-patterns.md Employ this for non-blocking image loading to maintain UI responsiveness. Requires `tokio` for async operations and `ratatui-image` for image processing. The `ThreadProtocol` is used to manage image data across threads. ```rust use tokio::fs; struct App { thread_proto: ThreadProtocol, // ... other fields } impl App { async fn load_image_async(&mut self, path: String, picker: Picker) { // Spawn async task tokio::spawn({ let tx = self.tx.clone(); async move { match load_and_encode(&path, &picker).await { Ok(proto) => { let _ = tx.send(AppMessage::ImageLoaded(proto)); } Err(e) => { let _ = tx.send(AppMessage::ImageError(e.to_string())); } } } }); } } async fn load_and_encode(path: &str, picker: &Picker) -> Result { let bytes = fs::read(path).await?; let img = image::load_from_memory(&bytes)?; Ok(picker.new_resize_protocol(img)) } ``` -------------------------------- ### Adaptive Image Sizing with StatefulImage Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/INDEX.md Employ `StatefulImage` for adaptive sizing, allowing the image to fit its container. This widget requires a state object for rendering. ```rust let image = StatefulImage::default().resize(Resize::Fit(None)); f.render_stateful_widget(image, f.area(), &mut state); ``` -------------------------------- ### Minimal Ratatui Image Dependency Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/README.md Configure minimal dependencies by disabling default features and explicitly enabling `crossterm` and `image-defaults`. ```toml # Minimal (no Chafa) [dependencies] ratatui-image = { version = "11", default-features = false, features = ["crossterm", "image-defaults"] } ``` -------------------------------- ### Create CropOptions for Image Resizing Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Use `CropOptions` to specify which sides to clip when resizing an image using `Resize::Crop`. Set `clip_top` and `clip_left` to `true` to crop from those respective sides. ```rust use ratatui_image::{Resize, CropOptions}; let crop_options = CropOptions { clip_top: true, clip_left: false, }; let resize = Resize::Crop(Some(crop_options)); ``` -------------------------------- ### SlicedProtocol::new_with_resize Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-sliced.md Creates a sliced protocol with an explicitly defined size and resize strategy. This allows for precise control over the image dimensions and how it's scaled or fitted. ```APIDOC ## SlicedProtocol::new_with_resize ### Description Create a sliced protocol with explicit size and resize strategy. ### Method ```rust pub fn new_with_resize( picker: &Picker, dyn_img: DynamicImage, size: Size, resize: Resize, ) -> Result ``` ### Parameters #### Path Parameters - **picker** (`&Picker`) - Required - Configured picker - **dyn_img** (`DynamicImage`) - Required - Source image - **size** (`Size`) - Required - Size in terminal cells - **resize** (`Resize`) - Required - Resize strategy: `Fit`, `Crop`, or `Scale` ### Response #### Success Response - **SlicedProtocol** (`Result`) - The sliced protocol, or error. ### Request Example ```rust use ratatui_image::sliced::SlicedProtocol; use ratatui_image::{picker::Picker, Resize}; use ratatui::layout::Size; let picker = Picker::halfblocks(); let image = image::ImageReader::open("./image.png")?.decode()?; let sliced = SlicedProtocol::new_with_resize( &picker, image, Size::new(80, 30), Resize::Fit(None), )?; ``` ``` -------------------------------- ### Create ThreadProtocol with std::sync::mpsc Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-thread.md Instantiate a ThreadProtocol using a standard MPSC channel sender. The background thread continuously receives resize requests and processes them. ```rust use ratatui_image::thread::ThreadProtocol; use std::sync::mpsc; let (tx, rx) = mpsc::channel(); let thread_proto = ThreadProtocol::new(tx, Some(protocol)); // In a background thread: while let Ok(resize_req) = rx.recv() { let response = resize_req.resize_encode()?; // Send response back to UI thread } ``` -------------------------------- ### StatefulImage::new Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-core.md Creates a new StatefulImage widget with default resize behavior. This widget is designed to handle image resizing and encoding during the rendering process. ```APIDOC ## StatefulImage::new ### Description Create a new stateful image widget with default resize behavior (`Resize::Fit(None)`). ### Returns `StatefulImage` — A widget parameterized over a type implementing `ResizeEncodeRender`. ### Throws No errors. ### Example ```rust use ratatui.Frame; use ratatui_image::{StatefulImage, protocol::StatefulProtocol, Resize}; struct App { image_state: StatefulProtocol, } fn ui(f: &mut Frame<'_>, app: &mut App) { let image = StatefulImage::::new(); f.render_stateful_widget(image, f.area(), &mut app.image_state); } ``` ``` -------------------------------- ### Create a Picker with Manual Font Size (Deprecated) Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Instantiate a Picker by manually specifying the font size. This method is deprecated. ```rust // Manual font size (deprecated) let mut picker = Picker::from_fontsize(FontSize::new(10, 20)); ``` -------------------------------- ### CropOptions for Image Resizing Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/types.md Use `CropOptions` to configure how an image is cropped during resizing. Set `clip_top` and `clip_left` to `true` to crop from the top and left respectively, or `false` to crop from the bottom and right. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CropOptions { pub clip_top: bool, pub clip_left: bool, } ``` ```rust let options = CropOptions { clip_top: true, clip_left: false, }; let resize = Resize::Crop(Some(options)); ``` -------------------------------- ### Configure ThreadProtocol with std::sync::mpsc Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Set up `ThreadProtocol` using `std::sync::mpsc` for inter-thread communication. This is the default channel implementation. ```rust use ratatui_image::thread::{ThreadProtocol, ResizeRequest}; use std::sync::mpsc; let (tx, rx) = mpsc::channel::(); let thread_proto = ThreadProtocol::new(tx, Some(protocol)); ``` -------------------------------- ### Configure Resize to Crop from Top-Left Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Configure the `Resize` enum to use the `Crop` option, specifying `CropOptions` to clip from the top-left corner. ```rust use ratatui_image::{Resize, CropOptions, FilterType}; // Crop from top-left let crop_opts = CropOptions { clip_top: true, clip_left: true, }; let resize = Resize::Crop(Some(crop_opts)); ``` -------------------------------- ### Configure Terminal Detection Options Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/configuration.md Customize terminal detection behavior using `QueryStdioOptions`. Adjust the timeout or blacklist specific protocols. ```rust use ratatui_image::picker::Picker; use ratatui_image::picker::cap_parser::QueryStdioOptions; use std::time::Duration; let options = QueryStdioOptions { timeout: Duration::from_secs(3), // Default: 2 seconds blacklist_protocols: vec![ProtocolType::Sixel, ProtocolType::Iterm2], }; let picker = Picker::from_query_stdio_with_options(options)?; ``` -------------------------------- ### Image Resize Strategy - Resize Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/types.md Defines how an image should be resized within a terminal, considering font cell dimensions. Supports fitting, cropping, and scaling. ```rust pub enum Resize { Fit(Option), Crop(Option), Scale(Option), } ``` -------------------------------- ### Create Halfblocks Protocol Image Source: https://github.com/ratatui/ratatui-image/blob/master/_autodocs/api-reference-protocol.md Use this to create a Halfblocks-rendered image. Provide the pre-resized image and the terminal cell size. ```rust use ratatui_image::protocol::halfblocks::Halfblocks; let halfblocks = Halfblocks::new(resized_image, Size::new(40, 20))?; ```