how to get XFile populated with images from flutter project assets? - flutter

how to get XFile populated with images from flutter project assets?
how to get XFile populated with images from flutter project assets?

You can use rootBundle from the services.dart package. Import the package like this:
import 'package:flutter/services.dart' show rootBundle;
And call the following function to get the image from asset and populate XFile:
Future<XFile> getImageFileFromAssets() async {
final byteData = await rootBundle.load('./assets/image.png');
final file = File('${(await getTemporaryDirectory()).path}/image.png');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
XFile xFile = XFile(file.path);
return xFile;
}

Related

Create a image File from a Image widget

I'm developing an application where the user of my App must upload images to Firebase Storage, and for that, they need to be in File format.
Part of the images come from the web, that is, they were obtained through the Image.network() method. Another part comes from the cell phone gallery, and was obtained by the ImagePicker package.
Even coming from different sources, all images are being grouped in a List<Image>. Now, I need to upload this list of images to Storage, but for that I need to convert them to File and I don't know how to do that, could anyone help?
First you should save image from network url to file, it is better like this
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/abc.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
After that add this to you image list with the image taken from image picker.
https://pub.dev/packages/image_picker
import 'package:image_picker/image_picker.dart';
final ImagePicker _picker = ImagePicker();
final XFile? image = await _picker.pickImage(source:ImageSource.gallery);
You can download the image and save the file in the followwing way.
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/xyz.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}

Using Flutter Camera package, how do I convert a photo to a base64 string?

Using the Flutter Camera package (v0.9.4+5), how do I convert a captured photo into a base64 string?
I believe the following code will work, but welcome to any thoughts on how the code can be improved.
import 'dart:convert' as convert;
void capturePhoto() async {
// Note: `controller` being initialized as shown in readme
// https://pub.dev/packages/camera#example
XFile photo = await controller.takePicture();
List<int> photoAsBytes = await photo.readAsBytes();
String photoAsBase64 = convert.base64Encode(photoAsBytes);
}
Try this.
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
final bytes = Io.File(image.path).readAsBytesSync();
String img64 = base64Encode(bytes);
print (img64);

How to add local image to flutter_local_notifications

I am trying to create push notifications and would like to add an image to the notification. I am able to add images from the web as shown in the screenshot below.
How can I add a local image instead? I tried adding the file path as shown below, but it did not work:
The file path you are adding is a root path of your project but this method needs an android file path(e.g. /storage/emulated/0/Android/data/com.expampe.app/cache/bg.png), so you have to convert your asset image to a File and save it, then return its path:
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<String> getImageFilePathFromAssets(String asset) async {
final byteData = await rootBundle.load(asset);
final file =
File('${(await getTemporaryDirectory()).path}/${asset.split('/').last}');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file.path;
}
then just
final attachmentPicturePath = await getImageFilePathFromAssets('assets/image2.jpg');
The Easiest Way is--
static Future<String> getImageFilePathFromAssets(
String asset, String filename) async {
final byteData = await rootBundle.load(asset);
final temp_direactory = await getTemporaryDirectory();
final file = File('${temp_direactory.path}/$filename');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes,
byteData.lengthInBytes));
return file.path;
}
final bigpicture = await Utils.getImageFilePathFromAssets(
'assets/images/largicon.png', 'bigpicture');
And For donwload Using URL---
add http and path_provider in pubspec.yml
static Future<String> downloadFile(String URL, String filename) async
{
final direactory = await getApplicationSupportDirectory();
final filepath = '${direactory.path}/$filename';
final response = await http.get(Uri.parse(URL));
print(response);
final file = File(filepath);
await file.writeAsBytes(response.bodyBytes);
return filepath;
}
check this demo github

Flutter - Network Image to File

I have an Image URL like "https://example.com/xyz.jpg". Now I want to put the image in a File type variable;
Something along these lines:
File f = File("https://example.com/xyz.jpg");
The whole point is to get the image from the given URL and save it as a File variable. How can I do so?
I searched for many solutions on the internet but there was no straightforward way to do so.
PS: I could have missed something where the question was similarly answered so please let me know the link where I can find it.
Edit: I am using the File type variable to pass it in the share function.
This is the library that I am using.
Here is my current on share button click code
if (file != null) {
ShareExtend.share(file.path, "image",
sharePanelTitle: "share image title",
subject: "share image subject");
}
Thanks for your help.
You need to download image and create an empty file then fill the file with image data:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get(Uri.parse('https://example.com/xyz.jpg)');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> getImage({required String url}) async {
/// Get Image from server
final Response res = await Dio().get<List<int>>(
url,
options: Options(
responseType: ResponseType.bytes,
),
);
/// Get App local storage
final Directory appDir = await getApplicationDocumentsDirectory();
/// Generate Image Name
final String imageName = url.split('/').last;
/// Create Empty File in app dir & fill with new image
final File file = File(join(appDir.path, imageName));
file.writeAsBytesSync(res.data as List<int>);
return file;
}
Future<File> fileFromImageUrl() async {
String img='https://pps.whatsapp.net/v/t61.24694-24/160266256_1115367465775510_3546030680878251116_n.jpg?ccb=11-4&oh=01_AdSsrMGOPfs8CUJsEkYImMUu5L4DAzt2ym8eBrdsMG5O0Q&oe=63D7B45E';
final response = await http.get(Uri.parse(img));
final documentDirectory = await getApplicationDocumentsDirectory();
final file =
File(p.join(documentDirectory.path, 'File Name.jpg'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}

How to copy images in assets to application document directory in Flutter?

My flutter app has the following assets.
assets:
- "images/01.png"
- "images/02.png"
- "images/03.png"
...
I'd like to copy these image files to the local path I can get by the following.
Directory docDir = await getApplicattionDocumentsDirectory();
String localPath = docDir.path;
Create a file in your application directory and copy your asset image byte by byte to that file. That's it! You copied your file.
final Directory docDir = await getApplicationDocumentsDirectory();
final String localPath = docDir.path;
File file = File('$localPath/${path.split('/').last}');
final imageBytes = await rootBundle.load(path);
final buffer = imageBytes.buffer;
await file.writeAsBytes(
buffer.asUint8List(imageBytes.offsetInBytes, imageBytes.lengthInBytes));
getApplicationDocumentsDirectory you need path_provider package.
Suppose you want to copy an m4a file to your application document directory
pubspec.yaml
assets:
- assets/audio/no_sound_3n.m4a
Your code
import 'package:path_provider/path_provider.dart';
final Directory docDir = await getApplicationDocumentsDirectory();
final String localPath = docDir.path;
File file = File(localPath);
final asset = await rootBundle.load("assets/audio/no_sound_3n.m4a");
final buffer = asset.buffer;
await file.writeAsBytes(
buffer.asUint8List(asset.offsetInBytes, asset.lengthInBytes));
You asset folder
I too couldn't find a way yet. A way to mitigate this is following the assets guide, by specifying
flutter:
assets:
- assets/
And load arbitrary files via rootBundle
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/index.html');
}
or in your case using AssetImage
Widget build(BuildContext context) {
// ...
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('graphics/background.png'),
// ...
),
// ...
),
);
// ...
}
This thread is pretty old, but in case anyone is still looking for an answer, this is how I did it :)
rootBundle.load('assets/test.jpg').then((content) {
File newFile = File('${dir.path}/img.jpg');
newFile.writeAsBytesSync(content.buffer.asUint8List());
visionImage = FirebaseVisionImage.fromFile(newFile);
_runAnalysis();
});