Convert jpg image to png image in Flutter iOS

和自甴很熟 提交于 2021-01-04 06:54:14

问题


How can I convert a jpg image selected from photo gallery to png image in flutter?


回答1:


Take a look at the image package. The following is a snippet available in the examples section, which converts JPEG to PNG:

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read a jpeg image from file.
  Image image = decodeImage(new File('test.jpg').readAsBytesSync());

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

  // Save the thumbnail as a PNG.
  new File('out/thumbnail-test.png')
    ..writeAsBytesSync(encodePng(thumbnail));
}



回答2:


First thing you need to do is import IMAGE library. Then using similar custom function like below you can convert JPG to PNG

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
void jpgTOpng(path) async {
  File imagePath = File(path);
  //get temporary directory
  final tempDir = await getTemporaryDirectory();
  int rand = new Math.Random().nextInt(10000);
  //reading jpg image
  Im.Image image = Im.decodeImage(imagePath.readAsBytesSync());
  //decreasing the size of image- optional
  Im.Image smallerImage = Im.copyResize(image, width:800);
      //get converting and saving in file
  File compressedImage = new File('${tempDir.path}/img_$rand.png')..writeAsBytesSync(Im.encodePng(smallerImage, level:8));     
}



回答3:


using image library you can do this

jpegToPng(jpegimage){
new File('output.png')
    ..writeAsBytesSync(encodePng(thumbnail));
}



回答4:


Many of the suggestions listed are good, I just wanted to add something that may confuse some people. If you're getting black images, see if you have alpha channels in the image. I use the Image package for my purposes, so I just add one during the decode: img.decodeImage(imageFile.readAsBytesSync())..channels = img.Channels.rgba

I also use the Image/Paint method to get a Dart UI Image as .png:

img = Image package, thumbnail is an img Image.

import 'dart:ui' as ui;
import 'package:image/image.dart' as img;

    ui.Image imageN;
        try {
          final paint = await PaintingBinding.instance
              .instantiateImageCodec(img.encodePng(thumbnail, level: 0));
          final nextFrame = await paint.getNextFrame();
          imageN = nextFrame.image;
        } catch (e, s) {
          // handle the exception
        }
        return imageN;


来源:https://stackoverflow.com/questions/51042665/convert-jpg-image-to-png-image-in-flutter-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!