BlurHash.decode constructor

BlurHash.decode(
  1. String blurHash,
  2. {double punch = 1.0}
)

Decode a BlurHash String to a BlurHash object.

The punch parameter adjusts the contrast on the decoded image. Values less than 1 will make the effect more subtle, larger values will make the effect stronger. This is a design parameter to adjust the look.

Throws BlurHashDecodeException when an invalid BlurHash is encountered.

Implementation

factory BlurHash.decode(String blurHash, {double punch = 1.0}) {
  if (blurHash.length < 6) {
    throw BlurHashDecodeException(
      "BlurHash must not be null or '< 6' characters long.",
    );
  }
  final sizeFlag = decode83(blurHash, 0, 1);
  final numCompX = (sizeFlag % 9) + 1;
  final numCompY = (sizeFlag ~/ 9) + 1;

  if (blurHash.length != 4 + 2 * numCompX * numCompY) {
    throw BlurHashDecodeException(
      'Invalid number of components in BlurHash.',
    );
  }

  final maxAcEnc = decode83(blurHash, 1, 2);
  final maxAc = (maxAcEnc + 1) / 166.0;
  final components = List.generate(
    numCompY,
    (i) => List<ColorTriplet>.filled(numCompX, ColorTriplet(0, 0, 0)),
  );

  for (var j = 0; j < numCompY; j++) {
    for (var i = 0; i < numCompX; i++) {
      if (i == 0 && j == 0) {
        final value = decodeDc(decode83(blurHash, 2, 6));
        components[j][i] = value;
      } else {
        final index = i + j * numCompX;
        final value = decodeAc(
          decode83(blurHash, 4 + index * 2, (4 + index * 2) + 2),
          maxAc,
        );
        components[j][i] = value;
      }
    }
  }

  return BlurHash._(blurHash, _multiplyPunch(components, punch));
}