I need to remove the image background to white when I pick an image from the image picker, but I don't want to use API for that work. I can use a third-party plugin.
Asked
Active
Viewed 1,055 times
1 Answers
1
If you want custom background color you need to change the line
Img.Image transparentImage = await colorTransparent(image, 255, 255, 255);
Now it's 255, 255, 255, so it's moving white color now.
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;
}

Anand
- 4,355
- 2
- 35
- 45
-
type 'Future
' is not a subtype of type 'Uint8List'? – abdullah bilal Apr 07 '22 at 17:16 -
if this is working at your side so can you please share the repo? – abdullah bilal Apr 07 '22 at 19:06
-
https://gist.github.com/plateaukao/ebb5e7169dd89cc52bda338762d4997e – Anand Apr 08 '22 at 04:34