如何用Flutter像素化图像?

时间:2020-05-28 14:09:53

标签: flutter dart

我在屏幕上显示了NetworkImage,并且想要应用块状像素化效果,有人知道如何解决吗?

有许多模糊或调整对比度/白平衡等的库。但是似乎找不到任何可以帮助我做其他图像效果的东西。

欢呼

1 个答案:

答案 0 :(得分:0)

我没有亲自尝试,但我发现了这个:

https://pub.dev/documentation/image/latest/image/pixelate.html

它只包含以下函数来创建一个像素化的图像:

Image pixelate(Image src, int blockSize,
    {PixelateMode mode = PixelateMode.upperLeft}) {
  if (blockSize <= 1) {
    return src;
  }

  var bs = blockSize - 1;

  switch (mode) {
    case PixelateMode.upperLeft:
      for (var y = 0; y < src.height; y += blockSize) {
        for (var x = 0; x < src.width; x += blockSize) {
          if (src.boundsSafe(x, y)) {
            var c = src.getPixel(x, y);
            fillRect(src, x, y, x + bs, y + bs, c);
          }
        }
      }
      break;
    case PixelateMode.average:
      for (var y = 0; y < src.height; y += blockSize) {
        for (var x = 0; x < src.width; x += blockSize) {
          var a = 0;
          var r = 0;
          var g = 0;
          var b = 0;
          var total = 0;

          for (var cy = 0; cy < blockSize; ++cy) {
            for (var cx = 0; cx < blockSize; ++cx) {
              if (!src.boundsSafe(x + cx, y + cy)) {
                continue;
              }
              var c = src.getPixel(x + cx, y + cy);
              a += getAlpha(c);
              r += getRed(c);
              g += getGreen(c);
              b += getBlue(c);
              total++;
            }
          }

          if (total > 0) {
            var c = getColor(r ~/ total, g ~/ total, b ~/ total, a ~/ total);
            fillRect(src, x, y, x + bs, y + bs, c);
          }
        }
      }
      break;
  }

  return src;
}