I want to delete the captured image via wechat_camera_picker Flutter - flutter

For image_picker MainActivity destruction I wanted to use other plugin to pick image. And I found wechat_camera_picker as an alternative. But there was a problem while capturing the image. The captured image saved on Local Storage after selecting the image. Here is my code.
Future<File> getImageByCamera(BuildContext context) async {
try{
final AssetEntity result = await CameraPicker.pickFromCamera(
context,
pickerConfig: CameraPickerConfig(
shouldDeletePreviewFile: true,
enableRecording: false,
textDelegate: EnglishCameraPickerTextDelegate(),
),
);
if(result != null){
File pickedFile = await result.file;
pickedFile = await compressFile(pickedFile);
return pickedFile;
}else{
return null;
}
}catch(error){
print(error);
return null;
}
}
Does anyone have any solution of this problem?

you can use the below function to delete the locally stored file.
Future<bool> deleteFile(File pickedFile) async {
try {
await pickedFile.delete();
return true;
} catch (e) {
return false;
}
}
You can check the Delete Function Documation for referenece.

Related

Encode image to photobase64

I am encoding the image to photobase64 but I am only getting parts of the image. The encoded code given to me is not the full code.
Future pickGallery() async {
try {
final pickedImage = await ImagePicker().pickImage(
source: ImageSource.gallery,
);
if (pickedImage != null) {
image = File(pickedImage.path);
List<int> photobytes = await image!.readAsBytes();
setState(() {
String photobase = convert.base64Encode(photobytes);
print(photobase);
});
} else {
Utils.showAlertSnackBar('No image selected.');
}
} on PlatformException catch (e) {
print('Failed to pick image: $e');
}
}
This encoded code below gave me this result.
iVBORw0KGgoAAAANSUhEUgAAASUAAAFACAYAAAD6XmqeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAGIHSURBVHhe7Z0HYBzF3fafu1PvvXfbkuXeewFiU4LpPUBoIUASUkheUnkLpEBIQhL4SEgIIcEECBCaDQbj3rssF9mSrN5779J+86zvzPl0dzpJd7qVPb9k8Glvd3ZmduaZ/8z+b0anCCCRSCQaQW/8VyKRSDSBFCWJRKIppChJJBJNIUVJIpFoCilKEolEU0hRkkgkmkKKkkQi0RRSlCQSiaaQoiSRSDSFFCWJRKIppChJJBJNIUVJIpFoCilKEolEU0hRkkgkmkKKkkQi0RRSlCQSiaZw+SJvF+sacjqdzvjJdThato6kZai4nBHHhchYPOeLDZeKEqPu7+9HX1+f8cjFgcFggKenp/Ev18FyHRgYUIM12GD0er2aHv5rC17f29trV1SYH8ZjC0fiuNBgmXp4eNgtW8nwcZkoMdru7m7k5ubi1KlT6t/2KvWFABsmRXjSpEmYN2+e8ahroADk5+ejvLwcLS0tqkCZGofpkfr6+iIiIgITJ05U/7VFVVUV9u3bh46OjkFiynh5bP78+UhKSjIeHUxlZaUaR2dn55gIsrth+bNMZ8+ejbCwMClMTsRlosQG2tDQgBdeeAF//OMf1b99fHyM316YsAGzYX/961/Hc88951LTvrW1FS+//DI+/vhjVfTNBYVlzRAfH4+FCxfia1/7GhYsWKB+Z42tW7eqaS4rK0NQUJDx6Fna2toQEhKCP/zhD7jpppuMRwfz+eef4+GHH0ZFRcWgOC5EmpubsWjRIjz99NOYO3euajFJnARFyRUIi0ERPbDyjW98g6J3UYXbbrtNEaJgLAnX0NTUpPz0pz9VhFVmNQ0MAQEBypo1axQhOsarrLNu3TpFCKjVOEzh73//u/Fs67z//vtWr7uQQ0pKirJlyxalp6fHWAoSZ+B
I solved it. Using print() gives limited results. Therefore, I used log() to show the full the photobase64 code.

Delete file permanantly from list view in flutter

