Created
April 13, 2019 05:18
-
-
Save plateaukao/ebb5e7169dd89cc52bda338762d4997e to your computer and use it in GitHub Desktop.
image remove background in flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried using the code, but seems like @Aishh2211 is correct, isn't removing bg for me at least.
Also wanted to ask if I have a gradient background what could be done in that case.
Thanks for the snippet though.