### Install rich-pixels Source: https://github.com/darrenburns/rich-pixels/blob/master/README.md Install the rich-pixels library using pip. ```bash pip install rich-pixels ``` -------------------------------- ### Import Examples Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Demonstrates how to import classes from the rich-pixels package, recommending the top-level import. ```python # Import from top-level package from rich_pixels import Pixels, HalfcellRenderer, FullcellRenderer # Import specific module (not recommended) from rich_pixels._pixel import Pixels from rich_pixels._renderer import Renderer ``` -------------------------------- ### Print Pixels using Rich Console Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Example of initializing a Rich Console and printing a Pixels object to it. This requires importing Console and Pixels. ```python from rich.console import Console from rich_pixels import Pixels console = Console() pixels = Pixels.from_image_path("image.png") console.print(pixels) ``` -------------------------------- ### Minimal Image Display Example Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Load an image from a file path and display it in the console using the Pixels class. This requires the rich and pillow libraries. ```python from rich_pixels import Pixels from rich.console import Console console = Console() pixels = Pixels.from_image_path("image.png") console.print(pixels) ``` -------------------------------- ### Example GetPixel Implementation with PIL Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Shows how to implement the GetPixel type using a PIL Image object's getpixel method. Coordinates are zero-indexed. ```python from typing import Callable, Tuple # Using PIL Image's getpixel: from PIL import Image image = Image.open("photo.png") get_pixel: Callable[[Tuple[int, int]], Tuple[int, int, int, int]] = image.getpixel # Get the color at position (10, 20) rgba = get_pixel((10, 20)) # Returns e.g., (255, 128, 0, 255) ``` -------------------------------- ### Example RGBA Color Tuples Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Illustrates the creation of RGBA tuples for opaque and transparent colors. Ensure values are within the 0-255 range. ```python from typing import Tuple # RGBA tuple pixel: Tuple[int, int, int, int] = (255, 0, 0, 255) # Red, opaque transparent: Tuple[int, int, int, int] = (255, 0, 0, 0) # Red, transparent ``` -------------------------------- ### Type Hint Examples from Table Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Illustrates various Python type hints used for method parameters and return types in Rich Pixels, such as Union, Optional, Mapping, Iterable, and Callable. ```python Union[PurePath, str] ``` ```python Optional[Tuple[int, int]] ``` ```python Mapping[str, Segment] ``` ```python Iterable[Segment] ``` ```python tuple[int, int] ``` ```python Callable[[Tuple[int, int]], RGBA] ``` -------------------------------- ### Handle FileNotFoundError for Image Loading Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md This example demonstrates how to catch a FileNotFoundError when the specified image path does not exist. It's crucial for robust image loading operations. ```python try: pixels = Pixels.from_image_path("nonexistent.png") except FileNotFoundError: print("Image file not found") ``` -------------------------------- ### Handle Transparent Pixels with Background Color Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Configure the renderer with a default color to handle transparent areas of an image. This example uses a black background for transparency. ```python from rich_pixels import Pixels, HalfcellRenderer # Use black background for transparent areas renderer = HalfcellRenderer(default_color="black") pixels = Pixels.from_image_path("image.png", renderer=renderer) console.print(pixels) ``` -------------------------------- ### Render Pixels in a Rich Table Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Use the Pixels class as a Rich renderable to display images within Rich tables. Ensure Rich is installed. ```python from rich.table import Table from rich_pixels import Pixels table = Table() table.add_column("Image") pixels = Pixels.from_image_path("photo.png") table.add_row(pixels) console.print(table) ``` -------------------------------- ### ASCII Art with Character Mapping Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Customize the appearance of ASCII art by mapping specific characters to Rich Segments with styles. This example styles '#' with a red background and 'O' with yellow. ```python from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style grid = """ ######### # # # O # # # ######### """ mapping = { "#": Segment(" ", Style.parse("on red")), "O": Segment("●", Style.parse("yellow")), } pixels = Pixels.from_ascii(grid, mapping=mapping) console.print(pixels) ``` -------------------------------- ### Define a Renderable Segment Generator Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Provides an example of a function that returns a generator yielding Rich Segment objects, suitable for custom rendering logic. ```python from typing import Generator from rich.segment import Segment def render() -> Generator[Segment, None, None]: yield Segment("Hello") ``` -------------------------------- ### Render Manipulated PIL Image with Pixels Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Manipulate images using PIL/Pillow and then render them using the Pixels class. This allows for pre-processing images before display. Requires Pillow to be installed. ```python from PIL import Image, ImageDraw from rich_pixels import Pixels img = Image.new("RGB", (100, 100), color="white") draw = ImageDraw.Draw(img) draw.ellipse((10, 10, 90, 90), fill="red") pixels = Pixels.from_image(img) console.print(pixels) ``` -------------------------------- ### Complex ASCII Art with Multiple Styles Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Apply multiple distinct styles to different characters within ASCII art. This example uses different styles for 'x', 'o', and 'O' characters. ```python from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style grid = """ xx xx ox ox Ox Ox xx xx xxxxxxxxxxxxxxxxx """ mapping = { "x": Segment(" ", Style.parse("yellow on yellow")), "o": Segment(" ", Style.parse("on white")), "O": Segment("O", Style.parse("white on blue")), } pixels = Pixels.from_ascii(grid, mapping=mapping) console.print(pixels) ``` -------------------------------- ### Simple Image Display Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Illustrates the basic workflow for displaying an image using rich-pixels, from loading an image file to printing it to the console. ```text Image file → Pixels.from_image_path() → console.print() ``` -------------------------------- ### Pixels Class Factory Methods and Display Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Demonstrates how to create Pixels objects using various factory methods and how to display them using the console. ```python from rich_pixels import Pixels # Factory methods pixels = Pixels.from_image_path("image.png") pixels = Pixels.from_image(pil_image) pixels = Pixels.from_segments(segments) pixels = Pixels.from_ascii(grid_text, mapping) # Display console.print(pixels) ``` -------------------------------- ### Pixel-by-Pixel Control Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Explains how to construct pixel data from a list of segments. This provides fine-grained control over the image representation. ```text Segment[] → Pixels.from_segments() → console.print() ``` -------------------------------- ### Initialize Pixels with Image Path and FullcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Use this snippet to load an image from a file path, resize it, and specify a custom default background color for the renderer. Ensure the image file exists and is in a supported format. ```python from rich_pixels import Pixels, FullcellRenderer pixels = Pixels.from_image_path( "image.png", resize=(100, 50), renderer=FullcellRenderer(default_color="navy_blue") ) ``` -------------------------------- ### Use Pixels in a Textual Widget Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Integrate the Pixels class into a custom Textual widget by returning a Pixels instance from the render method. Requires Textual to be installed. ```python from textual.widget import Widget from rich_pixels import Pixels class ImageWidget(Widget): def render(self): return Pixels.from_image_path("image.png") ``` -------------------------------- ### Custom Color for Transparency Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Set a custom hex color for transparent areas using the default_color parameter. This example uses a dark gray hex code. ```python from rich_pixels import Pixels, FullcellRenderer # Use hex color for transparency background renderer = FullcellRenderer(default_color="#1a1a1a") pixels = Pixels.from_image_path("image.png", renderer=renderer) console.print(pixels) ``` -------------------------------- ### Renderer Classes for Customization Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Shows how to instantiate HalfcellRenderer and FullcellRenderer for custom pixel rendering, and how to pass them to Pixels factory methods. ```python from rich_pixels import HalfcellRenderer, FullcellRenderer renderer = HalfcellRenderer(default_color="black") renderer = FullcellRenderer() # Typically passed to Pixels factory methods pixels = Pixels.from_image_path("image.png", renderer=renderer) ``` -------------------------------- ### Custom Rendering Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Shows how to use a custom renderer with rich-pixels for advanced image display. This allows for tailored rendering logic beyond the default behavior. ```text Image file → Pixels.from_image_path(renderer=CustomRenderer()) → console.print() ``` -------------------------------- ### Create a Simple Image Widget Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Use this snippet to display a static image within a Textual widget. Ensure the image file exists at the specified path. ```python from textual.widget import Widget from rich_pixels import Pixels class ImageWidget(Widget): def render(self): pixels = Pixels.from_image_path("image.png") return pixels ``` -------------------------------- ### Initialize Renderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Initializes a Renderer instance. A default color can be set for the renderer. ```python Renderer.__init__(*, default_color=None) ``` -------------------------------- ### Get Color from RGBA Pixel Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md Extracts RGB values from an RGBA pixel tuple. Returns a Rich color string if the pixel is not transparent, otherwise returns a default color. ```python def _get_color(pixel: RGBA, default_color: str | None = None) -> str | None: # ... implementation details ... pass ``` -------------------------------- ### Integrating Pixels with Textual Applications Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Pixels.md Demonstrates how to use the Pixels class within a Textual application. Load an image using Pixels.from_image_path and compose it within a Textual container. ```python from textual.app import ComposeResult from textual.widget import Widget from textual.containers import Container from rich_pixels import Pixels class ImageViewer(Widget): def compose(self) -> ComposeResult: pixels = Pixels.from_image_path("image.png") yield Container(pixels) ``` -------------------------------- ### ASCII Art Rendering Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Demonstrates creating pixel data from ASCII art. This workflow involves a text grid and a character mapping to generate the pixel representation. ```text Text grid + character mapping → Pixels.from_ascii() → console.print() ``` -------------------------------- ### Initialize FullcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md Instantiate a FullcellRenderer. Optionally set a default color for transparent pixel backgrounds. ```python from rich_pixels import FullcellRenderer renderer = FullcellRenderer() renderer = FullcellRenderer(default_color="black") ``` -------------------------------- ### Embed Image Widget in Textual Container Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Integrate an image widget within a Textual application's composition. This example shows how to yield a Static widget containing the Rich Pixels object. ```python from textual.app import ComposeResult from textual.widget import Widget from textual.widgets import Static from rich_pixels import Pixels class ImageViewerApp(Widget): def compose(self) -> ComposeResult: pixels = Pixels.from_image_path("image.png") yield Static(pixels) ``` -------------------------------- ### Create a Responsive Image Widget Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md This snippet demonstrates how to create an image widget that automatically resizes to fit the available space of its Textual container. The image is resized using the widget's current dimensions. ```python from textual.widget import Widget from rich_pixels import Pixels class ResponsiveImageWidget(Widget): def render(self): # Resize to widget size pixels = Pixels.from_image_path( "image.png", resize=(self.size.width, self.size.height) ) return pixels ``` -------------------------------- ### Display Image from File Path Source: https://github.com/darrenburns/rich-pixels/blob/master/README.md Load and display an image from a file path using Pixels.from_image_path. ```python from rich_pixels import Pixels from rich.console import Console console = Console() pixels = Pixels.from_image_path("pokemon/bulbasaur.png") console.print(pixels) ``` -------------------------------- ### Pixels Constructor and Factory Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Shows the constructor and static factory methods for creating Pixels objects from various sources like image paths, PIL Images, segments, or ASCII grids. ```python # Constructor (rarely called directly) def __init__(self) -> None ``` ```python # Factory methods (static) @staticmethod def from_image_path( path: Union[PurePath, str], resize: Optional[Tuple[int, int]] = None, renderer: Renderer | None = None, ) -> Pixels ``` ```python @staticmethod def from_image( image: Image, resize: Optional[Tuple[int, int]] = None, renderer: Renderer | None = None, ) -> Pixels ``` ```python @staticmethod def from_segments( segments: Iterable[Segment], ) -> Pixels ``` ```python @staticmethod def from_ascii( grid: str, mapping: Optional[Mapping[str, Segment]] = None ) -> Pixels ``` ```python # Instance method (Rich protocol) def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult ``` -------------------------------- ### Initialize HalfcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md Initialize a HalfcellRenderer. Optionally set a default color for transparent pixel backgrounds. ```python from rich_pixels import HalfcellRenderer # Default renderer renderer = HalfcellRenderer() # With custom background for transparency renderer = HalfcellRenderer(default_color="white") ``` -------------------------------- ### Renderer Class Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Documentation for the Renderer base class and its concrete implementations for image rendering. ```APIDOC ## Renderer Class ### Description Base class for rendering images into segments. ### Constructor - `Renderer.__init__(default_color: str = 'black')`: Constructor with an optional default color. ### Methods - `Renderer.render(image)`: Convert an image into segments. ### Renderers - **HalfcellRenderer**: Compact vertical resolution renderer (default). - **FullcellRenderer**: Full vertical resolution renderer. ``` -------------------------------- ### Image Rendering with HalfcellRenderer and FullcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md This snippet demonstrates how to load an image and render it using both HalfcellRenderer and FullcellRenderer. It also shows how to apply a custom default background color to the HalfcellRenderer. ```python from rich_pixels import HalfcellRenderer, FullcellRenderer from rich.console import Console from PIL import Image console = Console() image = Image.open("example.png") # Using HalfcellRenderer pixels_half = Pixels.from_image(image, renderer=HalfcellRenderer()) console.print("[Half-cell]") console.print(pixels_half) # Using FullcellRenderer pixels_full = Pixels.from_image(image, renderer=FullcellRenderer()) console.print("[Full-cell]") console.print(pixels_full) # With custom default color pixels_custom = Pixels.from_image( image, renderer=HalfcellRenderer(default_color="navy_blue") ) console.print("[With Custom Background]") console.print(pixels_custom) ``` -------------------------------- ### ASCII Art from File with Styling Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Load ASCII art from a text file and apply custom styling using a character mapping. This allows for complex, pre-designed ASCII art to be rendered with specific visual attributes. ```python from pathlib import Path from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style # Read ASCII art from file grid_file = Path("art.txt") grid = grid_file.read_text() # Define color mapping mapping = { "#": Segment(" ", Style.parse("on green")), ".": Segment(" ", Style.parse("on blue")), } pixels = Pixels.from_ascii(grid, mapping=mapping) console.print(pixels) ``` -------------------------------- ### Load and Convert PIL Image to Pixels Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Demonstrates loading an image file using Pillow, optionally resizing it, and then converting it into a Pixels object for terminal display. ```python from PIL import Image from rich_pixels import Pixels # Load an image with Image.open("photo.png") as img: # Optionally manipulate img.thumbnail((200, 150)) # Convert to Pixels pixels = Pixels.from_image(img) ``` -------------------------------- ### Gallery with Progress Indicator Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Create an interactive gallery that displays images sequentially while showing a progress bar. This pattern is useful for loading and displaying a large number of images. ```python from pathlib import Path from rich_pixels import Pixels from rich.progress import Progress image_dir = Path("images") images = list(image_dir.glob("*.png")) with Progress() as progress: task = progress.add_task("[cyan]Loading...", total=len(images)) for image_path in images: pixels = Pixels.from_image_path(image_path, resize=(60, 30)) console.print(f"[bold]{image_path.name}[/bold]") console.print(pixels) progress.advance(task) ``` -------------------------------- ### Rich Pixels Repository File Structure Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Provides an overview of the directory structure for the rich-pixels repository, highlighting key files and their purposes. ```text rich-pixels/ ├── rich_pixels/ │ ├── __init__.py (exports: Pixels, Renderer, *) │ ├── _pixel.py (Pixels class, see api-reference/Pixels.md) │ └── _renderer.py (Renderer classes, see api-reference/Renderer.md) ├── tests/ │ └── test_pixel.py (test cases) ├── pyproject.toml (dependencies, metadata) └── README.md (project overview) ``` -------------------------------- ### Package Exports (__init__) Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Lists the symbols that are directly available when importing from the main rich_pixels package. ```python __all__ = [ "Pixels", "Renderer", "HalfcellRenderer", "FullcellRenderer", ] ``` -------------------------------- ### Package Structure Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Illustrates the directory structure of the rich-pixels package, highlighting the main modules and their purposes. ```tree rich_pixels/ ├── __init__.py (public API exports) ├── _pixel.py (Pixels class) └── _renderer.py (Renderer classes) ``` -------------------------------- ### Initialize Pixels Instance Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Pixels.md Directly initialize an empty Pixels instance. This is rarely used as factory methods are preferred. ```python from rich_pixels import Pixels pixels = Pixels() ``` -------------------------------- ### Handle Transparency with Default Color Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Renders an image using `HalfcellRenderer` and specifies a default color for transparent areas. Requires `HalfcellRenderer` import. ```python from rich_pixels import Pixels, HalfcellRenderer pixels = Pixels.from_image_path( "image.png", renderer=HalfcellRenderer(default_color="black") ) console.print(pixels) ``` -------------------------------- ### Basic Usage Imports Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Essential imports for basic usage of the rich-pixels library with the console. ```python from rich_pixels import Pixels from rich.console import Console ``` -------------------------------- ### Render Image with Renderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Renders an image into a list of Segments using the specified resize dimensions. This is the base method for rendering. ```python Renderer.render(image, resize) -> list[Segment] ``` -------------------------------- ### Initialize HalfcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md Initialize a HalfcellRenderer with an optional default background color for transparent pixels. Use this to set a specific background for transparent areas or rely on the terminal's default. ```python from rich_pixels import HalfcellRenderer # Renderer with default transparent background (terminal's background) renderer = HalfcellRenderer() # Renderer with black background for transparent areas renderer = HalfcellRenderer(default_color="black") # Renderer with hex color renderer = HalfcellRenderer(default_color="#1a1a1a") ``` -------------------------------- ### Reuse Renderer Instance Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md To improve efficiency when processing multiple images, create a single renderer instance and reuse it across different `Pixels.from_image_path` calls. ```python from rich_pixels import Pixels, FullcellRenderer renderer = FullcellRenderer(default_color="black") # Reuse for multiple images for image_path in image_paths: pixels = Pixels.from_image_path(image_path, renderer=renderer) console.print(pixels) ``` -------------------------------- ### Create Rich Segment with Style Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Illustrates creating a Segment object from the Rich library, which represents a styled character or string for terminal output. Requires importing Segment and Style. ```python from rich.segment import Segment from rich.style import Style segment = Segment("█", Style.parse("red")) # Red block character segment = Segment(" ", Style.parse("on blue")) # Blue background ``` -------------------------------- ### Renderer Constructor Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Renderer.md Initializes a Renderer instance with an optional default background color for transparent pixels. This color is used when the image has transparent areas. ```APIDOC ## Renderer Constructor ### Description Initializes a renderer with an optional default background color for transparent pixels. ### Method Signature `__init__(self, *, default_color: str | None = None) -> None` ### Parameters #### Keyword Arguments - **default_color** (`str | None`) - Optional - Default: `None` - A Rich color name (e.g., "red", "#ff0000", "rgb(255,0,0)") to use as the background for transparent pixels. If `None`, transparent areas are rendered as the terminal's default background. ### Returns `Renderer` instance ### Example ```python from rich_pixels import HalfcellRenderer # Renderer with default transparent background (terminal's background) renderer = HalfcellRenderer() # Renderer with black background for transparent areas renderer = HalfcellRenderer(default_color="black") # Renderer with hex color renderer = HalfcellRenderer(default_color="#1a1a1a") ``` ``` -------------------------------- ### Full API Import Pattern Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Imports the main Pixels class along with all available renderers and necessary Rich types for comprehensive usage. ```python from rich_pixels import Pixels, Renderer, HalfcellRenderer, FullcellRenderer from rich.console import Console from rich.segment import Segment from rich.style import Style ``` -------------------------------- ### Load and Display Image Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Loads an image from a file path and displays it in the console using the Pixels class. Requires the rich-pixels and rich libraries. ```python from rich_pixels import Pixels from rich.console import Console console = Console() pixels = Pixels.from_image_path("pokemon.png") console.print(pixels) ``` -------------------------------- ### Default Renderer (HalfcellRenderer) Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Use the default HalfcellRenderer by simply creating a Pixels object from an image path. This is the most straightforward way to display an image. ```python from rich_pixels import Pixels # Implicitly uses HalfcellRenderer pixels = Pixels.from_image_path("image.png") console.print(pixels) ``` -------------------------------- ### Create Pixels from Image Path Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Pixels.md Load an image from a file path and convert it to a Pixels object. Supports resizing and custom renderers. Ensure the image file exists and is in a supported format. ```python from rich_pixels import Pixels from rich.console import Console console = Console() # Load and display an image at original size pixels = Pixels.from_image_path("path/to/image.png") console.print(pixels) # Load and resize to 40x30 cells pixels = Pixels.from_image_path("pokemon.png", resize=(40, 30)) console.print(pixels) # Load with custom renderer from rich_pixels import FullcellRenderer pixels = Pixels.from_image_path("photo.jpg", renderer=FullcellRenderer()) console.print(pixels) ``` -------------------------------- ### Typical Usage of Pixels with FullcellRenderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Demonstrates how to load an image and render it using the Pixels class with a FullcellRenderer. Requires 'rich_pixels' and 'rich' libraries. ```python from rich_pixels import Pixels, FullcellRenderer from rich.console import Console console = Console() pixels = Pixels.from_image_path("image.png", renderer=FullcellRenderer()) console.print(pixels) ``` -------------------------------- ### Apply Filters to Image with PIL Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Applies image filters, such as Gaussian blur, using PIL's filter method before rendering. Requires importing ImageFilter from PIL. ```python from PIL import Image, ImageFilter from rich_pixels import Pixels image = Image.open("photo.png") # Apply blur filter blurred = image.filter(ImageFilter.GaussianBlur(radius=2)) pixels = Pixels.from_image(blurred) console.print(pixels) ``` -------------------------------- ### Renderer Constructor and Render Method Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Details the constructor for the base Renderer class and its primary render method, which converts an image into a list of segments. ```python # Base class constructor def __init__(self, *, default_color: str | None = None) -> None ``` ```python # Render method def render(self, image: Image, resize: tuple[int, int] | None) -> list[Segment] ``` -------------------------------- ### Textual Widget Rendering Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Describes the process of rendering Pixels data into a Textual widget for display within a Textual application. ```text Pixels → Widget.render() → display ``` -------------------------------- ### Rich Integration Workflow Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Details how to integrate rich-pixels with the Rich library for display in various Rich components like Panels, Tables, or Layouts. ```text Pixels → Panel/Table/Layout → console.print() ``` -------------------------------- ### Use RGB and Hex Color Strings for Renderers Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Configure renderers with specific colors using named colors, RGB strings (e.g., 'rgb(R,G,B)'), or hex color codes (e.g., '#RRGGBB'). This allows for precise color control when rendering pixels. ```python from rich_pixels import Pixels, FullcellRenderer # Named colors renderer = FullcellRenderer(default_color="navy_blue") # RGB strings renderer = FullcellRenderer(default_color="rgb(25,25,112)") # Hex colors renderer = FullcellRenderer(default_color="#191b70") pixels = Pixels.from_image_path("photo.png", renderer=renderer) console.print(pixels) ``` -------------------------------- ### Pixels Class Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/INDEX.md Documentation for the Pixels class, including methods for loading images from various sources and Rich integration. ```APIDOC ## Pixels Class ### Description Main renderable class for rich-pixels. ### Methods - `from_image_path(path: str)`: Load image from file path. - `from_image(image: PIL.Image.Image)`: Create from a PIL Image object. - `from_segments(segments: list)`: Create from Rich Segments. - `from_ascii(ascii_grid: list[list[str]])`: Create from an ASCII art grid. - `__rich_console__()`: Rich protocol integration. ``` -------------------------------- ### Create Pixels from Image Path Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Use this factory method to create a Pixels object from an image file path. Optional resizing and a custom renderer can be specified. ```python Pixels.from_image_path(path, resize=None, renderer=None) -> Pixels ``` -------------------------------- ### Basic ASCII Art Display Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Render simple ASCII art directly to the console. The grid string is parsed and displayed using default styling. ```python from rich_pixels import Pixels from rich.console import Console console = Console() grid = """ * * \ / * / \ * * """ pixels = Pixels.from_ascii(grid) console.print(pixels) ``` -------------------------------- ### Display ASCII Art with Custom Mapping Source: https://github.com/darrenburns/rich-pixels/blob/master/README.md Convert ASCII art into a styled terminal display using Pixels.from_ascii and a character-to-segment mapping. ```python from rich_pixels import Pixels from rich.console import Console from rich.segment import Segment from rich.style import Style console = Console() # Draw your shapes using any character you want grid = """ xx xx ox ox Ox Ox xx xx xxxxxxxxxxxxxxxxx """ # Map characters to different characters/styles mapping = { "x": Segment(" ", Style.parse("yellow on yellow")), "o": Segment(" ", Style.parse("on white")), "O": Segment(" ", Style.parse("on blue")), } pixels = Pixels.from_ascii(grid, mapping) console.print(pixels) ``` -------------------------------- ### Parse Rich Style Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Shows how to parse style strings to create Style objects for terminal text formatting. Supports named colors, backgrounds, and RGB values. ```python from rich.style import Style style = Style.parse("red on white") # Red text on white background style = Style.parse("yellow") # Yellow text style = Style.parse("rgb(255,0,0)") # RGB color ``` -------------------------------- ### Resize Large Images Before Conversion Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md For better performance, resize large images using the `resize` parameter during `Pixels.from_image_path` initialization rather than after conversion. ```python from rich_pixels import Pixels # Good: Resize before conversion (faster) pixels = Pixels.from_image_path("large.png", resize=(80, 40)) # Less efficient: Resize after conversion (same result but slower) # Use resize parameter instead ``` -------------------------------- ### Pixels Factory Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md These factory methods allow you to create Pixels objects from various sources, including image files, PIL Images, segment data, and ASCII grids. ```APIDOC ## Pixels Factory Methods ### `Pixels.from_image_path(path, resize=None, renderer=None)` Creates a `Pixels` object from an image file path. - **path** (str) - The path to the image file. - **resize** (Tuple[int, int], optional) - The target size to resize the image to. Defaults to None. - **renderer** (Renderer, optional) - The renderer to use for conversion. Defaults to None. ### `Pixels.from_image(image, resize=None, renderer=None)` Creates a `Pixels` object from a PIL Image object. - **image** (PIL.Image.Image) - The Pillow image object. - **resize** (Tuple[int, int], optional) - The target size to resize the image to. Defaults to None. - **renderer** (Renderer, optional) - The renderer to use for conversion. Defaults to None. ### `Pixels.from_segments(segments)` Creates a `Pixels` object from a list of Rich `Segment` objects. - **segments** (list[Segment]) - A list of Rich `Segment` objects. ### `Pixels.from_ascii(grid, mapping=None)` Creates a `Pixels` object from an ASCII grid representation. - **grid** (list[list[str]]) - A 2D list representing the ASCII grid. - **mapping** (dict, optional) - A mapping from characters to colors. Defaults to None. ``` -------------------------------- ### Import Core Rich Pixels Components Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Imports the essential classes from the rich_pixels package for use in your application. ```python from rich_pixels import ( Pixels, Renderer, HalfcellRenderer, FullcellRenderer, ) ``` -------------------------------- ### Display Image with Rich Layout Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Integrate images into a Rich Layout by splitting the layout and updating specific sections with Panels containing the Pixels object. This allows for complex arrangements of content. ```python from rich.layout import Layout from rich_pixels import Pixels from rich.panel import Panel layout = Layout() layout.split( Layout(name="top"), Layout(name="bottom") ) pixels = Pixels.from_image_path("photo.png", resize=(80, 15)) layout["top"].update(Panel(pixels, title="Image")) layout["bottom"].update(Panel("Image details here")) console.print(layout) ``` -------------------------------- ### Internal Renderer Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/EXPORTS.md Lists internal methods of the Renderer and HalfcellRenderer classes, including `_get_color`, `_get_range`, `_render_line`, and `_render_halfcell`. These are for internal use only. ```python _get_color(pixel: RGBA, default_color: str | None) -> str | None ``` ```python Renderer._get_range(height: int) -> range ``` ```python Renderer._render_line(line_index, width, get_pixel) -> list[Segment] ``` ```python HalfcellRenderer._render_halfcell(x, y, get_pixel) -> Segment ``` -------------------------------- ### Create Segments from a List Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Demonstrates constructing a Segments object from a list of individual Segment objects. This is useful for managing collections of styled terminal output. ```python from rich.segment import Segments, Segment segments_list = [Segment("a"), Segment("b"), Segment("\n")] segments = Segments(segments_list) ``` -------------------------------- ### Create ASCII Art with Styling Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Generates a `Pixels` object from an ASCII grid string, mapping characters to styled `Segment` objects. Requires `Segment` and `Style` imports. ```python from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style grid = """ ########### # o # ########### """ mapping = { "#": Segment(" ", Style.parse("on red")), "o": Segment("●", Style.parse("yellow")), } pixels = Pixels.from_ascii(grid, mapping=mapping) console.print(pixels) ``` -------------------------------- ### Load and Display Image with rich-pixels Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Load an image from a file path and display it in the terminal using the Pixels class and Rich Console. ```python from rich_pixels import Pixels from rich.console import Console console = Console() # Load and display an image pixels = Pixels.from_image_path("photo.png") console.print(pixels) # Resize to terminal width pixels = Pixels.from_image_path("photo.png", resize=(100, 50)) console.print(pixels) ``` -------------------------------- ### Custom Rendering Imports Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Imports required for using custom rendering options with Pixels objects. ```python from rich_pixels import Pixels, HalfcellRenderer, FullcellRenderer ``` -------------------------------- ### Create Pixels from Segments Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Constructs a Pixels object by manually defining individual segments with specific styles. Useful for precise control over pixel appearance. ```python from rich.segment import Segment from rich.style import Style from rich_pixels import Pixels # Build segments manually segments = [ Segment("█", Style.parse("red")), Segment("█", Style.parse("blue")), Segment("\n", None), Segment("█", Style.parse("green")), Segment("█", Style.parse("yellow")), ] pixels = Pixels.from_segments(segments) console.print(pixels) ``` -------------------------------- ### Integrate with Textual Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Shows how to use `rich_pixels.Pixels` within a Textual `Widget` by returning a `Pixels` object from the `render` method. ```python from textual.widget import Widget from textual.containers import Container from rich_pixels import Pixels class ImageViewer(Widget): def render(self): pixels = Pixels.from_image_path("image.png") return pixels ``` -------------------------------- ### Handle Missing Image Files Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md This code checks if an image file exists before attempting to load it. If the file is not found, it prints an error message to the console. ```python from pathlib import Path from rich_pixels import Pixels image_path = "photo.png" if not Path(image_path).exists(): console.print("[red]Error: Image file not found[/red]") else: pixels = Pixels.from_image_path(image_path) console.print(pixels) ``` -------------------------------- ### Display Pillow Image Object Source: https://github.com/darrenburns/rich-pixels/blob/master/README.md Create a Pixels object from an existing Pillow Image object. This allows for pre-modification of the image. ```python from rich_pixels import Pixels from rich.console import Console from PIL import Image console = Console() with Image.open("path/to/image.png") as image: pixels = Pixels.from_image(image) console.print(pixels) ``` -------------------------------- ### Render ASCII Art with Custom Colors Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Create a Pixels object from an ASCII art string with a custom mapping of characters to Rich Segments and Styles. ```python from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style grid = """ xx xx ox ox Ox Ox xx xx xxxxxxxxxxxxxxxxx " mapping = { "x": Segment(" ", Style.parse("yellow on yellow")), "o": Segment(" ", Style.parse("on white")), "O": Segment("O", Style.parse("white on blue")), } pixels = Pixels.from_ascii(grid, mapping=mapping) console.print(pixels) ``` -------------------------------- ### Advanced Pixel Mapping Imports Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Imports needed for advanced pixel mapping scenarios, including Segment and Style objects. ```python from rich_pixels import Pixels from rich.segment import Segment from rich.style import Style ``` -------------------------------- ### Type Relationships in Pixels Class Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/types.md Shows the hierarchical structure and factory methods of the Pixels class, including its internal segments and how different methods return Pixels objects. ```plaintext Pixels ├── _segments: Segments (internal) └── Factory methods return Pixels: ├── from_image_path(path, resize, renderer: Renderer) ├── from_image(image: Image, resize, renderer: Renderer) ├── from_segments(segments: Iterable[Segment]) └── from_ascii(grid: str, mapping: Mapping[str, Segment]) ``` -------------------------------- ### Create Pixels from ASCII Grid Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Use this factory method to create a Pixels object from an ASCII character grid. A custom mapping can be provided to define character-to-color associations. ```python Pixels.from_ascii(grid, mapping=None) -> Pixels ``` -------------------------------- ### Use Full-Cell Renderer Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md Renders an image using the `FullcellRenderer`, which uses a single character per cell. Requires `FullcellRenderer` import. ```python from rich_pixels import Pixels, FullcellRenderer pixels = Pixels.from_image_path( "image.png", renderer=FullcellRenderer() ) console.print(pixels) ``` -------------------------------- ### Validate and Load Image Safely Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md This function safely loads an image, checks its dimensions against a maximum size, and resizes it using `thumbnail` if it exceeds the limit. It returns the Pillow Image object or None if an error occurs. ```python from PIL import Image def load_image_safely(path, max_size=(1000, 1000)): try: with Image.open(path) as image: # Check size if image.size[0] > max_size[0] or image.size[1] > max_size[1]: # Resize if too large image.thumbnail(max_size) return image except Exception as e: console.print(f"[red]Error loading image: {e}[/red]") return None image = load_image_safely("photo.png") if image: pixels = Pixels.from_image(image) console.print(pixels) ``` -------------------------------- ### Renderer Class Inheritance Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Module-Overview.md Illustrates the inheritance structure of the Renderer classes within the rich_pixels library. ```text Renderer (abstract base) ├── HalfcellRenderer └── FullcellRenderer ``` -------------------------------- ### Renderer Methods Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/REFERENCE.md These methods are used for rendering image data into terminal-compatible segments. ```APIDOC ## Renderer Methods ### `Renderer.__init__(*, default_color=None)` Initializes a Renderer instance. - **default_color** (str, optional) - The default color to use if none is specified. Defaults to None. ### `Renderer.render(image, resize)` Abstract method to render an image into a list of segments. - **image** (PIL.Image.Image) - The Pillow image object to render. - **resize** (Tuple[int, int]) - The target size for rendering. - **Returns**: list[Segment] - A list of Rich `Segment` objects. ### `HalfcellRenderer.render(image, resize)` Renders an image using half-height cells. - **image** (PIL.Image.Image) - The Pillow image object to render. - **resize** (Tuple[int, int]) - The target size for rendering. - **Returns**: list[Segment] - A list of Rich `Segment` objects. ### `FullcellRenderer.render(image, resize)` Renders an image using full-height cells. - **image** (PIL.Image.Image) - The Pillow image object to render. - **resize** (Tuple[int, int]) - The target size for rendering. - **Returns**: list[Segment] - A list of Rich `Segment` objects. ``` -------------------------------- ### Display Multiple Images with Rich Columns Source: https://github.com/darrenburns/rich-pixels/blob/master/_autodocs/api-reference/Usage-Patterns.md Arrange multiple images side-by-side using Rich's Columns. This is useful for creating galleries or comparing several images. ```python from rich_pixels import Pixels from rich.columns import Columns images = [ Pixels.from_image_path(f"photo{i}.png", resize=(30, 30)) for i in range(1, 4) ] columns = Columns(images) console.print(columns) ```