如何在Flutter中将png图像转换为jpg格式?

Dee*_*shu 8 android dart flutter

我正在寻找可以在 flutter 中将 png 图像转换为 jpg 格式的方法,因为我无法在任何地方找到一种方法来做到这一点。

这是我尝试过的代码,但它给了我黑色图像:

// Read a jpeg image from file.
 img.Image image = img.decodeImage(File(pngfilepath).readAsBytesSync());

// Resize the image to a 200 height thumbnail (maintaining the aspect ratio).
 img.Image thumbnail = img.copyResize(image, height: 200);

// Save the thumbnail as a JPG.
 File(outputfilepath/filename.jpg)
   ..writeAsBytesSync(img.encodeJpg(thumbnail));
Run Code Online (Sandbox Code Playgroud)

所以,请提供一种将 png 转换为 jpg 的方法。谢谢。

Abb*_*hsn 6

你可以尝试一下镜像包。在示例部分中,您可以看到如何更改.webp图像PNG格式。

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

void main() {
  // Read an image from file (webp in this case).
  // decodeImage will identify the format of the image and use the appropriate
  // decoder.
  final image = decodeImage(File('test.webp').readAsBytesSync())!;

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  final thumbnail = copyResize(image, width: 120);

  // Save the thumbnail as a PNG.
  File('thumbnail.png').writeAsBytesSync(encodePng(thumbnail));
}
Run Code Online (Sandbox Code Playgroud)

PNG 到 JPEG:

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

void main() {
  final image = decodeImage(File('test.png').readAsBytesSync())!;

  File('thumbnail.jpg').writeAsBytesSync(encodeJpg(image));
}
Run Code Online (Sandbox Code Playgroud)