I found a solution that propably suits you . Speed is fantastic and size of the image is reduced significantly.
late Uint8List targetlUinit8List;
late Uint8List originalUnit8List;
Future<Uint8List> _resizeImage() async {
var imageUrl = Uri.parse('https://picsum.photos/250?image=9');
http.Response response = await http.get(imageUrl);
originalUnit8List = response.bodyBytes;
ui.Image originalUiImage = await decodeImageFromList(originalUnit8List);
ByteData? originalByteData = await originalUiImage.toByteData();
print('original image ByteData size is ${originalByteData!.lengthInBytes}');
var codec = await ui.instantiateImageCodec(originalUnit8List,
targetHeight: 200, targetWidth: 200);
var frameInfo = await codec.getNextFrame();
ui.Image targetUiImage = frameInfo.image;
ByteData? targetByteData =
await targetUiImage.toByteData(format: ui.ImageByteFormat.png);
print('target image ByteData size is ${targetByteData!.lengthInBytes}');
targetlUinit8List = targetByteData.buffer.asUint8List();
//remove delay function
await Future.delayed(Duration(seconds: 2));
return targetlUinit8List;
}
Then I have a futureBuilder for my example , but you can use anything you want :
if (snapshot.hasData) {
children = <Widget>[
const Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Image.memory(snapshot.data!),
)
];
}
Only thing left to implement is to dispose the unused variables , and I have no idea how to do it (I am not the best at flutter). I want to know if anyone implements this with disposed variables
image
package and it'sdecodeImage
method is the bottleneck. So while it's decoding the image bytes into theirImage
object it freezes the flutter app (the tab where flutter app is loaded) for a while. And it depends on the size of image, big images takes longer. After the resize process completes, it reduces the image size and performance comes back to normal. For your use case, i think its not a solution as resizing image itself is a heavy op. So maybe while uploading images you can upload two versions, one full size and another downscaled. – Reggy