如何在颤动中将从照片库中选择的jpg图像转换为png图像?
答案 0 :(得分:5)
看看image package。以下是examples section中可用的摘要,它将JPEG
转换为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));
}
答案 1 :(得分:0)
使用image库,您可以这样做
jpegToPng(jpegimage){
new File('output.png')
..writeAsBytesSync(encodePng(thumbnail));
}
答案 2 :(得分:0)
您需要做的第一件事是导入IMAGE库。然后使用类似如下的自定义功能,可以将JPG转换为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(Image imagePath) async {
//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, 800);
//get converting and saving in file
File compressedImage = new File('${tempDir.path}/img_$rand.png')..writeAsBytesSync(Im.encodePng(smallerImage, level:8));
}
答案 3 :(得分:0)
列出的许多建议都很好,我只是想添加一些可能会使某些人困惑的建议。如果获取黑色图像,请查看图像中是否有Alpha通道。
我将Image包用于我的目的,因此在解码过程中只添加了一个:
img.decodeImage(imageFile.readAsBytesSync())..channels = img.Channels.rgba
我还使用Image / Paint方法获取.png的Dart UI图像:
img =图片包,缩略图是img图片。
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;