Flutter how to remove image background

58 views Asked by At

I need to remove image background in flutter for all the three platform Android, IOS and web.

Ex : I have a image from gallery or camera and need to make background transparent.

how to do this without sdk or any third party api? i am now using https://www.remove.bg/ but its too expansive

1

There are 1 answers

0
Mistraleuh On

I have a solution but only for 'white' pixels. If for some reasons you don't want to remove white pixels, look at the second part.

  1. Replace pixels

Firstly install image package on pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  image: ^3.0.8

And this following functions work:

import 'dart:io';
import 'package:image/image.dart' as img;

void makeTransparentBackground(File imageFile) {
  img.Image image = img.decodeImage(imageFile.readAsBytesSync())!;

  int white = img.getColor(255, 255, 255, 255);

  for (int y = 0; y < image.height; y++) {
    for (int x = 0; x < image.width; x++) {
      if (image.getPixel(x, y) == white) {
        image.setPixelRgba(x, y, 0, 0, 0, 0);
      }
    }
  }
  File('imgNoBg.png')..writeAsBytesSync(img.encodePng(image));
}
  1. Remove.bg Api

I thinks this is the best choice, you can take a look to the remove.bg's documentation right here: https://www.remove.bg/fr/api