首页 > 解决方案 > 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 位通道。

但是当我尝试显示此图像时,格式是错误的。有人知道如何解决这个问题吗?

标签: imageflutterdartjpeg

解决方案


为什么要使用图像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');
  }
}

推荐阅读