image - Flutter/Dart 以相同格式重写图像
问题描述
在使用 ImageDescriptor API 读取图像并通过实例化编解码器调整其大小后,我试图在应用程序目录中编写调整大小的版本。
我看到当将帧转换为字节数据时,我有一个 rawUnmodified 格式,我认为它会以与原始图像相同的格式写入调整大小的图像。但是当我尝试加载调整大小的图像时,我得到一个图像格式异常。
示例代码:
//read the original image and obtain the image descriptor
var imageData = await file.readAsBytes();
final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(imageData);
final imDescr = await ImageDescriptor.encoded(buffer);
//resize the image, get the first frame and convert it to bytes
Codec codec = await imDescr.instantiateCodec(targetWidth: 100, targetHeight: 100);
FrameInfo frameInfo = await codec.getNextFrame();
var bytes = await frameInfo.image.toByteData(
format: ImageByteFormat.rawUnmodified,
//note when using the png format it works, but I would like to have it in the original image format(in this case its jpg)
);
//write the resized image
Directory appDir = await getApplicationDocumentsDirectory();
var path = appDir.path;
var file = File('$path/test1.jpg');
await file.writeAsBytes(bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
在 ImageByteFormat api 中,它说:rawUnmodified -> Unencoded bytes,采用图像的现有格式。例如,灰度图像可以为每个像素使用单个 8 位通道。
但是当我尝试显示此图像时,格式是错误的。有人知道如何解决这个问题吗?
解决方案
为什么要使用图像ImageDescriptor,你可以通过图像包轻松做到
File resizeImage(File imageFile, String imageFormat, int targetWidth, int targetHeight) {
im.Image tempImage = im.decodeImage(imageFile.readAsBytesSync());
tempImage = im.bakeOrientation(tempImage);
tempImage = im.copyResize(tempImage, width: targetWidth, height: targetHeight);
File newImage;
if (imageFormat == 'jpg') {
newImage = File('newpath/test.jpg');
newImage.writeAsBytesSync(im.encodeJpg(tempImage));
return newImage;
} else if (imageFormat == 'png') {
newImage = File('newpath/test.png');
newImage.writeAsBytesSync(im.encodePng(tempImage));
return newImage;
} else {
throw ('Unknown Image Format');
}
}
推荐阅读
- r - 从 Bookdown TOC 中省略索引页
- javascript - 根据 Gatsby 中的日期动态更改页面的 URL
- regex - REGEX - 正则表达式以空格开头或以空格结尾或以 > 开头并以 < 结尾并且有一个文本 'ghghfg'
- c# - 对来自多个来源(例如 Cognito 和 Azure)的令牌进行身份验证
- r - 在数据框中选择第一次出现的带有前缀的变量
- python - 如何在python中从数组和列表创建字典?
- git - git for Windows:提交时删除尾随空格
- javascript - 无法从 content.js 文件向浏览器注入代码
- php - 如何在 AJAX 响应中重新初始化 DataTable
- mysql - 如何将一列添加到 SQL 表中,该列是其他两列的乘积?