blurHashPixels function
Decodes hash into width×height RGBA pixels, or null when it is not a
BlurHash.
Null rather than an exception: a document is untrusted input, and a malformed hash inside one should cost the placeholder, not the frame.
Implementation
Uint8List? blurHashPixels(
String hash, {
required int width,
required int height,
double punch = 1,
}) {
if (width <= 0 || height <= 0 || !isBlurHash(hash)) return null;
final sizeFlag = _decode83(hash, 0, 1);
final numX = sizeFlag % 9 + 1;
final numY = sizeFlag ~/ 9 + 1;
final maximumValue = (_decode83(hash, 1, 2) + 1) / 166;
// Every component in linear light: index 0 is the image's average colour
// (stored verbatim), the rest are the detail terms.
final colours = <List<double>>[
_decodeDc(_decode83(hash, 2, 6)),
for (var i = 1; i < numX * numY; i++)
_decodeAc(_decode83(hash, 4 + i * 2, 6 + i * 2), maximumValue * punch),
];
// Cosines depend only on the axis, so they are computed once per row and
// column instead of once per pixel and component — the difference between a
// handful of multiplications per pixel and a few thousand.
final cosX = List<List<double>>.generate(
width,
(x) => List<double>.generate(
numX,
(i) => math.cos(math.pi * x * i / width),
growable: false,
),
growable: false,
);
final cosY = List<List<double>>.generate(
height,
(y) => List<double>.generate(
numY,
(j) => math.cos(math.pi * y * j / height),
growable: false,
),
growable: false,
);
final pixels = Uint8List(width * height * 4);
var offset = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var r = 0.0;
var g = 0.0;
var b = 0.0;
for (var j = 0; j < numY; j++) {
for (var i = 0; i < numX; i++) {
final basis = cosX[x][i] * cosY[y][j];
final colour = colours[i + j * numX];
r += colour[0] * basis;
g += colour[1] * basis;
b += colour[2] * basis;
}
}
pixels[offset++] = _linearTosRgb(r);
pixels[offset++] = _linearTosRgb(g);
pixels[offset++] = _linearTosRgb(b);
pixels[offset++] = 255;
}
}
return pixels;
}