问题描述
使用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->未编码的字节,采用图像的现有格式。例如,灰度图像可以为每个像素使用单个8位通道。
但是当我尝试显示此图像时,格式错误。有人知道如何解决此问题吗?
解决方法
为什么要使用图像ImageDescriptor,您可以通过image包轻松地完成
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');
}
}