imageToBinary method

Future<String> imageToBinary(
  1. String imagePath
)

Implementation

Future<String> imageToBinary(String imagePath) async {
  var imageBytes = null;

  if (imagePath.contains('assets')) {
    var bytes = await rootBundle.load(imagePath);

    imageBytes = bytes.buffer.asUint8List();
  } else {
    imageBytes = File(imagePath).readAsBytesSync();
  }

  List<String> colors = [];
  image_lib.Image? image = image_lib.PngDecoder().decodeImage(imageBytes);
  if (image == null) {
    print('Image is null');
  }

  int? width = image?.width;
  int? height = image?.height;

  for (int i = 0; i < height!; i++) {
    for (int j = 0; j < width!; j++) {
      int? pixel = image?.getPixel(j, i);
      var color = pixel?.toInt() ?? 0;
      int red = image_lib.getRed(color);
      int green = image_lib.getGreen(color);
      int blue = image_lib.getBlue(color);
      // int alpha = image_lib.getAlpha(color); //Alpha part has been commented out, because of the conclusion that in Java Alpha part is not used.
      colors.add(intToBinary(red));
      colors.add(intToBinary(green));
      colors.add(intToBinary(blue));
   // colors.add(alpha.toRadixString(2));
    }
  }

  String imgBin = colors.toString();

  imgBin = imgBin.replaceAll(",", "");
  imgBin = imgBin.replaceAll("[", "");
  imgBin = imgBin.replaceAll("]", "");
  imgBin = imgBin.replaceAll(" ", "");

  return imgBin;
}