### Java API Source: https://context7.com/evanw/thumbhash/llms.txt Example for Java demonstrating how to encode RGBA data to a ThumbHash. ```APIDOC ## ThumbHash.rgbaToThumbHash - Encode Image to ThumbHash ### Description Static method to encode RGBA byte array to a ThumbHash. Input dimensions must be ≤100 pixels. ### Method `ThumbHash.rgbaToThumbHash(int width, int height, byte[] rgba)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.madebyevan.thumbhash.ThumbHash; import java.util.Base64; public class EncodeExample { public static void main(String[] args) { // Create sample RGBA data (10x10 image) int width = 10; int height = 10; byte[] rgba = new byte[width * height * 4]; for (int i = 0; i < width * height; i++) { int offset = i * 4; rgba[offset] = (byte) ((i * 25) % 256); // R rgba[offset + 1] = (byte) ((i * 15) % 256); // G rgba[offset + 2] = (byte) ((i * 35) % 256); // B rgba[offset + 3] = (byte) 255; // A } // Encode to ThumbHash byte[] hash = ThumbHash.rgbaToThumbHash(width, height, rgba); // Convert to Base64 for storage String base64Hash = Base64.getEncoder().encodeToString(hash); System.out.println("ThumbHash (base64): " + base64Hash); System.out.println("Hash size: " + hash.length + " bytes"); } } ``` ### Response #### Success Response (200) Returns a `byte[]` array representing the ThumbHash. #### Response Example `byte[]` containing ThumbHash bytes. ``` -------------------------------- ### Swift API Source: https://context7.com/evanw/thumbhash/llms.txt Examples for Swift, covering image encoding, decoding, platform-specific image handling, and metadata extraction. ```APIDOC ## rgbaToThumbHash - Encode Image to ThumbHash ### Description Encodes RGBA image data to a ThumbHash. Works with raw `Data` containing pixel values. ### Method `rgbaToThumbHash` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Foundation // Create sample RGBA data for a 10x10 image let width = 10 let height = 10 var rgba = Data(count: width * height * 4) for i in 0..<(width * height) { let offset = i * 4 rgba[offset] = UInt8(i * 2 % 256) // R rgba[offset + 1] = UInt8(i * 3 % 256) // G rgba[offset + 2] = UInt8(i * 5 % 256) // B rgba[offset + 3] = 255 // A (fully opaque) } // Encode to ThumbHash let hash = rgbaToThumbHash(w: width, h: height, rgba: rgba) print("ThumbHash bytes: \(hash.count)") // Output: ThumbHash bytes: ~13-25 ``` ### Response #### Success Response (200) Returns `Data` representing the ThumbHash. #### Response Example `Data` object containing ThumbHash bytes. ``` ```APIDOC ## thumbHashToRGBA - Decode ThumbHash to Image Data ### Description Decodes a ThumbHash back to RGBA pixel data with computed dimensions. ### Method `thumbHashToRGBA` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Foundation // Assume we have a ThumbHash from encoding let originalHash: Data = /* previously encoded hash */ // Decode to RGBA let (w, h, rgba) = thumbHashToRGBA(hash: originalHash) print("Placeholder size: \(w)x\(h)") print("Total pixels: \(rgba.count / 4)") // Output: Placeholder size: 32x32 (or similar based on aspect ratio) ``` ### Response #### Success Response (200) A tuple containing the width, height, and RGBA pixel data. #### Response Example `(width: Int, height: Int, rgba: Data)` ``` ```APIDOC ## imageToThumbHash / thumbHashToImage - High-Level Image Conversion (macOS/iOS) ### Description Platform-specific convenience functions for working directly with NSImage (macOS) or UIImage (iOS). ### Method `imageToThumbHash`, `thumbHashToImage` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift #if os(macOS) import Cocoa // Load an image and convert to ThumbHash let image = NSImage(contentsOfFile: "photo.jpg")! let hash = imageToThumbHash(image: image) // Convert ThumbHash back to displayable image let placeholder = thumbHashToImage(hash: hash) // Use in your UI imagingView.image = placeholder #endif #if os(iOS) import UIKit // Load an image and convert to ThumbHash let image = UIImage(named: "photo")! let hash = imageToThumbHash(image: image) // Convert ThumbHash back to displayable image let placeholder = thumbHashToImage(hash: hash) // Use in your UI imagingView.image = placeholder #endif ``` ### Response #### Success Response (200) `imageToThumbHash` returns `Data` (ThumbHash). `thumbHashToImage` returns `NSImage` (macOS) or `UIImage` (iOS). #### Response Example ThumbHash `Data` or platform-specific `Image` object. ``` ```APIDOC ## thumbHashToAverageRGBA / thumbHashToApproximateAspectRatio - Metadata Extraction ### Description Extract color and dimension metadata from a ThumbHash without full decoding. ### Method `thumbHashToAverageRGBA`, `thumbHashToApproximateAspectRatio` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Foundation let hash: Data = /* ThumbHash data */ // Get average color (values 0.0-1.0) let (r, g, b, a) = thumbHashToAverageRGBA(hash: hash) print("Average RGBA: \(r), \(g), \(b), \(a)") // Get aspect ratio for layout let aspectRatio = thumbHashToApproximateAspectRatio(hash: hash) print("Aspect ratio: \(aspectRatio)") // Calculate container size let containerWidth: CGFloat = 300 let containerHeight = containerWidth / CGFloat(aspectRatio) ``` ### Response #### Success Response (200) `thumbHashToAverageRGBA` returns a tuple of four `CGFloat` values (R, G, B, A). `thumbHashToApproximateAspectRatio` returns a `CGFloat` representing the aspect ratio. #### Response Example Average RGBA: `(0.5, 0.5, 0.5, 1.0)` Aspect ratio: `1.5` ``` -------------------------------- ### Rust API Source: https://context7.com/evanw/thumbhash/llms.txt Examples of using the ThumbHash library in Rust for encoding and metadata extraction. ```APIDOC ## thumb_hash_to_approximate_aspect_ratio - Extract Aspect Ratio ### Description Extracts the approximate aspect ratio from a ThumbHash for layout calculations. ### Method `thumb_hash_to_approximate_aspect_ratio` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use thumbhash::{rgba_to_thumb_hash, thumb_hash_to_approximate_aspect_ratio}; fn main() -> Result<(), ()> { // Create a wide landscape image (80x30) let width = 80; let height = 30; let rgba: Vec = vec![128; width * height * 4]; let hash = rgba_to_thumb_hash(width, height, &rgba); let ratio = thumb_hash_to_approximate_aspect_ratio(&hash)?; println!("Original aspect ratio: {:.2}", width as f32 / height as f32); println!("Encoded aspect ratio: {:.2}", ratio); // Output: Original aspect ratio: 2.67 // Output: Encoded aspect ratio: 2.33 (approximate) Ok(()) } ``` ### Response #### Success Response (200) Returns the approximate aspect ratio as a floating-point number. #### Response Example `2.33` ``` -------------------------------- ### Encode Image to ThumbHash (Java) Source: https://context7.com/evanw/thumbhash/llms.txt This Java code snippet demonstrates encoding RGBA image data into a ThumbHash using the static `rgbaToThumbHash` method. It takes image dimensions and an RGBA byte array as input, returning the ThumbHash as a byte array. The example also shows how to convert the resulting hash to a Base64 string for easier storage or transmission. Input dimensions must be less than or equal to 100 pixels. ```java import com.madebyevan.thumbhash.ThumbHash; import java.util.Base64; public class EncodeExample { public static void main(String[] args) { // Create sample RGBA data (10x10 image) int width = 10; int height = 10; byte[] rgba = new byte[width * height * 4]; for (int i = 0; i < width * height; i++) { int offset = i * 4; rgba[offset] = (byte) ((i * 25) % 256); // R rgba[offset + 1] = (byte) ((i * 15) % 256); // G rgba[offset + 2] = (byte) ((i * 35) % 256); // B rgba[offset + 3] = (byte) 255; // A } // Encode to ThumbHash byte[] hash = ThumbHash.rgbaToThumbHash(width, height, rgba); // Convert to Base64 for storage String base64Hash = Base64.getEncoder().encodeToString(hash); System.out.println("ThumbHash (base64): " + base64Hash); System.out.println("Hash size: " + hash.length + " bytes"); } } ``` -------------------------------- ### Generate ThumbHash and Placeholder in Browser Source: https://github.com/evanw/thumbhash/blob/main/examples/browser/index.html This snippet demonstrates how to load an image, scale it, convert it to a ThumbHash using the rgbaToThumbHash function, and display it as a background placeholder before the full image loads. ```javascript import * as ThumbHash from '../../js/thumbhash.js'; const originalURL = '../flower.jpg'; const image = new Image(); image.src = originalURL; await new Promise(resolve => image.onload = resolve); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); const scale = 100 / Math.max(image.width, image.height); canvas.width = Math.round(image.width * scale); canvas.height = Math.round(image.height * scale); context.drawImage(image, 0, 0, canvas.width, canvas.height); const pixels = context.getImageData(0, 0, canvas.width, canvas.height); const binaryThumbHash = ThumbHash.rgbaToThumbHash(pixels.width, pixels.height, pixels.data); const placeholderURL = ThumbHash.thumbHashToDataURL(binaryThumbHash); const demo = document.getElementById('demo'); demo.style.background = `center / cover url(${placeholderURL})`; setTimeout(() => demo.src = originalURL, 500); ``` -------------------------------- ### Metadata Extraction from ThumbHash (Swift) Source: https://context7.com/evanw/thumbhash/llms.txt This Swift code snippet demonstrates extracting metadata from a ThumbHash without full decoding. It shows how to retrieve the average RGBA color components and the approximate aspect ratio of the original image. This is useful for tasks like generating placeholders or performing layout calculations. ```swift import Foundation let hash: Data = /* ThumbHash data */ // Get average color (values 0.0-1.0) let (r, g, b, a) = thumbHashToAverageRGBA(hash: hash) print("Average RGBA: \(r), \(g), \(b), \(a)") // Get aspect ratio for layout let aspectRatio = thumbHashToApproximateAspectRatio(hash: hash) print("Aspect ratio: \(aspectRatio)") // Calculate container size let containerWidth: CGFloat = 300 let containerHeight = containerWidth / CGFloat(aspectRatio) ``` -------------------------------- ### High-Level Image Conversion (Swift - macOS/iOS) Source: https://context7.com/evanw/thumbhash/llms.txt These Swift code snippets provide platform-specific convenience functions for converting between `NSImage` (macOS) or `UIImage` (iOS) and ThumbHashes. They simplify the process of loading images, encoding them to ThumbHashes, and decoding ThumbHashes back into displayable image objects for UI elements. ```swift #if os(macOS) import Cocoa // Load an image and convert to ThumbHash let image = NSImage(contentsOfFile: "photo.jpg")! let hash = imageToThumbHash(image: image) // Convert ThumbHash back to displayable image let placeholder = thumbHashToImage(hash: hash) // Use in your UI imagView.image = placeholder #endif #if os(iOS) import UIKit // Load an image and convert to ThumbHash let image = UIImage(named: "photo")! let hash = imageToThumbHash(image: image) // Convert ThumbHash back to displayable image let placeholder = thumbHashToImage(hash: hash) // Use in your UI imagView.image = placeholder #endif ``` -------------------------------- ### Encode RGBA Image to ThumbHash (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt Encodes an RGBA image (100x100 pixels or smaller) into a ThumbHash binary representation using the 'sharp' library for image processing and 'thumbhash' for encoding. The output is a Uint8Array, typically around 25 bytes, which can be converted to base64 for storage or transmission. Input RGB values should not be premultiplied by alpha. ```javascript import * as ThumbHash from 'thumbhash' import sharp from 'sharp' // Load and resize image to fit within 100x100 const image = sharp('photo.jpg').resize(100, 100, { fit: 'inside' }) const { data, info } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true }) // Encode to ThumbHash (returns Uint8Array, typically ~25 bytes) const binaryThumbHash = ThumbHash.rgbaToThumbHash(info.width, info.height, data) // Convert to base64 for storage/transmission const base64ThumbHash = Buffer.from(binaryThumbHash).toString('base64') console.log('ThumbHash (base64):', base64ThumbHash) // Output: "YTkGJwaRhWWI94lDhof/h4aIh4k=" (example) ``` -------------------------------- ### Decode ThumbHash to RGBA (Swift) Source: https://context7.com/evanw/thumbhash/llms.txt This Swift code snippet demonstrates decoding a ThumbHash back into RGBA pixel data. It takes a ThumbHash (`Data`) as input and returns the decoded width, height, and RGBA data. This is useful for rendering a placeholder image from a ThumbHash. ```swift import Foundation // Assume we have a ThumbHash from encoding let originalHash: Data = /* previously encoded hash */ // Decode to RGBA let (w, h, rgba) = thumbHashToRGBA(hash: originalHash) print("Placeholder size: \(w)x\(h)") print("Total pixels: \(rgba.count / 4)") // Output: Placeholder size: 32x32 (or similar based on aspect ratio) ``` -------------------------------- ### Convert ThumbHash Binary to Base64 Source: https://github.com/evanw/thumbhash/blob/main/examples/browser/index.html Utility functions to convert binary ThumbHash data to a base64 string for easier storage and back to binary for processing. ```javascript const binaryToBase64 = binary => btoa(String.fromCharCode(...binary)); const base64ToBinary = base64 => new Uint8Array(atob(base64).split('').map(x => x.charCodeAt(0))); const thumbHashToBase64 = binaryToBase64(binaryThumbHash); const thumbHashFromBase64 = base64ToBinary(thumbHashToBase64); ``` -------------------------------- ### Encode Image to ThumbHash (Swift) Source: https://context7.com/evanw/thumbhash/llms.txt This Swift code snippet shows how to encode raw RGBA image data into a ThumbHash. It takes image width, height, and the RGBA data as input, returning the ThumbHash as a `Data` object. This is useful for creating compact image representations. ```swift import Foundation // Create sample RGBA data for a 10x10 image let width = 10 let height = 10 var rgba = Data(count: width * height * 4) for i in 0..<(width * height) { let offset = i * 4 rgba[offset] = UInt8(i * 2 % 256) // R rgba[offset + 1] = UInt8(i * 3 % 256) // G rgba[offset + 2] = UInt8(i * 5 % 256) // B rgba[offset + 3] = 255 // A (fully opaque) } // Encode to ThumbHash let hash = rgbaToThumbHash(w: width, h: height, rgba: rgba) print("ThumbHash bytes: \(hash.count)") // Output: ThumbHash bytes: ~13-25 ``` -------------------------------- ### ThumbHash.thumbHashToApproximateAspectRatio Source: https://context7.com/evanw/thumbhash/llms.txt Calculates the approximate aspect ratio of the original image from the ThumbHash. ```APIDOC ## ThumbHash.thumbHashToApproximateAspectRatio ### Description Returns the approximate width/height ratio, useful for calculating layout dimensions before the full image loads. ### Method Static Method ### Endpoint ThumbHash.thumbHashToApproximateAspectRatio(byte[] hash) ### Parameters #### Request Body - **hash** (byte[]) - Required - The binary ThumbHash data. ### Response #### Success Response (200) - **aspectRatio** (float) - The calculated width/height ratio. #### Response Example 1.333 ``` -------------------------------- ### Decode ThumbHash to RGBA Image Data (Rust) Source: https://context7.com/evanw/thumbhash/llms.txt Decodes a ThumbHash byte vector back into RGBA pixel data. Returns the dimensions and the pixel buffer, or an error if the hash is invalid. ```rust use thumbhash::{rgba_to_thumb_hash, thumb_hash_to_rgba}; fn main() -> Result<(), ()> { let original_width = 50; let original_height = 30; let rgba: Vec = (0..original_width * original_height * 4) .map(|i| ((i * 7) % 256) as u8) .collect(); let hash = rgba_to_thumb_hash(original_width, original_height, &rgba); let (w, h, decoded_rgba) = thumb_hash_to_rgba(&hash)?; println!("Decoded placeholder: {}x{}", w, h); Ok(()) } ``` -------------------------------- ### Encode RGBA Image to ThumbHash (Rust) Source: https://context7.com/evanw/thumbhash/llms.txt Encodes an RGBA image buffer into a ThumbHash byte vector. The input image should be 100x100 pixels or smaller for optimal results. ```rust use thumbhash::rgba_to_thumb_hash; fn main() { let width = 4; let height = 4; let mut rgba = Vec::with_capacity(width * height * 4); for y in 0..height { for x in 0..width { let r = (x * 255 / (width - 1)) as u8; let g = (y * 255 / (height - 1)) as u8; let b = 128u8; let a = 255u8; rgba.extend_from_slice(&[r, g, b, a]); } } let hash = rgba_to_thumb_hash(width, height, &rgba); println!("ThumbHash: {:?}", hash); } ``` -------------------------------- ### Extract Aspect Ratio from ThumbHash (Java) Source: https://context7.com/evanw/thumbhash/llms.txt Calculates and returns the approximate aspect ratio (width / height) of the image represented by a ThumbHash. This is valuable for pre-allocating space for images in layouts, preventing layout shifts. Requires the ThumbHash library and Base64 decoding. ```java import com.madebyevan.thumbhash.ThumbHash; import java.util.Base64; public class AspectRatioExample { public static void main(String[] args) { byte[] hash = Base64.getDecoder().decode("YTkGJwaRhWWI94lDhof/h4aIh4k="); // Get aspect ratio float aspectRatio = ThumbHash.thumbHashToApproximateAspectRatio(hash); System.out.println("Aspect ratio: " + aspectRatio); // Calculate ImageView dimensions int targetWidth = 400; int targetHeight = Math.round(targetWidth / aspectRatio); System.out.println("Recommended size: " + targetWidth + "x" + targetHeight); } } ``` -------------------------------- ### Convert RGBA Pixel Data to PNG Data URL (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt Encodes raw RGBA pixel data into a base64-encoded PNG data URL. This utility is optimized for performance and is suitable for generating small image placeholders. ```javascript import * as ThumbHash from 'thumbhash' const width = 2 const height = 2 const rgba = new Uint8Array([ 255, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 255, 255, 0, 0, 255 ]) const dataURL = ThumbHash.rgbaToDataURL(width, height, rgba) console.log('PNG Data URL:', dataURL.substring(0, 50) + '...') ``` -------------------------------- ### Extract Average Color from ThumbHash (Rust) Source: https://context7.com/evanw/thumbhash/llms.txt Retrieves the average RGBA color from a ThumbHash. The returned color components are normalized in the range 0.0 to 1.0. ```rust use thumbhash::{rgba_to_thumb_hash, thumb_hash_to_average_rgba}; fn main() -> Result<(), ()> { let width = 10; let height = 10; let rgba: Vec = (0..width * height) .flat_map(|_| vec![200u8, 50, 50, 255]) .collect(); let hash = rgba_to_thumb_hash(width, height, &rgba); let (r, g, b, a) = thumb_hash_to_average_rgba(&hash)?; println!("Average color: R={:.2}, G={:.2}, B={:.2}, A={:.2}", r, g, b, a); Ok(()) } ``` -------------------------------- ### Extract Aspect Ratio from ThumbHash (Rust) Source: https://context7.com/evanw/thumbhash/llms.txt This Rust code snippet demonstrates how to extract the approximate aspect ratio from a ThumbHash. It takes a ThumbHash as input and returns a floating-point number representing the aspect ratio, useful for layout calculations. This function is part of the core ThumbHash library. ```rust use thumbhash::{rgba_to_thumb_hash, thumb_hash_to_approximate_aspect_ratio}; fn main() -> Result<(), ()> { // Create a wide landscape image (80x30) let width = 80; let height = 30; let rgba: Vec = vec![128; width * height * 4]; let hash = rgba_to_thumb_hash(width, height, &rgba); let ratio = thumb_hash_to_approximate_aspect_ratio(&hash)?; println!("Original aspect ratio: {:.2}", width as f32 / height as f32); println!("Encoded aspect ratio: {:.2}", ratio); // Output: Original aspect ratio: 2.67 // Output: Encoded aspect ratio: 2.33 (approximate) Ok(()) } ``` -------------------------------- ### Decode ThumbHash to PNG Data URL (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt A convenience function that decodes a ThumbHash directly into a PNG data URL. This URL is suitable for immediate use in HTML `` `src` attributes or as CSS background images, making it the most common method for client-side ThumbHash integration. It simplifies the process of displaying placeholders while full images load. ```javascript import * as ThumbHash from 'thumbhash' // Convert base64 ThumbHash to binary const base64ThumbHash = "YTkGJwaRhWWI94lDhof/h4aIh4k=" const binaryThumbHash = new Uint8Array(atob(base64ThumbHash).split('').map(x => x.charCodeAt(0))) // Generate PNG data URL for immediate display const placeholderURL = ThumbHash.thumbHashToDataURL(binaryThumbHash) // Use in HTML const img = document.createElement('img') img.src = placeholderURL img.style.width = '200px' img.style.height = '267px' document.body.appendChild(img) // Or use as CSS background while loading full image img.style.background = `center / cover url(${placeholderURL})` img.onload = () => img.src = 'full-resolution-photo.jpg' ``` -------------------------------- ### Extract Average Color from ThumbHash (Java) Source: https://context7.com/evanw/thumbhash/llms.txt Extracts the average color of the image represented by a ThumbHash. It returns an RGBA object with normalized color values (0.0 to 1.0). This is useful for creating solid color placeholders or dominant color swatches. Requires the ThumbHash library and Base64 decoding. ```java import com.madebyevan.thumbhash.ThumbHash; import java.util.Base64; public class ColorExample { public static void main(String[] args) { byte[] hash = Base64.getDecoder().decode("YTkGJwaRhWWI94lDhof/h4aIh4k="); // Extract average color ThumbHash.RGBA avgColor = ThumbHash.thumbHashToAverageRGBA(hash); System.out.printf("Average color: R=%.2f, G=%.2f, B=%.2f, A=%.2f%n", avgColor.r, avgColor.g, avgColor.b, avgColor.a); // Convert to Android Color int int colorInt = (Math.round(avgColor.a * 255) << 24) | (Math.round(avgColor.r * 255) << 16) | (Math.round(avgColor.g * 255) << 8) | Math.round(avgColor.b * 255); System.out.println("Android color int: 0x" + Integer.toHexString(colorInt)); } } ``` -------------------------------- ### Extract Aspect Ratio from ThumbHash (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt Calculates the approximate aspect ratio of an image directly from its ThumbHash string without full decoding. This is useful for reserving layout space to prevent cumulative layout shifts. ```javascript import * as ThumbHash from 'thumbhash' const base64ThumbHash = "YTkGJwaRhWWI94lDhof/h4aIh4k=" const binaryThumbHash = new Uint8Array(atob(base64ThumbHash).split('').map(x => x.charCodeAt(0))) const aspectRatio = ThumbHash.thumbHashToApproximateAspectRatio(binaryThumbHash) console.log('Aspect ratio:', aspectRatio) const containerWidth = 300 const containerHeight = containerWidth / aspectRatio const container = document.createElement('div') container.style.width = `${containerWidth}px` container.style.height = `${containerHeight}px` ``` -------------------------------- ### Decode ThumbHash to RGBA Image (Java) Source: https://context7.com/evanw/thumbhash/llms.txt Decodes a ThumbHash byte array into an Image object containing width, height, and RGBA pixel data. This is useful for rendering image placeholders. It requires the ThumbHash library and standard Java utilities for Base64 decoding. ```java import com.madebyevan.thumbhash.ThumbHash; import java.util.Base64; public class DecodeExample { public static void main(String[] args) { // Decode from Base64-stored ThumbHash String base64Hash = "YTkGJwaRhWWI94lDhof/h4aIh4k="; byte[] hash = Base64.getDecoder().decode(base64Hash); // Decode to RGBA image ThumbHash.Image image = ThumbHash.thumbHashToRGBA(hash); System.out.println("Placeholder dimensions: " + image.width + "x" + image.height); System.out.println("Pixel data length: " + image.rgba.length); // Access individual pixels int x = 0, y = 0; int offset = (y * image.width + x) * 4; int r = image.rgba[offset] & 0xFF; int g = image.rgba[offset + 1] & 0xFF; int b = image.rgba[offset + 2] & 0xFF; int a = image.rgba[offset + 3] & 0xFF; System.out.println("Pixel (0,0): RGBA(" + r + "," + g + "," + b + "," + a + ")"); } } ``` -------------------------------- ### Extract Average Color from ThumbHash (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt Extracts the average RGBA color from a ThumbHash without performing a full decode. This is useful for setting immediate background colors or creating simple color-based placeholders. The function returns RGBA values normalized to a 0-1 range, which can then be converted to CSS color formats. ```javascript import * as ThumbHash from 'thumbhash' const base64ThumbHash = "YTkGJwaRhWWI94lDhof/h4aIh4k=" const binaryThumbHash = new Uint8Array(atob(base64ThumbHash).split('').map(x => x.charCodeAt(0))) // Extract average color (values range from 0 to 1) const { r, g, b, a } = ThumbHash.thumbHashToAverageRGBA(binaryThumbHash) // Convert to CSS color const cssColor = `rgba(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)}, ${a})` console.log('Average color:', cssColor) // Output: "Average color: rgba(142, 89, 67, 1)" // Use as immediate background color document.body.style.backgroundColor = cssColor ``` -------------------------------- ### Decode ThumbHash to RGBA Image Data (JavaScript) Source: https://context7.com/evanw/thumbhash/llms.txt Decodes a ThumbHash binary representation back into RGBA pixel data. The function automatically determines output dimensions based on the encoded aspect ratio, typically resulting in images around 32 pixels on the longest side. The output includes width, height, and the RGBA pixel data. ```javascript import * as ThumbHash from 'thumbhash' // Decode from base64-stored ThumbHash const base64ThumbHash = "YTkGJwaRhWWI94lDhof/h4aIh4k=" const binaryThumbHash = new Uint8Array(atob(base64ThumbHash).split('').map(x => x.charCodeAt(0))) // Decode to RGBA pixel data const { w, h, rgba } = ThumbHash.thumbHashToRGBA(binaryThumbHash) console.log(`Placeholder dimensions: ${w}x${h}`) console.log(`Pixel data length: ${rgba.length} bytes (${w * h * 4} expected)`) // Output: "Placeholder dimensions: 24x32" // Output: "Pixel data length: 3072 bytes (3072 expected)" ``` -------------------------------- ### ThumbHash.thumbHashToRGBA Source: https://context7.com/evanw/thumbhash/llms.txt Decodes a binary ThumbHash into an image object containing dimensions and raw RGBA pixel data. ```APIDOC ## ThumbHash.thumbHashToRGBA ### Description Decodes a ThumbHash byte array into a ThumbHash.Image object containing width, height, and RGBA pixel data. ### Method Static Method ### Endpoint ThumbHash.thumbHashToRGBA(byte[] hash) ### Parameters #### Request Body - **hash** (byte[]) - Required - The binary ThumbHash data. ### Request Example byte[] hash = Base64.getDecoder().decode("YTkGJwaRhWWI94lDhof/h4aIh4k="); ### Response #### Success Response (200) - **image** (ThumbHash.Image) - Object containing width (int), height (int), and rgba (byte[]) data. #### Response Example { "width": 100, "height": 75, "rgba": [...] } ``` -------------------------------- ### ThumbHash.thumbHashToAverageRGBA Source: https://context7.com/evanw/thumbhash/llms.txt Extracts the dominant average color from a ThumbHash as normalized RGBA values. ```APIDOC ## ThumbHash.thumbHashToAverageRGBA ### Description Returns the average color of the image represented by the ThumbHash, normalized between 0.0 and 1.0. ### Method Static Method ### Endpoint ThumbHash.thumbHashToAverageRGBA(byte[] hash) ### Parameters #### Request Body - **hash** (byte[]) - Required - The binary ThumbHash data. ### Response #### Success Response (200) - **RGBA** (Object) - Contains r, g, b, a (float) values. #### Response Example { "r": 0.5, "g": 0.3, "b": 0.2, "a": 1.0 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.