简体   繁体   English

Flutter/Dart 以相同格式重写图像

[英]Flutter/Dart rewriting image in the same format

After reading an image with the ImageDescriptor API and resizing it by instantiating a codec I am trying to write the resized version in the application directory.使用 ImageDescriptor API 读取图像并通过实例化编解码器调整其大小后,我试图在应用程序目录中编写调整后的版本。

I saw that the when converting the frame into byte data I have a format which is rawUnmodified which I assumed would write the resized image in the same format as the original image.我看到当将帧转换为字节数据时,我有一个 rawUnmodified 格式,我认为它会以与原始图像相同的格式写入调整大小的图像。 But when I tried to load the resized image I get an image format exception.但是当我尝试加载调整大小的图像时,出现图像格式异常。

Example code:示例代码:

    //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));

In the ImageByteFormat api it says: rawUnmodified -> Unencoded bytes, in the image's existing format.在 ImageByteFormat api 中,它表示:rawUnmodified -> Unencoded bytes,采用图像的现有格式。 For example, a grayscale image may use a single 8-bit channel for each pixel.例如,灰度图像可以为每个像素使用单个 8 位通道。

But when I try to show this image the format is wrong.但是当我尝试显示此图像时,格式错误。 Anybody have an idea how to fix this?有人知道如何解决这个问题吗?

Why use image ImageDescriptor, You can do it easily by image package为什么要使用image ImageDescriptor,你可以通过image package轻松搞定

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');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM