I want to convert path "content://media/external/images/media/138501" to File and set in the Image.
Code:
File imageFile = File("content://media/external/images/media/138501");
is not working on:
DecorationImage(image: ExactAssetImage(imageFile.path),fit: BoxFit.fill)
You can use uri_to_file package. It supports content:// URI.
Simple to use (Updated)
import 'package:uri_to_file/uri_to_file.dart';
try {
String uriString = 'content://sample.txt';
// Don't pass uri parameter using [Uri] object via uri.toString().
// Because uri.toString() changes the string to lowercase which causes this package to misbehave
// If you are using uni_links package for deep linking purpose.
// Pass the uri string using getInitialLink() or linkStream
File file = await toFile(uriString);
} on UnsupportedError catch (e) {
print(e.message);
} on IOException catch (e) {
print(e);
} catch (e) {
print(e);
}
then you can use this file as you want
Important note
Don't pass uri value like this
File file = await toFile(uri.toString());
Use like this if you are using uni_links package for deep linking purpose. Use getInitialLink() or linkStream
String? uriString = await getInitialLink();
if (uriString != null) {
File file = await toFile(uriString);
}
linkStream.listen((uriString) async {
if (uriString != null) {
File file = await toFile(uriString!);
}
});
This will not modify the uri string as we are not using uri.toString()
So this package will work fine
Working example:
Working example
For more details: uri_to_file
According to the doc you can use the fromUri constructor: File.fromUri(Uri uri).
Your case:
File imageFile = File.fromUri("content://media/external/images/media/138501");
You can use Absolute path plugin.
final filePath = await FlutterAbsolutePath.getAbsolutePath(uriString);
and then show the image by using Image.file:
Image.file(
File(filePath),
);
Make use of flutter_absolute_path package.
flutter_absolute_path: ^1.0.6 In pubsec.yaml
To convert file path from this format : “content://media/external/images/media/5275” To
"/storage/emulated/0/DCIM/Camera/IMG_00124.jpg”
final filePath = await FlutterAbsolutePath.getAbsolutePath("Any path
here");
File tempFile = File(filePath);
if (tempFile.existsSync()) {
//add your logic here.
}
define your URL:
final url = "Your Image Url";
then convert the Image Url to File in flutter :
XFile _xFile = XFile(url);
Done.
You could use Image.file constructor.
DecorationImage(
image: Image.file(File("content://media/external/images/media/138501")),
fit: BoxFit.fill
)
Please take a note: On Android, this may require the android.permission.READ_EXTERNAL_STORAGE permission.
Related
I apologise in advance if this is a silly question, but I have created a file and stored it in my "assets" sub-directory, which is at the same level as my lib directory and my pubspec.yaml file. I've set the relative path to "assets/ExerData.json" in my code (see below).
When I run the code saved as a scratch.dart file as shown below, hitched up to a Galaxy Nexus API 29 emulator, it can only tell me "Can't find file!"
import 'dart:io';
import 'package:flutter/services.dart';
String filePath = "assets/ExerData.json";
void main() {
performTasks();
}
void performTasks() {
if (checkFileExists(filePath)) {
readFile(filePath);
} else {
print("Can't find file");
}
}
bool checkFileExists(path) {
bool result = File(path).existsSync();
print(result.toString());
return result;
}
Future<String> readFile(path) async {
return await rootBundle.loadString(filePath);
}
I populated my pubspec.yaml file with this entry:
assets:
- assets/ExerData.json
I expected it to find my file, read it using rootbundle.loadstring(path), and print out the resulting string to the console.
As I say, all it did was print "Can't find file".
I'd very much appreciate you help on this one!
Thanks in advance!
The rootBundle contains the resources that were packaged with the app when it was built. All files specified under assets: in your pubspec are packaged with the app. You can check if file exists by wrapping rootBundle.loadString() inside try{} catch(){} block.
Future<bool> fileExists(String path) async {
try {
await rootBundle.loadString(path);
} catch (_) {
return false;
}
return true;
}
or
Future<String?> loadFile(String path) async {
try {
return await rootBundle.loadString(path);
} catch (_) {
// File not found Exception
return null;
}
}
File is a dart class. It needs absolute or relative path of the file being read.
You can use File with path_provider to get the absolute path from the current File System.
For example on Android:
Future<void> getPath() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
print('PATH IS : $appDocPath');
}
prints
'/data/user/0/com.soliev.file_demo/app_flutter'
Use:
String data = await DefaultAssetBundle.of(context).loadString("assets/ExerData.json");
final jsonResult = jsonDecode(data);
Reference: How to load JSON assets into a Flutter App?
As it turns out, the program logic had not completed initializing the necessary binding.
I called the method WidgetsFlutterBinding.ensureInitialized() in the first line of the main class and everything started working as I expected.
Thanks to everyone who looked at my question!
Here's a similar question involving binding with XML files:
How to read XML files in flutter?
How can I allow the user to save a file to a specific folder in Flutter?
I have built a simple desktop app for Mac that returns a file from an API.
Currently, it saves the file to a caches directory.
try {
io.Directory saveDir = await getTemporaryDirectory();
String filePath = saveDir.path;
io.File returnedFile = new io.File('$filePath/$filename.xlsx');
await returnedFile.writeAsBytes(result.bodyBytes);
print(saveDir);
} catch (e) {
print(e);
}
I played around with my original code and that provided by #Pavel and managed to write my solution to saving files to a custom user-picked directory in this fashion.
The first part opens a file picker dialogue that returns a path to a directory.
The second part provides the path to the File class that then writes the file to that directory.
Hope this helps anyone trying to save files.
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Save Your File to desired location',
fileName: filename);
try {
io.File returnedFile = io.File('$outputFile');
await returnedFile.writeAsBytes(responsefile.bodyBytes);
} catch (e) {}
Use https://pub.dev/packages/file_picker
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Please select an output file:',
fileName: 'output-file.pdf',
);
if (outputFile == null) {
// User canceled the picker
}
I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :
FlatButton(
onPressed: () => {
!isRecording
? {
setState(() {
isRecording = true;
}),
cameraController.prepareForVideoRecording(),
cameraController.startVideoRecording('assets/Videos/test.mp4')
}
: cameraController.stopVideoRecording(),
},
............
but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)).
I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?
In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.
You are trying to save a video in your assets folder which is not possible ,
What you need to do is to save to device locally either common folders like downloads or app directory.
Here is an example of how to go about it
dependencies:
path_provider:
Flutter plugin for getting commonly used locations on host platform
file systems, such as the temp and app data directories.
We will be saving the video to app directory.
We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider
Future<String> _startVideoRecording() async {
if (!controller.value.isInitialized) {
return null;
}
// Do nothing if a recording is on progress
if (controller.value.isRecordingVideo) {
return null;
}
//get storage path
final Directory appDirectory = await getApplicationDocumentsDirectory();
final String videoDirectory = '${appDirectory.path}/Videos';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final String filePath = '$videoDirectory/${currentTime}.mp4';
try {
await controller.startVideoRecording(filePath);
videoPath = filePath;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//gives you path of where the video was stored
return filePath;
}
I'm using Flutter web for a webapp and having trouble converting an image from the image picker to a file in order to upload it to my server. I display the image in Image.file(xxx) but I get the error:
Error while trying to load an asset: FormatException: Illegal scheme
character (at character 6)
Image(image:%20MemoryImage(Uint8List%234267a,%20scale:%201),%20frameBuilder...
Here is the code I'm trying:
Future getImage(bool isCamera) async {
Image image;
if (isCamera) {
image = await FlutterWebImagePicker.getImage;
} else {
}
var bytes = await rootBundle.load('$image');
String tempPath = (await getTemporaryDirectory()).path;
File file = File('$tempPath/profile.png');
await file.writeAsBytes(
bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
setState(() {
currentSelfie = file;
_accDetails['customer_selfie'] = currentSelfie;
});
}
Thanks in advance
I've tested this package and was very happy with the result imagePickerWebit returns 3 different types it can be in the form of Image(widget for preview), byte, File(upload)
then you can use this to get the values
html.File _cloudFile;
var _fileBytes;
Image _imageWidget;
Future<void> getMultipleImageInfos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
if (mediaFile != null) {
setState(() {
_cloudFile = mediaFile;
_fileBytes = mediaData.data;
_imageWidget = Image.memory(mediaData.data);
});
}
I havent used the plugin although your code has 2 issues. One is the if statement and the second one is using Rootbundle. If you are picking from the filesystem, my assumption isCamera would be false. You have not added any logic for the falsy condition.
if (isCamera) {// This would be true if the source was camera
image = await FlutterWebImagePicker.getImage;
} else {
}
Additionally,
var bytes = await rootBundle.load('$image');
From the flutter documentation, rootbundle contains the resources that were packaged with the application when it was built. Those are assets that you define in your pubspec. yaml. You are selecting an image at runtime hence its not bundled as an asset.
Since the package appears to return an image object, use the toByteData method on the image i.e
image = await FlutterWebImagePicker.getImage;
await image.toByteData();//This method has some parameters. Look into them
I have URI LIKE below
content://media/external/images/media/5275
but I want convert it to Like format below:
/storage/emulated/0/DCIM/Camera/IMG_00124.jpg
Anyone who can help me!
Sreng Bona
Thanks!
var path = await FlutterAbsolutePath.getAbsolutePath("content://media/external/images/media/5275");
Add this flutter_absolute_path: ^1.0.6 to your file: pubspec.yaml
It will be working as Well.
Bona SR.
I had to search a lot, but I found a very useful solution to save the image in the cell phone's photo gallery and get the absolute path to use it the way you want.
For this example I used a result obtained from saving an image in the photo gallery, however it could also work to read other files, obviously making the changes that you see necessary, I hope it will help you
uri_to_file
image_gallery_saver
import 'dart:io';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:uri_to_file/uri_to_file.dart';
Future<File> saveImage(File image, String identifier) async {
try {
var result = await
ImageGallerySaver.saveImage(image.readAsBytesSync(),
quality: 60, name: identifier +
"-${DateTime.now().toIso8601String()}");
print(result);
File file = await toFile(Uri.parse(result['filePath']));
print(file);
return file;
} catch (e) {
print(e);
return new File('assets/img/default-img.jpg');
}
}
// example
saveImage(File("path/image.jpg"),"img-test");