I list all pdf files from storage and now I want to delete multi-files in my flutter list . as well as from the device file manager. I am using this function but when I delete and restart the app the file comes again
This is the function I'm using to delete the list:
void deleteItems() {
var list = myMultiSelectController.selectedIndexes;
list.sort((b, a) => a.compareTo(b));
list.forEach((element) {
files.removeAt(element);
});
setState(() {
myMultiSelectController.set(files.length);
});
}
files.removeAt(element); Just removes file from the list. You need to actually delete file from device.
eg
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print('path ${path}');
return File('$path/counter.txt');
}
Future<int> deleteFile() async {
try {
final file = await _localFile;
await file.delete();
} catch (e) {
return 0;
}
}
See more here from SO answer

how to handle the time lag after capturing the image ImagePicker Flutter

im learning flutter and now tried to capture the photo with ImagePicker package from the following method, but after I successfully capture the photo, there is always 1 sec until app get the data and jump to next page:
Future pickImage(ImageSource source) async {
try {
var image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final imagePermanent = await saveImagePermanently(image.path);
selectedImage = File(imagePermanent.path);
isUploaded.value = !isUploaded.value;
update();
} on PlatformException catch (e) {
print('Failed to pick image: $e');
}
}
Future<File> saveImagePermanently(String imagePath) async {
final directory = await getApplicationDocumentsDirectory();
final name = basename(imagePath);
final image = File('${directory.path}/$name');
return File(imagePath).copy(image.path);
}
now my solution is adding a listener onInit when image is created with GetX:
#override
void onInit() {
super.onInit();
ever(isUploaded, (value) {
Get.to(
() => AddPersonProfileAddDetails(),
);
});
}
So is there a way to detect the status of capturing the image like finished/failed/progressing, thanks for any clue or let me know a better way to jump to next page after capturing the image, thanks a lot!

What is the right way of reducing image size captured from flutter camera plugin

I am using the example code from Flutter Camera Plugin. I want to reduce Image size once I capture the image and store it in imageFile variable.
I am not sure is there a built in feature available. didn't find any information in their documentation.
I tried to use Image Plugin to achieve it like below. but it is not working. the entire application stops it function when you use it.
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
XFile resizeImage(img) {
var image = imageP.decodeJpg(File(img.path).readAsBytesSync());
var thumbnail = imageP.copyResize(image, width: 400);
File(img.path).writeAsBytesSync(imageP.encodeJpg(thumbnail));
return XFile(img.path);
}
There is a bug in Image Package.... I used flutter_native_image Package and it worked....
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
here is the image compression function code.
Future<XFile> resizeImage(img) async {
ImageProperties properties =
await FlutterNativeImage.getImageProperties(img.path);
File compressedFile = await FlutterNativeImage.compressImage(img.path,
quality: 90,
targetWidth: 500,
targetHeight: (properties.height! * 500 / properties.width!).round());
// delete original file
try {
if (await img.exists()) {
await img.delete();
}
} catch (e) {
// Error in getting access to the file.
}
return XFile(compressedFile.path);
}

iOS app crashes when calling this function 2 times in a row (Firebase Storage, Flutter)

My app crashes when calling "_submit" function 2 times in a row.
I can pick the picture from gallery and upload it to Firebase Storage but if I call it again the the whole app crashes.
From this button :
floatingActionButton: FloatingActionButton(
onPressed: () => _submit(),
Submit calls a Provider of type Database :
Future<void> _submit() async {
widget.database = Provider.of<Database>(context, listen: false);
await widget.database
.setPicture("regione/citta/comune/lavoro/IDArtista/profilo.png");
return;
}
That calls a function that uploads a picture taken from "imgGallery()" to the database :
Future<void> setPicture(String pathStorage) async {
try {
final File file = await imgFromGallery();
if (file == null) return;
TaskSnapshot task =
await FirebaseStorage.instance.ref(pathStorage).putFile(file);
String image_url = await task.ref.getDownloadURL();
return;
} catch (e) {
print(e);
return;
}
}
imgGallery :
Future<File> imgFromGallery() async {
try {
final ImagePicker _picker = ImagePicker();
final PickedFile imageFile =
await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
//If there is no image selected, return.
if (imageFile == null) return null;
//File created.
File tmpFile = File(imageFile.path);
//it gives path to a directory - path_provider package.
final appDir = await getApplicationDocumentsDirectory();
//filename - returns last part after the separator - path package.
final fileName = tmpFile.path.split('/').last;
//copy the file to the specified directory and return File instance.
return tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
} catch (e) {
print(e);
return null;
}
}
EDIT : Solved using a real device instead of emulators.
Which device are you experiencing this in? I'm also having this error but only on iOS emulator. It has to do with the Image_Picker package and the FocusNode. Look at this issue on github