Niccolo
Niccolo

Reputation: 983

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.

Upvotes: 10

Views: 24598

Answers (2)

Anand saga
Anand saga

Reputation: 1503

While i am using

package:image/image.dart

facing below issues

  • showing blank page while converting image ( may be taking so much process while compressing image)
  • After compression image was stretched and not looking good

Then used below plugin, same working fine without any issue, even faster and what i expected

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

steps and method available in above link.

Upvotes: 3

Richard Heap
Richard Heap

Reputation: 51750

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.

Upvotes: 12

Related Questions