### Simple Quantization Example Source: https://docs.rs/pixo/latest/pixo/guides/quantization/index_search= A step-by-step numerical example demonstrating the quantization process and the resulting error. It highlights how rounding introduces loss, reducing the precision of DCT coefficients for better compression. ```plaintext DCT coefficient: 47 Quantization value: 10 Quantized result: round(47/10) = round(4.7) = 5 During decoding: Reconstructed: 5 × 10 = 50 Error: |47 - 50| = 3 ``` -------------------------------- ### JavaScript Example for Pixo WASM Source: https://docs.rs/pixo/latest/pixo/wasm/index Example demonstrating how to use the pixo WebAssembly module in JavaScript for image encoding and resizing. It includes initialization, getting image data, resizing, and encoding to PNG and JPEG. ```javascript import init, { encodePng, encodeJpeg, resizeImage, bytesPerPixel } from 'pixo'; await init(); // Get pixels from canvas const ctx = canvas.getContext('2d'); const imageData = ctx.getImageData(0, 0, width, height); // Resize image to half size using Lanczos3 (RGBA=3, algorithm=2) const resized = resizeImage(imageData.data, width, height, width/2, height/2, 3, 2); // Encode as PNG (RGBA=3, preset=1 balanced, lossy=true for smaller files) const pngBytes = encodePng(resized, width/2, height/2, 3, 1, true); // Encode as JPEG (RGB=2, quality=85, preset=1 balanced, subsampling=true) const rgb = stripAlpha(resized); // Assuming stripAlpha is defined elsewhere const jpegBytes = encodeJpeg(rgb, width/2, height/2, 2, 85, 1, true); ``` -------------------------------- ### Initialize PngOptions with Specific Overrides in Rust Source: https://docs.rs/pixo/latest/pixo/guides/introduction_to_rust/index This example demonstrates how to create an instance of `PngOptions` in Rust, starting with default values and then overriding specific fields. It utilizes the `PngOptions::default()` method to get a default struct and then uses the struct update syntax (`..`) to set a custom `compression_level` while keeping other settings as default. ```rust let opts = PngOptions { compression_level: 9, ..PngOptions::default() // Use defaults for everything else }; ``` -------------------------------- ### Install Pixo CLI using Cargo Source: https://docs.rs/pixo/latest/pixo/guides/cli/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Instructions for installing the pixo command-line tool from source using Cargo, with an option to enable the 'cli' feature. ```bash # Install from source cargo install --path . --features cli # Or build locally cargo build --release --features cli ``` -------------------------------- ### Rust Visibility Modifiers and Example Source: https://docs.rs/pixo/latest/pixo/guides/introduction_to_rust/index_search=std%3A%3Avec Demonstrates different visibility levels in Rust (public, crate-internal, parent module, private) using an example with `pub` and `pub(crate)` on a `ColorType` enum. ```rust pub — visible everywhere pub(crate) — visible within this crate only pub(super) — visible to parent module (nothing) — private to current module // From src/color.rs impl ColorType { // Public: anyone can call this #[inline] pub const fn bytes_per_pixel(self) -> usize { match self { ColorType::Gray => 1, ColorType::GrayAlpha => 2, ColorType::Rgb => 3, ColorType::Rgba => 4, } } // Crate-internal: only our code can use this #[inline] pub(crate) const fn png_color_type(self) -> u8 { // ... } } ``` -------------------------------- ### PngOptions Example Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptions_search= Example demonstrating how to encode a PNG image using PngOptions. ```APIDOC ## Example Usage ```rust use pixo::png::{encode, PngOptions}; use pixo::ColorType; let pixels = vec![255, 0, 0, 255]; // 1x1 RGBA red pixel let options = PngOptions::builder(1, 1) .color_type(ColorType::Rgba) .preset(1) // balanced .build(); let png_bytes = encode(&pixels, &options).unwrap(); ``` ``` -------------------------------- ### Paeth Predictor Example Calculation Source: https://docs.rs/pixo/latest/pixo/guides/png_encoding/index_search=u32+-%3E+bool Demonstrates a practical example of the Paeth predictor's effectiveness in a smooth diagonal gradient scenario. It shows how the predictor can accurately determine the pixel value by fitting a plane through its neighbors. ```pseudocode C=100 | B=110 ------+------ A=110 | X=? p = 110 + 110 - 100 = 120 ``` -------------------------------- ### Example: Encode Image with Custom PNG Options (Rust) Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptions_search=std%3A%3Avec Demonstrates how to create PngOptions using a builder pattern, set specific encoding parameters like color type and compression preset, and then encode pixel data into PNG format. This example highlights the flexibility in customizing PNG output. ```rust use pixo::png::{encode, PngOptions}; use pixo::ColorType; let pixels = vec![255, 0, 0, 255]; // 1x1 RGBA red pixel let options = PngOptions::builder(1, 1) .color_type(ColorType::Rgba) .preset(1) // balanced .build(); let png_bytes = encode(&pixels, &options).unwrap(); ``` -------------------------------- ### Basic Pixo CLI Usage Examples Source: https://docs.rs/pixo/latest/pixo/guides/cli/index_search= Demonstrates common ways to use the pixo CLI for image compression. This includes specifying input and output files, formats, quality, and compression levels. ```bash # Basic usage - compress to JPEG (default) pixo input.png -o output.jpg # Compress to PNG with maximum compression pixo input.jpg -o output.png -c 9 # JPEG with custom quality (1-100) pixo photo.png -o photo.jpg -q 90 # JPEG with 4:2:0 chroma subsampling (smaller files) pixo photo.png -o photo.jpg --subsampling s420 # PNG with specific filter strategy pixo input.jpg -o output.png --filter paeth # Adaptive fast (reduced trials) filter strategy pixo input.jpg -o output.png --filter adaptive-fast # Convert to grayscale pixo color.png -o gray.jpg --grayscale # Verbose output with timing and size info pixo input.png -o output.jpg -v # Preview operation without writing (dry run) pixo input.png -o output.jpg -n # Quiet mode (suppress output) pixo input.png -o output.jpg --quiet # JSON output for scripting pixo input.png -o output.jpg --json ``` -------------------------------- ### Pixo CLI JSON Output Example Source: https://docs.rs/pixo/latest/pixo/guides/cli/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to obtain machine-readable JSON output from the pixo CLI, which is useful for integrating with scripting and automation tools. ```bash $ pixo input.png -o output.jpg --json {"input":"input.png","output":"output.jpg","input_size":102400,"output_size":51200,"ratio":50.0} With --dry-run: $ pixo input.png -o output.jpg --json -n {"dry_run":true,"input":"input.png","output":"output.jpg","input_size":102400,"output_size":51200,"ratio":50.0} ``` -------------------------------- ### Example: Encode PNG Image with Custom Options Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptions_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create PngOptions using a builder pattern and encode a simple pixel buffer into PNG format. This example shows setting dimensions, color type, and a compression preset. ```rust use pixo::png::{encode, PngOptions}; use pixo::ColorType; let pixels = vec![255, 0, 0, 255]; // 1x1 RGBA red pixel let options = PngOptions::builder(1, 1) .color_type(ColorType::Rgba) .preset(1) // balanced .build(); let png_bytes = encode(&pixels, &options).unwrap(); ``` -------------------------------- ### JavaScript Example for Pixo Wasm Image Operations Source: https://docs.rs/pixo/latest/pixo/wasm/index_search=std%3A%3Avec Example demonstrating how to use the pixo WebAssembly module in JavaScript for image encoding and resizing. It shows initialization, resizing an image using Lanczos3, encoding to PNG, and encoding to JPEG. ```javascript import init, { encodePng, encodeJpeg, resizeImage, bytesPerPixel } from 'pixo'; await init(); // Get pixels from canvas const ctx = canvas.getContext('2d'); const imageData = ctx.getImageData(0, 0, width, height); // Resize image to half size using Lanczos3 (RGBA=3, algorithm=2) const resized = resizeImage(imageData.data, width, height, width/2, height/2, 3, 2); // Encode as PNG (RGBA=3, preset=1 balanced, lossy=true for smaller files) const pngBytes = encodePng(resized, width/2, height/2, 3, 1, true); // Encode as JPEG (RGB=2, quality=85, preset=1 balanced, subsampling=true) const rgb = stripAlpha(resized); const jpegBytes = encodeJpeg(rgb, width/2, height/2, 2, 85, 1, true); ``` -------------------------------- ### Integer DCT Calculation Example Source: https://docs.rs/pixo/latest/pixo/guides/compression_evolution/index_search= Demonstrates the conversion of a floating-point DCT constant to its fixed-point integer equivalent by scaling and using bit shifts for multiplication. This ensures platform reproducibility and potential speed improvements. ```plaintext Floating-point: cos(π/8) = 0.9238795... Fixed-point: (0.9238795 × 8192) ≈ 7568 Multiplication becomes: result = (a × 7568) >> 13 // Shift replaces division ``` -------------------------------- ### Example of Using ResizeOptions (Rust) Source: https://docs.rs/pixo/latest/pixo/resize/struct.ResizeOptions_search=std%3A%3Avec Demonstrates how to create and configure ResizeOptions for an image resizing operation. It shows the use of the builder pattern to set dimensions, color type, and algorithm, and then calls the `resize` function. Requires the `pixo` crate and its associated types. ```rust use pixo::resize::{resize, ResizeOptions, ResizeAlgorithm}; use pixo::ColorType; let pixels = vec![128u8; 100 * 100 * 4]; let options = ResizeOptions::builder(100, 100) .dst(50, 50) .color_type(ColorType::Rgba) .algorithm(ResizeAlgorithm::Lanczos3) .build(); let resized = resize(&pixels, &options).unwrap(); ``` -------------------------------- ### Rust: Builder Pattern Example for PngOptions Source: https://docs.rs/pixo/latest/pixo/guides/introduction_to_rust/index_search=u32+-%3E+bool Demonstrates the builder pattern in Rust using struct initialization. It shows how to create a PngOptions instance, overriding specific fields while using default values for the rest. ```rust let opts = PngOptions { compression_level: 9, ..PngOptions::default() // Use defaults for everything else }; ``` -------------------------------- ### Rust: Get Metadata with Fallible Path Operations Source: https://docs.rs/pixo/latest/pixo/error/type.Result_search=u32+-%3E+bool Illustrates using `and_then` with file system operations in Rust to handle potential errors. This example attempts to get metadata for a path, returning an error if the path is invalid or inaccessible. It demonstrates error kind checking. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Basic Pixo CLI Usage Examples Source: https://docs.rs/pixo/latest/pixo/guides/cli/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates fundamental ways to use the pixo CLI for image compression, including output format specification, quality adjustments, and specific filter strategies. ```bash # Basic usage - compress to JPEG (default) pixo input.png -o output.jpg # Compress to PNG with maximum compression pixo input.jpg -o output.png -c 9 # JPEG with custom quality (1-100) pixo photo.png -o photo.jpg -q 90 # JPEG with 4:2:0 chroma subsampling (smaller files) pixo photo.png -o photo.jpg --subsampling s420 # PNG with specific filter strategy pixo input.jpg -o output.png --filter paeth # Adaptive fast (reduced trials) filter strategy pixo input.jpg -o output.png --filter adaptive-fast # Convert to grayscale pixo color.png -o gray.jpg --grayscale ``` -------------------------------- ### Progressive Scan Structure Example Source: https://docs.rs/pixo/latest/pixo/guides/compression_evolution/index_search= Visualizes the multi-scan structure of progressive encoding in JPEG. It shows how different scans transmit varying levels of detail, starting with DC coefficients (brightness), then low-frequency AC (shapes), and finally higher frequencies (details). ```plaintext Progressive Scan Structure ══════════════════════════ Scan 1: DC coefficients only (overall brightness) ┌─────────────────────────────────────┐ │ ██ │ Just the average │ │ brightness of each │ │ 8×8 block └─────────────────────────────────────┘ Scan 2: Low-frequency AC (basic shapes) ┌─────────────────────────────────────┐ │ ██ ░░ │ Basic gradients │ ░░ │ and large shapes │ │ └─────────────────────────────────────┘ Scan 3-N: Higher frequencies (details, texture) ┌─────────────────────────────────────┐ │ ██ ░░ ░░ ▒▒ ▒▒ ▒▒ ░░ ░░ │ Fine details │ ░░ ▒▒ ▒▒ ▒▒ ░░ ░░ ░░ ░░ │ and textures │ ░░ ▒▒ ░░ ░░ ░░ ░░ ░░ │ └─────────────────────────────────────┘ ``` -------------------------------- ### Rust: Crc32 Default Initialization Source: https://docs.rs/pixo/latest/pixo/compress/crc32/struct.Crc32 Shows how to initialize a Crc32 struct using its Default implementation. This provides a convenient way to get a Crc32 instance with its default starting state, which is equivalent to calling Crc32::new(). ```rust use pixo::compress::crc32::Crc32; let mut crc: Crc32 = Default::default(); let data = b"example data"; crc.update(data); let checksum = crc.finalize(); println!("CRC32 checksum (default init): {}", checksum); ``` -------------------------------- ### Rust: PngOptionsBuilder initialization and configuration Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptionsBuilder_search=std%3A%3Avec Demonstrates how to initialize and configure PngOptionsBuilder. It shows the creation of a new builder with dimensions and setting various options like color type, compression, and lossy settings. ```rust /// Create a new builder with image dimensions. pub fn new(width: u32, height: u32) -> Self /// Set the color type of the pixel data. pub fn color_type(self, color_type: ColorType) -> Self /// Convenience to toggle lossy (Auto quantization) vs. lossless (Off). /// When lossy is true, enables auto-quantization with dithering for better visual quality on photographic content. pub fn lossy(self, lossy: bool) -> Self ``` -------------------------------- ### Handling File Metadata with Result (Rust) Source: https://docs.rs/pixo/latest/pixo/error/type.Result Shows how to safely get file metadata using `Path::metadata()` and chain operations with `and_then`. This example highlights error handling, specifically checking for `ErrorKind::NotFound` when a path does not exist. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Rust: Initialize and Configure ResizeOptionsBuilder Source: https://docs.rs/pixo/latest/pixo/resize/struct.ResizeOptionsBuilder Demonstrates how to create a new ResizeOptionsBuilder with source dimensions and then set destination dimensions, color type, and resizing algorithm. This builder pattern allows for a fluent and readable way to configure resize options. ```rust use pixo::resize::{ResizeOptions, ResizeAlgorithm, ColorType, ResizeOptionsBuilder}; let mut builder = ResizeOptionsBuilder::new(1920, 1080); builder = builder.dst(800, 600); builder = builder.color_type(ColorType::Rgba); builder = builder.algorithm(ResizeAlgorithm::Lanczos3); let options: ResizeOptions = builder.build(); println!("Resize options built successfully."); ``` -------------------------------- ### Rust: Create and Configure ResizeOptionsBuilder Source: https://docs.rs/pixo/latest/pixo/resize/struct.ResizeOptionsBuilder_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the usage of ResizeOptionsBuilder methods to configure resizing parameters. It starts with initializing the builder with source dimensions and then sets destination dimensions, color type, and resizing algorithm. ```rust let options = ResizeOptionsBuilder::new(src_width, src_height) .dst(width, height) .color_type(ColorType::Rgba) .algorithm(ResizeAlgorithm::Lanczos3) .build(); ``` -------------------------------- ### JPEG File Structure Markers Source: https://docs.rs/pixo/latest/pixo/guides/jpeg_encoding/index_search=u32+-%3E+bool Defines the standard markers used in the JPEG file structure. These markers delineate different sections of the JPEG file, such as the start of image, quantization tables, Huffman tables, and the end of the image. ```rust // From src/jpeg/mod.rs const SOI: u16 = 0xFFD8; // Start of Image const EOI: u16 = 0xFFD9; // End of Image const APP0: u16 = 0xFFE0; // JFIF marker const DQT: u16 = 0xFFDB; // Define Quantization Table const SOF0: u16 = 0xFFC0; // Start of Frame (baseline DCT) const DHT: u16 = 0xFFC4; // Define Huffman Table const SOS: u16 = 0xFFDA; // Start of Scan ``` -------------------------------- ### JPEG File Structure Markers Source: https://docs.rs/pixo/latest/pixo/guides/jpeg_encoding/index_search= Defines constants for common JPEG file structure markers. These markers indicate the start and end of the image, as well as the beginning of various segments like JFIF metadata, quantization tables, frame information, Huffman tables, and the encoded image data scan. ```rust const SOI: u16 = 0xFFD8; // Start of Image const EOI: u16 = 0xFFD9; // End of Image const APP0: u16 = 0xFFE0; // JFIF marker const DQT: u16 = 0xFFDB; // Define Quantization Table const SOF0: u16 = 0xFFC0; // Start of Frame (baseline DCT) const DHT: u16 = 0xFFC4; // Define Huffman Table const SOS: u16 = 0xFFDA; // Start of Scan ``` -------------------------------- ### Image Resizing with Pixo Resize Source: https://docs.rs/pixo/latest/pixo/resize/index Demonstrates resizing an RGBA image to new dimensions using the Lanczos3 algorithm with custom options. This example shows how to set destination dimensions, color type, and the resizing algorithm. ```rust use pixo::resize::{resize, ResizeOptions, ResizeAlgorithm}; use pixo::ColorType; // Resize a 100x100 RGBA image to 50x50 using Lanczos3 let pixels = vec![128u8; 100 * 100 * 4]; let options = ResizeOptions::builder(100, 100) .dst(50, 50) .color_type(ColorType::Rgba) .algorithm(ResizeAlgorithm::Lanczos3) .build(); let resized = resize(&pixels, &options).unwrap(); assert_eq!(resized.len(), 50 * 50 * 4); ``` -------------------------------- ### Fast PNG Preset Configuration (Rust) Source: https://docs.rs/pixo/latest/pixo/guides/png_encoding/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes PngOptions using the `fast()` preset. This preset is optimized for development and real-time processing, featuring a low compression level (2) and the AdaptiveFast filter strategy. ```rust PngOptions::fast() ``` -------------------------------- ### PNG Unfiltering (Reverse Predictions) - Sub Filter Example Source: https://docs.rs/pixo/latest/pixo/guides/decoding/index_search= This example illustrates the 'Sub' filter's un-decoding process in PNG images. The stored value is added to the value of the pixel to its left (A) to reconstruct the original pixel data. This process is applied sequentially to each pixel in a scanline after the filter type byte. ```plaintext Stored values: [1, 100, 2, 2, 2, 2, 2, 2] ↑ filter type = Sub ↑ first pixel (no left neighbor, A=0) Decode: Pixel 0: 100 + 0 = 100 Pixel 1: 2 + 100 = 102 Pixel 2: 2 + 102 = 104 Pixel 3: 2 + 104 = 106 ... Reconstructed: 100, 102, 104, 106, 108, 110, 112, 114 ``` -------------------------------- ### TryFrom Trait Implementation Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptionsBuilder_search=std%3A%3Avec Documentation for the `TryFrom` trait implementation, allowing conversions that may fail. ```APIDOC ## TryFrom for T ### Description Provides a way to perform fallible conversions from type `U` into type `T`. ### Method (Implicitly part of a trait, not a direct HTTP method) ### Endpoint (Not applicable to this Rust trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (Not applicable) ### Response #### Success Response (Result) Returns `Ok(T)` on successful conversion. #### Response Example (Not applicable) ``` ```APIDOC ## try_from(value: U) ### Description Performs the conversion from `U` to `T`. ### Method (Associated function of the `TryFrom` trait) ### Endpoint (Not applicable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let value_u: SomeU = ...; let result_t: Result = SomeT::try_from(value_u); ``` ### Response #### Success Response (Result>::Error>) Returns `Ok(T)` if the conversion is successful, otherwise returns `Err(>::Error)`. #### Response Example ```json // Success { "Ok": "converted_value_of_type_T" } // Error { "Err": "error_details" } ``` ``` -------------------------------- ### DEFLATE Compression Ratio Example (Larger Data) Source: https://docs.rs/pixo/latest/pixo/guides/deflate/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the significant savings of DEFLATE on larger inputs with more repetition, contrasting the original size with the compressed size after one match reference replaces a long sequence. ```text Input: "ABRACADABRA ABRACADABRA ABRACADABRA" (35 bytes) LZ77: "ABRACADABRA [copy 12 back, length 24]" = 11 literals + 1 match covering 24 bytes! Now one match reference (13 bits) replaces 24 bytes (192 bits). Savings: 179 bits on just one match! ``` -------------------------------- ### Rust: PngOptions presets for encoding speed/compression Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptions Provides static methods on PngOptions for creating preset configurations: `fast` (prioritizes speed), `balanced` (tradeoff between speed and compression), and `max` (maximum compression). These presets configure compression level, filter strategy, and optimization flags. ```rust pub fn fast(width: u32, height: u32) -> Self pub fn balanced(width: u32, height: u32) -> Self pub fn max(width: u32, height: u32) -> Self ``` -------------------------------- ### Paeth Predictor Example: Smooth Gradient Source: https://docs.rs/pixo/latest/pixo/guides/png_encoding/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how the Paeth predictor works effectively on a smooth gradient. The example shows the calculation of the ideal prediction and how it accurately predicts the next pixel's value in a diagonal gradient scenario. ```text C=100 | B=110 ------+------ A=110 | X=120 p = 110 + 110 - 100 = 120 ← exactly right! ``` -------------------------------- ### Rust Visibility Modifiers Example Source: https://docs.rs/pixo/latest/pixo/guides/introduction_to_rust/index Demonstrates different visibility levels in Rust: public, crate-internal, parent module, and private. The example shows how `pub` and `pub(crate)` are used within an `impl` block. ```rust // From src/color.rs impl ColorType { // Public: anyone can call this #[inline] pub const fn bytes_per_pixel(self) -> usize { match self { ColorType::Gray => 1, ColorType::GrayAlpha => 2, ColorType::Rgb => 3, ColorType::Rgba => 4, } } // Crate-internal: only our code can use this #[inline] pub(crate) const fn png_color_type(self) -> u8 { // ... } } ``` -------------------------------- ### Rust Runtime Feature Detection Example Source: https://docs.rs/pixo/latest/pixo/guides/introduction_to_rust/index Demonstrates runtime feature detection for x86 architectures using the `is_x86_feature_detected!` macro. This allows for dynamic selection of optimized code paths based on available CPU features. ```rust if is_x86_feature_detected!("avx2") { // Use AVX2 implementation } ``` -------------------------------- ### DEFLATE Compression Ratio Calculation Example Source: https://docs.rs/pixo/latest/pixo/guides/deflate/index_search= Calculates the final compressed size in bits for the 'ABRACADABRA' example, comparing it to the original size to determine the compression ratio. This shows the impact of DEFLATE on a small dataset. ```text Original: 11 bytes = 88 bits Compressed: Block header: 3 bits 7 literals × 8: 56 bits Length code: 7 bits Distance code: 6 bits End-of-block: 7 bits ───────────────────────── Total: 79 bits = 10 bytes (rounded up) Compression ratio: 88 → 79 bits = 10% savings ``` -------------------------------- ### JPEG Quantization Formula and Example Source: https://docs.rs/pixo/latest/pixo/guides/quantization/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the core concept of JPEG quantization, where DCT coefficients are divided by quantization values, leading to information loss. It includes a simple mathematical example showing the irreversible nature of this process. ```plaintext Quantized[i] = round(DCT[i] / Q[i]) DCT coefficient: 47 Quantization value: 10 Quantized result: round(47/10) = round(4.7) = 5 During decoding: Reconstructed: 5 × 10 = 50 Error: |47 - 50| = 3 ``` -------------------------------- ### Initialize and Configure PngOptionsBuilder in Rust Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptionsBuilder Demonstrates creating a PngOptionsBuilder and fluently setting various configuration options for PNG encoding. This builder allows customization of color type, compression, filtering, and specific optimizations like alpha handling and palette reduction. ```rust use pixo::png::{PngOptions, ColorType, FilterStrategy, QuantizationOptions, QuantizationMode}; let options: PngOptions = PngOptions::builder(800, 600) .color_type(ColorType::Rgba) .compression_level(6) .filter_strategy(FilterStrategy::Adaptive) .optimize_alpha(true) .reduce_color_type(false) .strip_metadata(true) .reduce_palette(true) .verbose_filter_log(false) .optimal_compression(true) .quantization(QuantizationOptions::default()) .quantization_mode(QuantizationMode::Fast) .lossy(true) .quantization_max_colors(256) .quantization_dithering(true) .preset(5) .build(); // PngOptions::builder returns a PngOptionsBuilder. // Methods like color_type, compression_level, etc., return `Self` (PngOptionsBuilder). // The final build() method returns the PngOptions struct. ``` -------------------------------- ### JPEG Dequantization Calculation Example Source: https://docs.rs/pixo/latest/pixo/guides/decoding/index_search= This demonstrates the dequantization step in JPEG decoding. Quantized DCT coefficients are multiplied by their corresponding values from the quantization table to approximate the original DCT coefficients. This step is lossy, as information was lost during the initial quantization by rounding. ```plaintext Quantized: [60, -2, 1, 0, 0, ...] Quantization table: [16, 11, 10, ...] Dequantized: 60 × 16 = 960 -2 × 11 = -22 1 × 10 = 10 0 × 16 = 0 ... ``` -------------------------------- ### Balanced PNG Preset Configuration (Rust) Source: https://docs.rs/pixo/latest/pixo/guides/png_encoding/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes PngOptions using the `balanced()` preset. This preset is suitable for general use and web assets, offering a moderate compression level (6) and the Adaptive filter strategy, along with several lossless optimizations. ```rust PngOptions::balanced() ``` -------------------------------- ### JPEG Marker Segments Identification Source: https://docs.rs/pixo/latest/pixo/guides/decoding/index_search= This lists common marker segments found in JPEG files, indicated by a 0xFF byte followed by a marker type. These markers signal the start of different data sections such as image start (SOI), quantization tables (DQT), frame headers (SOF0), Huffman tables (DHT), and scan data (SOS). ```plaintext FFD8 SOI (Start of Image) FFE0 xxxx APP0 (JFIF metadata) FFDB xxxx DQT (Quantization tables) FFC0 xxxx SOF0 (Frame header: dimensions, components) FFC4 xxxx DHT (Huffman tables) FFDA xxxx SOS (Start of Scan, followed by entropy-coded data) FFD9 EOI (End of Image) ``` -------------------------------- ### Implement Default for CostModel Source: https://docs.rs/pixo/latest/pixo/compress/lz77/struct.CostModel Allows a CostModel to be created with its default value. This is often a sensible starting point or a fallback mechanism. ```Rust impl Default for CostModel { fn default() -> Self { /* ... */ } } ``` -------------------------------- ### Maximum PNG Preset Configuration (Rust) Source: https://docs.rs/pixo/latest/pixo/guides/png_encoding/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes PngOptions using the `max()` preset. This preset is designed for final distribution where every byte counts, employing the highest compression level (9) and advanced DEFLATE techniques with the MinSum filter strategy. ```rust PngOptions::max() ``` -------------------------------- ### Get Bytes Per Pixel Source: https://docs.rs/pixo/latest/pixo/wasm/fn.bytes_per_pixel_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the number of bytes per pixel for a given color type. This function is available only when the 'wasm' feature is enabled. ```APIDOC ## GET /wasm/bytes_per_pixel ### Description Get the number of bytes per pixel for a color type. ### Method GET ### Endpoint `/wasm/bytes_per_pixel` ### Parameters #### Query Parameters - **color_type** (u8) - Required - The color type identifier. * 0 (Gray) = 1 byte * 1 (GrayAlpha) = 2 bytes * 2 (Rgb) = 3 bytes * 3 (Rgba) = 4 bytes ### Request Example ```json { "color_type": 2 } ``` ### Response #### Success Response (200) - **bytes** (u8) - The number of bytes per pixel for the given color type. #### Response Example ```json { "bytes": 3 } ``` #### Error Response (400) - **error** (string) - A message indicating an invalid color type was provided. #### Error Example ```json { "error": "Invalid color type provided" } ``` ``` -------------------------------- ### Rust JpegOptionsBuilder Initialization Source: https://docs.rs/pixo/latest/pixo/jpeg/struct.JpegOptionsBuilder_search=std%3A%3Avec Creates a new instance of JpegOptionsBuilder with the specified image width and height. This is the starting point for configuring JPEG options. ```rust pub fn new(width: u32, height: u32) -> Self ``` -------------------------------- ### Rust Result map_or_else() Example Source: https://docs.rs/pixo/latest/pixo/error/type.Result Demonstrates `map_or_else()`, similar to `map_or()`, but the default value is provided by a lazily evaluated closure. This is useful for avoiding unnecessary computation. ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### Rust: Create PngOptions with lossless option Source: https://docs.rs/pixo/latest/pixo/png/struct.PngOptions Enables creating PngOptions from a preset while also controlling whether lossless compression is enforced. When `lossless` is false, auto-quantization can be enabled for potential size reduction through lossy compression. ```rust pub fn from_preset_with_lossless( width: u32, height: u32, preset: u8, lossless: bool, ) -> Self ``` -------------------------------- ### Rust: Create ResizeOptionsBuilder Instance Source: https://docs.rs/pixo/latest/pixo/resize/struct.ResizeOptionsBuilder_search=std%3A%3Avec Initializes a new ResizeOptionsBuilder. This is the starting point for configuring resize operations, requiring the source image dimensions (width and height) to be provided upon creation. ```rust pub fn new(src_width: u32, src_height: u32) -> Self ``` -------------------------------- ### Rust Result as_ref() Example Source: https://docs.rs/pixo/latest/pixo/error/type.Result Shows the `as_ref()` method, which converts a reference to a Result into a Result of references. This allows inspecting the contents of a Result without consuming it. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Rust Result map_or() Example Source: https://docs.rs/pixo/latest/pixo/error/type.Result Illustrates `map_or()`, which applies a function to an Ok value or returns a default value if the Result is Err. The default value is eagerly evaluated. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Rust: Build ResizeOptions from Builder Source: https://docs.rs/pixo/latest/pixo/resize/struct.ResizeOptionsBuilder Shows the final step of using the ResizeOptionsBuilder to construct a ResizeOptions object. The `build` method consumes the builder and returns the configured options. ```rust use pixo::resize::{ResizeOptions, ResizeOptionsBuilder}; // Assume builder is already configured with desired options... let builder = ResizeOptionsBuilder::new(100, 100).dst(50, 50); let options: ResizeOptions = builder.build(); // The 'options' variable now holds the configured resize settings. ```