Flutter Image form Image Picker to Document Path - flutter

I am creating an app that saves images locally through sqflite, I have soon found out that the images are being saved as temp which means that it will be deleted by the device and i'm not able to retrieve those images anymore. I have been coding to save it to the document directory of the app but it seems to fail and throw error
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot copy file to '/data/user/0/com.example.e4psmap/cache/scaled_0d5d5070-70da-4f42-9055-c31a6ed8d3d51761448072222030817.jpg', path = '/data/user/0/com.example.e4psmap/app_flutter/scaled_0d5d5070-70da-4f42-9055-c31a6ed8d3d51761448072222030817.jpg' (OS Error: No such file or directory, errno = 2)
this is my code:
void getpic(ImageSource src) async{
Uint8List byte;
final picfile = await _imagepicker.getImage(
source: src, imageQuality: 25
);
if(picfile != null){
Directory appDir = await getApplicationDocumentsDirectory();
String appdoc = appDir.path;
final filename = path.basename(picfile.path);
final local = File('${appdoc}/$filename');
final lclfile = await local.copy(picfile.path);
}
// converted = picfile!.path;
// setState(() {
// _imgfile = picfile!;
// });
Navigator.pop(context);
}
Anyone knows why I am having this errors, and any fix for this error, Thank you

The copy() function expects the source file to be passed as an argument, but in your code, you're passing picfile.path instead of the File object.
try to replace local.copy(picfile.path) with picfile.saveTo(local.path), which should save the image to the desired directory.

If you replace final with the corresponding class, the error will be very obvious.

Related

How to upload an image from assets folder to server in flutter?

I need to let user pick an image from assets/images directory, I did it.
now i need to upload image selected to backend guy, i used this snap of code to convert asset path to file :
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
I test the file in this line
final file = File('${(await getTemporaryDirectory()).path}/$path');
and got this as file path:
'/data/user/0/com.mohra.app/cache/assets/images/svg/dream_icons/dream-icon-9.png'
but error i got in this line :
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
the error is :
Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.mohra.app/cache/assets/images/svg/dream_icons/dream-icon-9.png' (OS Error: No such file or directory, errno = 2)
any one can help how to create file from assets path ??

In file picker in flutter, path was not unique

I'm trying with two different images with same name. But the path was same for two picked images. it was not unique.So that I uploaded in server second image with the same name of first uploaded image. But server had both the image are same and it had first image. So how to handle this case and customize the path?
You can use the path_provider to define the customize directory on your app.
So, copy the file with your customize path and rename the file name.
BTW, do NOT save the absolute path of File on iOS.
The iOS use SandBox to access the file. When you get the file path every time. The file path will be different.
class FileUtils {
final String avatarPath = '/avatar/';
Future<String> getAvatarDirectoryPath() async {
final String appDirPath = await getApplicationSupportDirectory().path;
final Directory avatarDirPath = await Directory(appDirPath + avatarPath).create();
return directory.path;
}
}
// Example
{
final XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
final File imageFile = File(image.path);
final File newFile = File(await FileUtils().getAvatarDirectoryPath() + 'userAvatar.png');
await imageFile.copy(newFile.path);
}

Converting Image FlutterWebImagePicker Output to File

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

How correcty evict image cache?

I'm trying to evict the image cache before take a picture, but it doesn't work and I cannot reupdate an image with the same name because it gives me cache error that the file already exists.
Directory pathCache;
String pathFile;
pathCache = await getTemporaryDirectory();
pathFile = pathCache.path+"/"+profilo+'.jpg';
print(pathFile);
try {
bool res =imageCache.evict(pathFile);
print("eviction result : $res");
imageCache.clear();
}
catch(e) {
print(e.toString());
}
try {
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Construct the path where the image should be saved using the
// pattern package.
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
profilo+'.jpg',
);
// Attempt to take a picture and log where it's been saved.
await _controller.takePicture(path);
What I'm missing?
Thanks
You are trying to clear only the cache, but the file still exists. You need to do:
Remove the old file (from the temporary directory)
Clear the cache
Take the new picture
File pictureFile = File(path);
if (pictureFile.existsSync()) {
pictureFile.deleteSync();
imageCache.clear();
}
...
await _controller.takePicture(path);

In Flutter, How to detect the completion of copying file?

I am beginner on Flutter.
I want to do this process,,,
1. save a image file.
2. read the property information of the saved image file.
below is the code for it.
// save a image file.
String mainDir = await getMainDirectory(widget.topic);
String path = mainDir + '/' + count.toString();
image.copy(path);
ImageProperties properties;
try {
// get the property information of the image file.
properties = await FlutterNativeImage.getImageProperties( path);
}
on PlatformException catch(e) {
print( e );
// try again ...
properties = await FlutterNativeImage.getImageProperties(
path);
}
When this code running, sometimes an error is occurred.
the error message is "file is not exist".
So, I have to call "getImageProperties()" function again, and I can get the property.
If I can detect the completion of the file copy, I can make these code better.
Is there any suggestion ?
You can use await to make sure image copy finish
final File newImage = await image.copy(path);