brendan-duncan / image

Dart Image Library for opening, manipulating, and saving various different image file formats.
MIT License
1.17k stars 265 forks source link

How to convert transparent part of PNG to specific color #611

Closed lhkzhl closed 8 months ago

lhkzhl commented 8 months ago

why it doesn't work? also has black backgroundColor;

final Directory? downloadsDir = await getDownloadsDirectory();
if (downloadsDir == null) {
  return;
}
// // files.last.
var targetPath = '${downloadsDir.path}/testconvert.jpg';
var image = await img.decodeImageFile(files.last.path);
if (image != null) {
  final p = image.getBytes();
  for (var i = 0, len = p.length; i < len; i += 4) {
    if (p[i + 3] != 255) {
      // If the alpha is transparent
      p[i] = 255; // Set the color to white
      p[i + 1] = 255;
      p[i + 2] = 255;
      p[i + 3] = 255;
    }
  }
  img.writeFile(targetPath, img.encodeJpg(image));
}

this is my image 1-选中@3x this is the result testconvert