【问题标题】:How to compress/reduce image sizes while uploading in Dart?在 Dart 中上传时如何压缩/减小图像大小?
【发布时间】:2018-11-05 16:06:54
【问题描述】:

在 Dart 中上传时如何压缩/减小图像大小?我正在尝试上传 5MB 的图像,但我想在上传时减小它的大小。我正在使用 Dart 和 Flutter。

【问题讨论】:

  • 您可能希望在上传之前降低图像的分辨率。但请记住,上传后您无法恢复分辨率。因此,您可以永久减小其大小,但不能仅在上传时减小其大小
  • 我不介意这里的质量。那么,如何降低分辨率以减小图像大小以使应用程序更快。
  • 图片来源是什么?如果它来自相机,则以较低的分辨率捕获图像可能是最简单的:*.com/questions/50453705/…
  • @Richard Heap 从您的回答中可以看出,image 库解码和调整图像大小很慢
  • 没错,这就是为什么我建议尝试以较低分辨率捕获原始图像的原因。来源是相机吗?

标签: dart flutter


【解决方案1】:

飞镖

使用Image 包:

使用此包,您可以加载图像、调整大小并将其保存为 png:

首先,在 pubspec.yaml 文件中添加 image 作为依赖项。

用法

import 'dart:io';
import 'package:image/image.dart';
void main() {
  // Read an image from file (webp in this case).
  // decodeImage will identify the format of the image and use the appropriate
  // decoder.
  Image image = decodeImage(File('test.webp').readAsBytesSync());

  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  Image thumbnail = copyResize(image, width: 120);

  // Save the thumbnail as a PNG.
  File('thumbnail.png')..writeAsBytesSync(encodePng(thumbnail));
}

如果您想在 flutter 中使用此图像,请不要使用它。使用 flutter_image_compressResizeImage class 等其他解决方案。

Q:Dart 已经有图片压缩库了。为什么要使用原生?

A:由于未知原因,Dart 语言中的图像压缩效率不高,即使在发布版本中也是如此。使用隔离不能解决 问题。

【讨论】:

    【解决方案2】:

    有一个image manipulation package on pub。它甚至包括一个你想要做什么的例子。

    import 'dart:io' as Io;
    import 'package:image/image.dart';
    void main() {
      // Read an image from file (webp in this case).
      // decodeImage will identify the format of the image and use the appropriate
      // decoder.
      Image image = decodeImage(new Io.File('test.webp').readAsBytesSync());
    
      // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
      Image thumbnail = copyResize(image, 120);
    
      // Save the thumbnail as a PNG.
      new Io.File('thumbnail.png')
            ..writeAsBytesSync(encodePng(thumbnail));
    }
    

    【讨论】:

    • 这会导致应用冻结。
    • 调整图像大小是 CPU 密集型的。你应该在一个单独的 Isolate 中运行它,这样 Flutter 主线程就不会被阻塞。第一个示例演示了如何执行此操作:github.com/brendan-duncan/image/wiki/Examples
    • @MichaelM 该库应该包含期货以便于使用。
    • 无法压缩 PNG 图像或调整其大小。是否有任何选项可以压缩和调整 png 图像的大小? *.com/questions/61436254/…
    • @OliverDixon 一个简单的 Future 仍然在同一个主隔离区运行。