remove black color from png background in flutter

138 Views Asked by At

i am working on a Flutter app which removes background and makes it transparent. when i hit API and receives image after BG removal, the image gets black color in its background. What i am doing is, i get base64 string of converted image and then converts it to Uint8List and then show insice image.memory widget. I want to remove that black color. for that purpose i tried this code and make some google searches but didn't found something valuable.

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);

    setState(() {
      localBytes = newPng;
    });
    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;
  }

i found this code from Github (link) but when i implemented this. my UI got blocked and start doing lag. Tell me any suggestion what should i do, or help me with some codes, or suggest me to change in this code.

0

There are 0 best solutions below