BlurHash.encode constructor

BlurHash.encode(
  1. Image image, {
  2. int numCompX = 4,
  3. int numCompY = 3,
})

Encodes an image to a BlurHash string.

The parameters numCompX and numCompY are the number of components of the BlurHash. Both parameters must be between 1 and 9. Throws a BlurHashEncodeException when numCompX and numCompY are not in the expected range.

Implementation

factory BlurHash.encode(
  Image image, {
  int numCompX = 4,
  int numCompY = 3,
}) {
  if (numCompX < 1 || numCompX > 9 || numCompY < 1 || numCompY > 9) {
    throw BlurHashEncodeException(
      'BlurHash components must be between 1 and 9.',
    );
  }

  final data = image.getBytes();
  final components = List.generate(
    numCompY,
    (i) => List<ColorTriplet>.filled(numCompX, ColorTriplet(0, 0, 0)),
  );

  for (var y = 0; y < numCompY; ++y) {
    for (var x = 0; x < numCompX; ++x) {
      final normalisation = (x == 0 && y == 0) ? 1.0 : 2.0;
      components[y][x] = _multiplyBasisFunction(
        data,
        image.width,
        image.height,
        x,
        y,
        normalisation,
        image.numChannels,
      );
    }
  }

  final hash = _encodeComponents(components);
  return BlurHash._(hash, components);
}