How to get a Uint8List from a Network image by url in Flutter? - flutter

I have the network url of image and I need to get Uint8List. How can I convert it?
I check answers in like question, but those ways don't work.
How to get a Flutter Uint8List from a Network Image?

Try this:
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
.buffer
.asUint8List();

Uint8List yourVar;
final DecoderCallback callback = (Uint8List bytes, {int cacheWidth, int cacheHeight}) {
yourVar = bytes.buffer.asUint8List();
return instantiateImageCodec(bytes, targetWidth: cacheWidth, targetHeight: cacheHeight);
};
ImageProvider provider = NetworkImage(yourImageUrl);
provider.obtainKey(createLocalImageConfiguration(context)).then((key) {
provider.load(key, callback);
});

this did the trick for me:
import 'dart:typed_data';
import 'package:flutter/services.dart';
//Get the image from the URL and then convert it to Uint8List
Uint8List bytes = (await NetworkAssetBundle(Uri.parse('https://some_image_url.png'))
.load('https://some_image_url.png'))
.buffer
.asUint8List();

This works on me (using flutter web) with a library file_saver.
Uri uri = Uri.parse(url);
Uint8List bytes = await readBytes(uri);
await FileSaver.instance.saveFile(filename, bytes, 'jpg',
mimeType: MimeType.JPEG); // specify your vars

I'm having the same problem in Flutter web, I had to use the extended_image library, and I found inside your example that has a method that allows you to convert an ImageProvider to Bytes.
https://github.com/fluttercandies/extended_image/blob/master/example/lib/pages/simple/image_editor_demo.dart.
/// it may be failed, due to Cross-domain
Future<Uint8List> _loadNetwork(ExtendedNetworkImageProvider key) async {
try {
final Response response = await HttpClientHelper.get(Uri.parse(key.url),
headers: key.headers,
timeLimit: key.timeLimit,
timeRetry: key.timeRetry,
retries: key.retries,
cancelToken: key.cancelToken);
return response.bodyBytes;
} on OperationCanceledError catch (_) {
print('User cancel request ${key.url}.');
return Future<Uint8List>.error(
StateError('User cancel request ${key.url}.'));
} catch (e) {
return Future<Uint8List>.error(StateError('failed load ${key.url}. \n $e'));
}
}

Related

Can I convert Future<Uint8List> to Uint8List in flutter? [duplicate]

This question already has answers here:
What is a Future and how do I use it?
(6 answers)
Closed 3 months ago.
I'm making a watermark image using flutter and I need to convert Future to Uint8List.
This is the code where the problem happens.
child: Image.memory(putWatermarkOnImage(asset))
The child is in the Container widget and the result of the putWatermarkOnImage function has to be Uint8List type not a future type.
Future<Uint8List> putWatermarkOnImage(asset) async {
final assetFile = await asset.file;
var imageBytes = await assetFile!.readAsBytes();
ByteData watermarkImgByteData = await rootBundle.load('assets/images/ournow_logo.png');
Uint8List watermarkImgBytes = watermarkImgByteData.buffer.asUint8List();
Uint8List imageUint8List = Uint8List.fromList(imageBytes);
Uint8List watermarkedImg = await ImageWatermark.addImageWatermark(
originalImageBytes: imageUint8List,
waterkmarkImageBytes: watermarkImgBytes,
imgHeight: 200,
imgWidth: 200,
dstY: 400,
dstX: 400);
return watermarkedImg;
}
How can I solve this problem?
I have taken your code and wrote it the way I do to avoid confusions, so I created a class for you on the side to collect all bytes transformation related methods and called them "BytesHandlers"
then I re-organized the code as follows,,, I believe it will work
please test it and tell me if something is going wrong
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
Future<Uint8List> putWatermarkOnImage(AssetEntity asset) async {
Uint8List _output;
if (asset != null){
final File assetFile = await asset.file;
final ByteData watermarkImgByteData = await BytesHandlers.getByteDataFromPath('assets/images/ournow_logo.png');
_output = await BytesHandlers.getUint8ListFromFile(assetFile);
_output = await ImageWatermark.addImageWatermark(
originalImageBytes: _output,
waterkmarkImageBytes: watermarkImgByteData,
imgHeight: 200,
imgWidth: 200,
dstY: 400,
dstX: 400
);
}
return _output;
}
class BytesHandlers {
// --------------------
BytesHandlers();
// --------------------
static Future<ByteData> getByteDataFromPath(String assetPath) async {
/// NOTE : Asset path can be local path or url
ByteData _byteData;
if (assetPath != null){
_byteData = await rootBundle.load(assetPath);
}
return _byteData;
}
// --------------------
static Future<Uint8List> getUint8ListFromFile(File file) async {
Uint8List _uInt;
if (file != null){
_uInt = await file.readAsBytes();
}
return _uInt;
}
// --------------------
}
then you get to call it like this
final Uint8List _ImageWithWatermark = await putWatermarkOnImage(_inputFile);

Flutter web Error while loading network image url

