【问题标题】:Flutter resize image before upload上传前颤振调整图像大小
【发布时间】:2019-03-07 07:13:59
【问题描述】:

我需要在上传到服务器之前调整图像大小。

我正在使用io和图像包。

import 'dart:io';  
import 'package:image/image.dart' as Img;

使用此功能

uploadImages(File image_File) async {

    Img.Image image_temp = Img.decodeImage(image_File.readAsBytesSync());

    Img.Image resized_img = Img.copyResize(image_temp, 800);

    File resized_file = File('resized_img.jpg')
      ..writeAsBytesSync(Img.encodeJpg(resized_img));

    var stream = new http.ByteStream(DelegatingStream.typed(resized_file.openRead()));
    var length = await resized_file.length();

    var uri = Uri.parse("https://myserver.com/upload.php");

    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('file', stream, length,
        filename: p.basename("resized_image.jpg"));


    request.files.add(multipartFile);
    var response = await request.send();
    print(response.statusCode);
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
  }

当我运行此代码时,应用程序只是冻结并且图像没有上传到服务器。

【问题讨论】:

  • 调试控制台中没有错误?
  • [VERBOSE-2:shell.cc(181)] Dart 错误:未处理的异常:FileSystemException:无法打开文件,路径 = 'thumbnail.jpg'(操作系统错误:不允许操作,errno = 1 ) #0 _File.throwIfError (dart:io/file_impl.dart:647:7) #1 _File.openSync (dart:io/file_impl.dart:491:5) #2 _File.writeAsBytesSync (dart:io/file_impl.dart :616:31)
  • 所以问题是它无法打开名为“thumbnail.jpg”的文件。这是下载的资产还是图像?它在哪里寻找这张图片?
  • @user7380419 你不能像那样直接访问文件系统中的文件。您必须使用path_provider 插件将文件写入应用程序的临时或应用程序目录。但在实践中,理查德的回答是一个更好的选择。
  • 如何将 resized_img 转换为 Unit8List?

标签: image io dart flutter


【解决方案1】:

无需将其写入文件;您可以直接从内存中发送调整大小的图像。

uploadImages(File image_File) async {
  img.Image image_temp = img.decodeImage(image_File.readAsBytesSync());
  img.Image resized_img = img.copyResize(image_temp, 800);

  var request = new http.MultipartRequest(
    'POST',
    Uri.parse('https://myserver.com/upload.php'),
  );
  var multipartFile = new http.MultipartFile.fromBytes(
    'file',
    img.encodeJpg(resized_img),
    filename: 'resized_image.jpg',
    contentType: MediaType.parse('image/jpeg'),
  );

  request.files.add(multipartFile);
  var response = await request.send();
  print(response.statusCode);
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}

注意:当你导入包时,你应该使用小写的标签(即img)。您还需要导入package:http_parser 才能获得MediaType

【讨论】:

【解决方案2】:

当我使用时

package:image/image.dart

面临以下问题

  • 转换图像时显示空白页(可能会占用很多 压缩图像时处理)
  • 压缩后的图像被拉伸,看起来不太好

然后在插件下面使用,同样工作正常,没有任何问题,甚至更快,符合我的预期

https://github.com/btastic/flutter_native_image.git

以上链接中提供的步骤和方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 2015-08-06
    • 2011-04-16
    • 2014-07-19
    • 2017-07-30
    • 2017-06-26
    相关资源
    最近更新 更多