如何在flutter中以编程方式删除图像背景?

问题描述 投票:0回答:2

当我从图像选择器中选取图像时,我需要将图像背景删除为白色,但我不想使用 API 来完成这项工作。我可以使用第三方插件。

flutter image dart background imagebackground
2个回答
1
投票

如果您想要自定义背景颜色,您需要更改该行

 Img.Image transparentImage = await colorTransparent(image, 255, 255, 255);

现在是 255, 255, 255,所以现在正在移动白色。

Future<Uint8List> _downloadImage() async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$_filename');

    if (file.existsSync()) {
      var image = await file.readAsBytes();
      return image;
    } else {
      var response = await http.get(_url,);
      var bytes = response.bodyBytes;
      Uint8List newPng = await removeWhiteBackground(bytes);
      file.writeAsBytes(newPng);
      return newPng;
    }
  }

  Future<Uint8List> removeWhiteBackground(Uint8List bytes) async {
    Img.Image image = Img.decodeImage(bytes);
    Img.Image transparentImage = await colorTransparent(image, 255, 255, 255);
    var newPng = Img.encodePng(transparentImage);
    return newPng;
  }

Future<Img.Image> colorTransparent(Img.Image src, int red, int green, int blue) async {
  var pixels = src.getBytes();
  for (int i = 0, len = pixels.length; i < len; i += 4) {
    if(pixels[i] == red
        && pixels[i+1] == green
        && pixels[i+2] == blue
    ) {
      pixels[i + 3] = 0;
    }
  }

  return src;
}

-1
投票

https://pub.dev/packages/backraund这是我的第一个插件这是一个用户友好的在线工具,可以快速删除图像中的背景。

© www.soinside.com 2019 - 2024. All rights reserved.