How to convert asset image to File?
You can access the byte data via rootBundle
. Then, you can save it to the device's temporary directory which is obtained by path_provider
(you need to add it as a dependency).
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
In your example, you would call this function like this:
File f = await getImageFileFromAssets('images/myImage.jpg');
For more information on writing the byte data, check out this answer.
You will need to await
the Future
and in order to do that, make the function async
:
RaisedButton(
onPressed: () async => showDialog(
context: context,
builder: (_) => Container(child: Image.file(await getImageFileFromAssets('images/myImage.jpg')))),
child: Text('Show Image'));
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”
======
List <File> fileImageArray = [];
assetArray.forEach((imageAsset) async {
final filePath = await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier);
File tempFile = File(filePath);
if (tempFile.existsSync()) {
fileImageArray.add(tempFile);
}
Get File from Asset without providing a path.
import 'package:path_provider/path_provider.dart';
Future<File> getImageFileFromAssets(Asset asset) async {
final byteData = await asset.getByteData();
final tempFile =
File("${(await getTemporaryDirectory()).path}/${asset.name}");
final file = await tempFile.writeAsBytes(
byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes),
);
return file;
}