Future<Uint8List> _loadNetworkImage(String imgname) async {
try {
final ByteData imageData = await NetworkAssetBundle(Uri.parse('https://picsum.photos/250?image=9')).load("");
final Uint8List bytes = imageData.buffer.asUint8List();
return bytes;
} catch (_) {
throw "Couldn't resolve network Image.";
}
}
when i run this code on flutter web i am getting this error i dont know why can anyone please help me.
Error: Couldn't resolve network Image.
Uri uri = Uri.parse(filePath);
Uint8List fileData = await http.readBytes(uri);

Flutter Converting network image into byteData

Is there any better way to convert network image to byteData? I am trying to convert network image from firebase url to byteData and here is my code:
Future<Uint8List> _loadNetworkImage() async {
try {
final response = await http.get(imageUrl);
return response.bodyBytes;
} catch (_) {
throw "Couldn't resolve network Image.";
}
}
Currently it takes almost 20+ seconds for a 7mb photo to be converted.
Here is how I ended up doing it.
Future<Uint8List?> _loadNetworkImage(String path) async {
final completer = Completer<ImageInfo>();
var img = NetworkImage(path);
img.resolve(const ImageConfiguration()).addListener(
ImageStreamListener((info, _) => completer.complete(info)));
final imageInfo = await completer.future;
final byteData =
await imageInfo.image.toByteData(format: ui.ImageByteFormat.png);
return byteData?.buffer.asUint8List();
}

How to resize image using multi_image_picker in Flutter?

I'm using multi_image_picker package to pick images and upload to server, but before uploading I want to resize images. I'm trying to accomplish it using dart.ui but having a problem:
//assets is List<Asset> from MultiImagePicker.pickImages
assets.forEach((asset) {
Future<ByteData> byteData = asset.getByteData();
byteData.then((d) async {
List<int> imageData = d.buffer.asUint8List();
String b64 =base64Encode(imageData);
print(b64); // prints [/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE...
//if i send b64 to server then decode it and save as img it's working well
//Resize
ui.instantiateImageCodec(imageData,targetHeight: 800, targetWidth: 600)
.then((codec) {
codec.getNextFrame().then((frameInfo) async {
ui.Image i = frameInfo.image;
ByteData bytes = await i.toByteData();
List<int> resizedImageData = bytes.buffer.asUint8List();
String rb64 = base64Encode(resizedImageData);
print(rb64); // prints too many backslashes:[k5KO/5qWk/+ZlZL/mpaT/5uXlP+alpP/mJSR/5iUkf+YlJH/mZSR/5uWk/+blpP/n5qX/6GcmP+gm5f/oZyY/6GcmP+fmpb/nZi..
//If i send rb64 to server then server cannot decode and save it.
});
});
});
});
This is the function I normally use to resize:
import 'dart:ui' as skia;
Future<skia.Image> resizeImage(String path, {int width, int height}) async {
Uint8List data = await File(path).readAsBytes();
final codec = await skia.instantiateImageCodec(data, targetWidth: width, targetHeight: height);
final frame = await codec.getNextFrame();
return frame.image;
}
As I mentioned in the comment, this is currently not working in Flutter Web but it's due to a bug that will be fixed soon, hopefully.

How to share multiple files simultaneously in flutter?

Am new to flutter . I am using flutter_share package to share files. but now i want to share more than one file at a time. is this possible with flutter? I am using dio to download file and path_provider to get the filepath.
If anyone know please help me to solve this.....
You can use package https://pub.dev/packages/esys_flutter_share
full example code https://github.com/esysberlin/esys-flutter-share/blob/master/example/lib/main.dart
You can convert file to Uint8List then share with Share.files
code snippet
Future<void> _shareMixed() async {
try {
final ByteData bytes1 = await rootBundle.load('assets/image1.png');
final ByteData bytes2 = await rootBundle.load('assets/image2.png');
final ByteData bytes3 = await rootBundle.load('assets/addresses.csv');
await Share.files(
'esys images',
{
'esys.png': bytes1.buffer.asUint8List(),
'bluedan.png': bytes2.buffer.asUint8List(),
'addresses.csv': bytes3.buffer.asUint8List(),
},
'*/*',
text: 'My optional text.');
} catch (e) {
print('error: $e');
}
}
This function is easy work with gmail share and image file is also open. But problem with social media share like when 4 to 5 image share with whatsup share. Image list show like file image. Help about exact solution and easy share with whatsup image.
Use below code :
Future<void> _shareMixed() async {
try {
final ByteData bytes1 = await rootBundle.load('assets/images/ic_back.svg');
final ByteData bytes2 = await rootBundle.load('assets/images/ic_back.svg');
final ByteData bytes3 = await rootBundle.load('assets/images/ic_back.svg');
await Share.files(
'esys images',
{
'back1.png': bytes1.buffer.asUint8List(),
'back2.png': bytes2.buffer.asUint8List(),
'back3.png': bytes3.buffer.asUint8List(),
},
'*/*',
text: 'My optional text.');
} catch (e) {
print('error: $e');
}
}