Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter resize image before upload

I need to resize images before uploading to the server.

I am using io and image package.

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

using this function

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

When I run this code, and the app just freezes and the images didn't upload to the server.

like image 260
Niccolo Avatar asked Oct 02 '18 07:10

Niccolo


1 Answers

There's no need to write it to a file; you can send the resized image directly from memory.

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

Note: when you import packages, you should use a lower case label (i.e. img). You'll need to import package:http_parser to get MediaType too.

like image 184
Richard Heap Avatar answered Sep 18 '22 08:09

Richard Heap