How to convert png image to jpg format in Flutter?

Viewed 3092

I'm looking for ways through which I can convert png images to jpg format in flutter as I'm unable to find a way to do that anywhere.

This is the code I tried but it is giving me black images:

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

So, please provide me a way in which I can convert png to jpg. Thank you.

1 Answers

You can try image package. in the example section you can see how to change .webp image to PNG format.

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

PNG to JPEG:

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

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

  File('thumbnail.jpg').writeAsBytesSync(encodeJpg(image));
}
Related