Home > Enterprise >  Dart Fails to save Bytes to PNG, JPEG
Dart Fails to save Bytes to PNG, JPEG

Time:12-14

I have been trying for hours to figure out why my code is not working. Basically, I have an image. I load its bytes into dart as a list of Uint8List. Then, I replace the values of the list with some other values. The problem is that after replacing the values, when I call the File().writeAsBytes() function, the image is CORRUPTED. Don't know why this is happening. Tried doing everything I could.


var b = File("assets/1K91k (1).jpg").readAsBytesSync();
void main() {
  runApp(const MyApp());
  for (int i = 0; i < b.length; i  ) {
    double check = b[i] / 255;
    if (check > 0.8) {
      b[i] = 255;
    } else {
      b[i] = 2;
    }
  }
  File("/home/kq1231/Desktop/test.jpg")
    ..createSync()
    ..writeAsBytesSync(b);
}

I tried converting the b list to a Uint8List but to no avail.

CodePudding user response:

Feels funny to answer my own question but here's how it got working:

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

image.Image prettify(String fileName, String exportPath, String imageName,
    double threshold, int blurRadius) {
  var b = image.decodeImage(File(fileName).readAsBytesSync());
  b = image.gaussianBlur(b!, blurRadius);
  for (int i = 0; i < b.width; i  ) {
    for (int j = 0; j < b.height; j  ) {
      var pix = b.getPixel(i, j);
      if ((image.getBlue(pix)   image.getRed(pix)   image.getGreen(pix)) /
              (255 * 3) >
          threshold) {
        b.setPixel(i, j, 0xffffff);
      } else {
        b.setPixel(i, j, 0);
      }
    }
  }
  File("$exportPath/$imageName")
    ..createSync()
    ..writeAsBytesSync(image.encodePng(b));
  return b;
}

This is a function called prettify. It applies a specific operation to a given image. First, decode the image. Then, loop through each pixel, average the R, G and B values to get the grayscale value (get the value of the pixel using image.getPixel() and set its value using image.setPixel()). Then, encode it back to .png format and save it.

Note that image is the name of the library imported.

  • Related