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;
}
Related
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;
}
I have tried this code below but an empty folder i have found and still cannot create a file, but no errors found in the terminal.
here is the packages i have used :
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
this is the codes to create the file, is there something wrong:
Future<String> getFilePath() async {
Directory? appExtDirectory = await getExternalStorageDirectory();
String appExtPath = appExtDirectory.toString();
print('$appExtPath');
return appExtPath;
}
Future<File> get _localFile async {
final path = await getFilePath();
return File('$path/counter.txt');
}
Future<File> writeCounter() async {
final file = await _localFile;
// Write the file
return file.writeAsString("This is my demo text that will be saved to : counter.txt");
}
void saveFile() {
writeCounter();
}
Regards..
Try String appExtPath = appExtDirectory.path;
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
See the following code:
import 'package:path_provider/path_provider.dart';
Directory? directory = await getExternalStorageDirectory();
String id = "z8PANL7qgbg9XJOQQZM2V9RnP5nESNvi";
try {
String fullPathName = directory.path + '/' + id + '.jpg';
file = File(fullPathName).writeAsBytes(data);
print("success $fullPathName");
}
I get the following output:
success /storage/emulated/0/Android/data/com.example.myapp/files/z8PANL7qgbg9XJOQQZM2V9RnP5nESNvi.jpg
It seems that the file is successfully written but then when I try to see the file (an image), with ImagePicker, it is impossible to find it anywhere.
NB: I use Android emulator.
you can use this way
import 'package:image/image.dart' as ImD;
File file;
photoAdress() async {
final directory = await getTemporaryDirectory();
final path= directory .path;
ImD.Image photo= ImD.decodeImage(dosya.readAsBytesSync());
var formed= File("$path/img_$gonderiID.jpg")..writeAsBytesSync(ImD.encodeJpg(photo, quality: 90));
setState(() {
file= formed;
});
}
I'm trying to capture an image, then send path of the image to a function that returns the image in Base64. For capturing an image I'm using the example on Flutter website.
Future _takePhoto(BuildContext context) async {
try {
await _initializeControllerFuture;
final path = join(
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
await _cameraController.takePicture(path);
setState(() {
_imagePath = path;
});
} catch (e) {
print(e);
}
}
It's working well. I can see the captured image in widget Image.file(File(_imagePath))
The problem starts when I'm trying to convert the image into Base64.
File file = File(_imagePath);
final _imageFile = ImageProcess.decodeImage(
file.readAsBytesSync(),
);
String base64Image = base64Encode(ImageProcess.encodePng(_imageFile));
print(base64Image);
I copy and paste the printed message into an online tool that generates an image from Base64 and either it's all black or there is tiny top layer of the image and the rest is black.
print function did not print everything.
you can see full result with debug mode
and copy paste full result in debug mode to online tool
This should print your image as a base64 string
import 'dart:typed_data';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
File file = File(_imagePath);
Uint8List bytes = file.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);
To show base64 print:
import 'dart:developer' as developer;
developer.log(
'log me',
name: 'my.app.category',
error: jsonEncode(base64Image),
);