为啥Flutter 中的ui.Image 不能直接转成jpg格式的图片呢?

为啥Flutter 中的ui.Image 不能直接转成jpg格式的图片呢?

flutter用了差不多快两年了,一直有个疑问,为啥在Image 的toByteData 不支持jpg格式只支持png呢。
jpg格式 的图片比png的小很多,很多场景下都需要使用jpg格式的图片。但这么久了,谷歌就是不支持。
直到今天无意间我才看到为什么。

在这里插入图片描述

原来坑爹的谷歌觉得需要jpg格式的场景太少了,不值以增加库大小为代价来支持它。难道国外都用png图片吗,不懂。。。。

那想要编码保存为jpg格式的图片怎么办呢?
在网上找了下发现了一个开源库 image

支持的图片格式

解/编码

  • PNG / Animated APNG
  • JPEG
  • Targa
  • GIF / Animated GIF
  • PVR(PVRTC)
  • ICO
  • BMP

仅解码

  • WebP / Animated WebP
  • TIFF
  • Photoshop PSD
  • OpenEXR

仅编码

  • CUR

使用起来也很方便

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格式的图片呢?







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值