flutter用了差不多快两年了,一直有个疑问,为啥在Image 的toByteData 不支持jpg格式只支持png呢。
jpg格式 的图片比png的小很多,很多场景下都需要使用jpg格式的图片。但这么久了,谷歌就是不支持。
直到今天无意间我才看到为什么。
原来坑爹的谷歌觉得需要jpg格式的场景太少了,不值以增加库大小为代价来支持它。难道国外都用png图片吗,不懂。。。。
那想要编码保存为jpg格式的图片怎么办呢?
在网上找了下发现了一个开源库 image
支持的图片格式
解/编码
仅解码
仅编码
使用起来也很方便
import 'dart:io';
import 'dart:isolate';
import 'package:image/image.dart';
class DecodeParam {
final File file;
final SendPort sendPort;
DecodeParam(this.file, this.sendPort);
}
void decodeIsolate(DecodeParam param) {
// Read an image from file (webp in this case).
// decodeImage will identify the format of the image and use the appropriate
// decoder.
var image = decodeImage(param.file.readAsBytesSync())!;
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
var thumbnail = copyResize(image, width: 120);
param.sendPort.send(thumbnail);
}
// Decode and process an image file in a separate thread (isolate) to avoid
// stalling the main UI thread.
void main() async {
var receivePort = ReceivePort();
await Isolate.spawn(
decodeIsolate, DecodeParam(File('test.webp'), receivePort.sendPort));
// Get the processed image from the isolate.
var image = await receivePort.first as Image;
await File('thumbnail.png').writeAsBytes(encodePng(image));
}
版权声明:本文为凸然网站的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:为啥Flutter 中的ui.Image 不能直接转成jpg格式的图片呢?