Why dart JPG-to-PNG conversion fails, saving as JPG?

How to convert JPG images to PNG format. My current approach involves using a method that should theoretically convert the images and save them in the gallery. However, I’m encountering an issue where the images are being saved to the gallery, but they remain in JPG format rather than converting to PNG.

Here’s the method I’m using:

getImages() async {
  File _image;
  final pickedFile = await ImagePicker.pickImage(source: ImageSource.gallery);
  setState(() {
    if (pickedFile != null) {
      img.Image image = decodeImage(pickedFile.readAsBytesSync());
      img.Image thumbnail = copyResize(image, width: 120);
      _image = File(pickedFile.path)..writeAsBytesSync(img.encodePng(thumbnail));
      GallerySaver.saveImage(_image.path, albumName: 'Image Resizer')
          .then((bool success) {
            msg: "Image saved",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            timeInSecForIosWeb: 5,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0);
    } else {
      print('No image selected.');
    return _image;

In this method, I’m using the ImagePicker to select an image from the gallery, then using decodeImage and copyResize to process the image, and finally attempting to save it as a PNG using writeAsBytesSync(img.encodePng(thumbnail)). Despite these steps, the image saved in the gallery is still in JPG format. I need help understanding why the conversion isn’t working as expected and how to ensure the images are saved in PNG format.

1 Like

It seems the issue might be with how you’re saving the converted image. When you use writeAsBytesSync(img.encodePng(thumbnail)), it correctly encodes the image as PNG. However, the file path used to save the image, which is pickedFile.path, still points to the original JPG file. You need to specify a new file path for the PNG file.

How do I specify a new file path for the PNG image?

You can modify the file path to have a ‘.png’ extension instead of ‘.jpg’. Here’s how you can do it:

String newPath = pickedFile.path.replaceAll('.jpg', '.png');

_image = File(newPath)..writeAsBytesSync(img.encodePng(thumbnail));

This changes the file extension in the path to ‘.png’, ensuring that the saved file is recognized as a PNG.

Also, this change ensures that the image is saved as a PNG in the gallery. By changing the file extension to ‘.png’, GallerySaver will save the file as a PNG image. Just make sure that the new path doesn’t conflict with any existing files.