How to remove surrounding whitespace from an Image in Dart Flutter?

1,530

Solution 1

You can do image processing in Dart (Flutter is just a UI Framework, image processing is an algorithm, so not related to UI, but with the language itself).

You can try to use the image package, open the image, decode its bytes and apply any image processing algorithms there.

This library will help you extract the image bytes, but if you need more hardcore image processing algorithms, like the ones in OpenCV, and you aren't very keen on implementing them yourself, you might need to do some maneuvers like:

  1. Test any of the OpenCV packages for Flutter/Dart in pub.dev. I can't recommend any as I never used them.

  2. Use Method Channel calls to interact with OpenCV libraries for the native platforms (Android/iOS), passing the image and process it there and return it to Flutter afterwards.

Not ideal, but totally doable.

Solution 2

First, you need to install Image package

Then use the following code to remove the background

import 'package:image/image.dart' as Img;

Future<Uint8List> removeWhiteBackgroundFromImage(
    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;
}

Note: if you want to convert image to Uint8List use the follwing code

Uint8List imageBytes = File(imageFilePath).readAsBytesSync();

Reference Link: https://gist.github.com/plateaukao/ebb5e7169dd89cc52bda338762d4997e

Share:
1,530
jazzbpn
Author by

jazzbpn

With 6+ years of experience, I have developed many iOS/android applications in different context, professional and oldest passion for computer programming began very early in my life. I've learned the social environment is as important as logic aspects of the developing approach then I appreciate very much to get in touch with positive and eager colleagues that involve me in new and exciting challenges. This is why I still want to get involved in new opportunities to improve my skillness.

Updated on December 20, 2022

Comments

  • jazzbpn
    jazzbpn over 1 year

    Users write to screen and create image and send to our platform. Each image is a picture of something(hand written text) which is taken with a white background. I would like to remove all the white parts of the image get the content only user writes. Is it possible using image-processing in flutter? If possible how?