CrImage::Util::Blurhash
Blurhash encoder and decoder for compact image placeholders.
Blurhash is a compact representation of a placeholder for an image. It encodes the image using DCT (Discrete Cosine Transform) and produces a short string that can be used to show a blurred preview while the full image loads.
Example
# Encode an image to blurhash
img = CrImage.read("photo.jpg")
hash = CrImage::Util::Blurhash.encode(img, x_components: 4, y_components: 3)
# => "LKO2?U%2Tw=w]~RBVZRi};RPxuwH"
# Decode blurhash to image
placeholder = CrImage::Util::Blurhash.decode(hash, width: 32, height: 32)
See: https://blurha.sh/
Constants
CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"
Base83 character set used for encoding
CHARSET_LOOKUP = begin
lookup = {} of Char => Int32
CHARSET.each_char_with_index do |c, i| lookup[c] = i end
lookup
end
Lookup table for decoding base83
Class methods
Returns the average color from a blurhash without full decoding.
This is useful when you only need the dominant color.
Returns the number of components encoded in a blurhash.
Decodes a blurhash string to an image.
Parameters:
blurhash: Blurhash string to decodewidth: Output image widthheight: Output image heightpunch: Contrast adjustment (default: 1.0)
Returns: RGBA image
Example:
img = CrImage::Util::Blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 32, 32)
Encodes an image to a blurhash string.
Parameters:
image: Source image to encodex_components: Number of components on X axis (1-9, default: 4)y_components: Number of components on Y axis (1-9, default: 3)
Returns: Blurhash string
Example:
hash = CrImage::Util::Blurhash.encode(img, x_components: 4, y_components: 3)