imageToBinary method

Future<String> imageToBinary(
  1. String imagePath
)

Implementation

Future<String> imageToBinary(String imagePath) async {
  Uint8List imageBytes;
  ByteData bytes = ByteData(0);
  if (imagePath.contains('assets')) {
    bytes = await rootBundle.load(imagePath);
    imageBytes = bytes.buffer.asUint8List();
  } else {
    imageBytes = File(imagePath).readAsBytesSync();
  }
  //  ByteData bytes = await rootBundle.load(Path);

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

      colors.add(Dependencies().intToBinary(red));
      colors.add(Dependencies().intToBinary(green));
      colors.add(Dependencies().intToBinary(blue));
      //    colors.add(alpha.toRadixString(2));
    }
  }

  // remove "," and "[" and "]" from the colors list
  String imgBin = colors.toString();

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

  return imgBin;
}