Flutter web Error while loading network image url - flutter

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

Related

Flutter Solve: 'Offset is outside the bounds of the DataView' error only on Firebase Hosting

Code saving file:
on<GeneratePDFFromInvoice>((event, emit) async {
final aspHeaderLogo =
await rootBundle.loadString('assets/images/asp_logo.svg');
final aspFooterSlogan =
await rootBundle.loadString('assets/images/asp_slogan.svg');
final fontBold = Font.ttf(
await rootBundle.load('fonts/Mulish/static/Mulish-Regular.ttf'));
final regFont = Font.ttf(
await rootBundle.load('fonts/Mulish/static/Mulish-Bold.ttf'));
final pw.Document pdf =
pw.Document(theme: PDFTheme(fontBold, regFont).themeData());
PDF(
pdf: pdf,
invoice: event.invoice,
aspHeaderLogo: aspHeaderLogo,
aspFooterSlogan: aspFooterSlogan)
.createPDF();
String fileName =
'${event.invoice.projectNumber}-${event.invoice.invoiceNumber} Invoice.pdf';
final Uint8List fileData = await pdf.save();
const String mimeType = 'application/pdf';
final XFile pdfFile =
XFile.fromData(fileData, mimeType: mimeType, name: fileName);
await pdfFile.saveTo(fileName);
});
Error from browser console is:
Uncaught RangeError: Offset is outside the bounds of the DataView
at DataView.getUint32 (<anonymous>)
at atE.a5A (main.dart.js:92807:5)
at Object.aJI (main.dart.js:25128:3)
at HD.U4 (main.dart.js:94596:28)
at HD.py (main.dart.js:94570:37)
at anw.$3 (main.dart.js:95329:97)
at q_.atL (main.dart.js:95196:7)
at Wp.agb (main.dart.js:95253:8)
at Wp.cm (main.dart.js:95279:22)
at Oj.cm (main.dart.js:94447:16)
The error occurs regardless of which browser I am on, but only happens when I deploy Firebase. There is no error on localhosting. The error doesn't seem to happen when I don't load a font into the PDF. Also using pdf_package link below.
https://pub.dev/packages/pdf
await rootBundle.load('assets/fonts/Mulish/static/Mulish-Bold.ttf'));
Simple type was the issue. missing 'assets' directory reference. Thanks to #Greg Fenton

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

Flutter AZURE BLOB IMAGE UPLOAD - How to upload image captured using mobile camera to azure blob storage

I have been working for few since yesterday to try upload an image to azure blob storage taken using mobile camera form iOS/Android device.
I am able to upload the files but for some reason they being corrupted not able to open the image uploaded.
Please check the image error while opening the uploaded image
I am using flutter package http with different approach all work in uploading image file to azure blob store but it gets corrupted somehow , I tried forcing the ContentType to image/jpeg but no help.
Here is code I am using an http API -
takePicture() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
String fileName = basename(pickedFile.path);
uploadFile(fileName, image);
} else {
print('No image selected.');
}
});
}
First approach -->
http.Response response = await http.put(
uri,
headers: {
"Content-Type": 'image/jpeg',
"X-MS-BLOB-TYPE": "BlockBlob",
},
body: image.path,
);
print(response.statusCode);
Using Approach second -->
final data = image.readAsBytesSync();
var dio = Dio();
dio.options.headers['x-ms-blob-type'] = 'BlockBlob';
dio.options.headers['Content-Type'] = 'image/jpeg';
try {
final response = await dio.put(
'$url/$fileName?$token',
data: data,
onSendProgress: (int sent, int total) {
if (total != -1) {
print((sent / total * 100).toStringAsFixed(0) + "%");
}
},
);
print(response.statusCode);
} catch (e) {
print(e);
}
Approach third -->
var request = new http.MultipartRequest("PUT", postUri);
request.headers['X-MS-BLOB-TYPE'] = 'BlockBlob';
request.headers['Content-Type'] = 'image/jpeg';
request.files.add(
new http.MultipartFile.fromBytes(
'picture',
await image.readAsBytes(),
),
);
request.send().then((response) {
uploadResponse.add(response.statusCode);
}, onError: (err) {
print(err);
});
Help here is much appreciated.
If you want to upload the image to Azure Blob Storage in the flutter application, you can use the Dart Package azblob to implement it. Regarding how to use the package, please refer to here.
For example
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';
import 'package:azblob/azblob.dart';
import 'package:mime/mime.dart';
...
//use image_picker to get image
Future uploadImageToAzure(BuildContext context) async {
try{
String fileName = basename(_imageFile.path);
// read file as Uint8List
Uint8List content = await _imageFile.readAsBytes();
var storage = AzureStorage.parse('<storage account connection string>');
String container="image";
// get the mine type of the file
String contentType= lookupMimeType(fileName);
await storage.putBlob('/$container/$fileName',bodyBytes: content,contentType: contentType,type: BlobType.BlockBlob);
print("done");
} on AzureStorageException catch(ex){
print(ex.message);
}catch(err){
print(err);
}
Unfortunately, the multipart form is causing break of image. I don't know how it works on azure side, because there is little or no information about multipart uploads, but it's clearly broken because of multipart form. I replicated the problem in .net core application and whenever i am using multipart form data to upload image - it is broken. When i am using simple ByteArrayContent - it works. I couldn't find flutter equivalent to ByteArrayContent, so i am lost now :( The package mentioned by #Jim is useless for me, because i want to give clients sas url, so they have permission to upload image on client side. I do not want to store azure storage account secrets in flutter app.
EDIT. I found the solution to send raw byte data with Dio package. You can do that also with http package.
final dio = new Dio();
final fileBytes = file.readAsBytesSync();
var streamData = Stream.fromIterable(fileBytes.map((e) => [e]));
await dio.put(uploadDestinationUrl,
data: streamData,
options: Options(headers: {
Headers.contentLengthHeader: fileBytes.length,
"x-ms-blob-type": "BlockBlob",
"content-type": "image/jpeg"
}));

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

How to get a Uint8List from a Network image by url in 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'));
}
}