module

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

average_color(blurhash : String) : CrImage::Color::RGBA

Returns the average color from a blurhash without full decoding.

This is useful when you only need the dominant color.

Source
components(blurhash : String) : Tuple(Int32, Int32)

Returns the number of components encoded in a blurhash.

Source
decode(blurhash : String, width : Int32, height : Int32, punch : Float64 = 1.0) : CrImage::RGBA

Decodes a blurhash string to an image.

Parameters:

  • blurhash : Blurhash string to decode
  • width : Output image width
  • height : Output image height
  • punch : Contrast adjustment (default: 1.0)

Returns: RGBA image

Example:

img = CrImage::Util::Blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 32, 32)
Source
encode(image : CrImage::Image, x_components : Int32 = 4, y_components : Int32 = 3) : String

Encodes an image to a blurhash string.

Parameters:

  • image : Source image to encode
  • x_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)
Source
valid?(blurhash : String) : Bool

Validates a blurhash string.

Source

Nested types