上传前先调整图像大小

时间:2018-10-02 07:17:37

标签: image io dart flutter

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

我正在使用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);
    });
  }

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

我正在使用

package:image/image.dart

面对下面的问题

  • 在转换图像时显示空白页(可能花费了很多 压缩图像时进行处理)
  • 压缩图像拉伸后看起来不太好

然后使用下面的插件,同样可以正常工作,没有任何问题,甚至更快,而且我期望的是

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

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