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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With