Issue downloading images using image_downloader package - flutter

So, I have been successful in downloading an image from a firebase URL and storing it in the device, The issue that I am facing is that it also downloads a file with the same name as the downloaded image, but without file type.
Example, downloading Image.jpg will also download a file named Image, and it is visible within the device.
saveImage(Message message) async {
String url = message.photoURL;
try {
var imageId = await ImageDownloader.downloadImage(
url,
destination: AndroidDestinationType.custom(directory: 'exampleDir'),
);
if (imageId == null) {
return;
}
setState(() {
SnackBar snackBar = SnackBar(
content: Text('Image Saved!'),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds: 2), () {});
});
if (imageId == null) {
return;
}
} on PlatformException catch (error) {
print(error);
}
}
Any suggestions?
Thanks

Related

How I can save each image in different folder for each click in flutter?

I am using gallery_saver package for saving image.
I want when I press the capture button Image will save different folder for each click. How I can archive it? Please help me.
Save Image method here:
CameraController? controller;
void _takePhoto() async {
try {
if (controller != null) {
if (controller!.value.isInitialized) {
image = await controller!.takePicture();
try{
GallerySaver.saveImage(image!.path);
} catch(e) {
Fluttertoast.showToast(msg: "Image not saved" + e.toString());
}
}
}
} catch (e) {
print(e); //show error
}
}
Copy file data to another location
And give that file to gallery saver.
CameraController? controller;
void _takePhoto() async {
try {
if (controller != null) {
if (controller!.value.isInitialized) {
XFile? image = await controller!.takePicture();
// Read file and save it to new location
final buffer = await image.readAsBytes();
await new File(<newPath>).writeAsBytes(buffer);
// Give that new path to Gallerysaver
try{
GallerySaver.saveImage(<newPath>);
} catch(e) {
Fluttertoast.showToast(msg: "Image not saved" + e.toString());
}
}
}
} catch (e) {
print(e); //show error
}
}

How to send Images through Multipart in Flutter

I want to send three images to my server. I have tried following. There are no errors, no exception but I can't send pictures to the server. Can you help me where I am making the error?
File? image1;
I am picking images from gallery
Future pickImage1() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery,imageQuality: 75);
if (image == null) return;
final imagePermanent = await saveImagePermanently(image.path);
setState(() => image1 = imagePermanent);
} on PlatformException catch (e) {
print('failed to pick image $e');
}
}
It's how I am trying to send images to the server
uploadImage1(File imageFile1,File imageFile2, File imageFile3 ) async {
var postUri = Uri.parse("https://my link");
var request = http.MultipartRequest('POST', postUri);
request.files.add( http.MultipartFile.fromBytes("image1", imageFile1.readAsBytesSync(), filename: "Photo1.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image2", imageFile1.readAsBytesSync(), filename: "Photo2.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image3", imageFile1.readAsBytesSync(), filename: "Photo3.jpg", ));
await request.send().then((response) {
if (response.statusCode == 200)
{
print("Uploaded");
}
else {
print('error');
}
});
}
what I got in my console is
error
Here is the button where I call this function
ElevatedButton(
onPressed: () {
uploadImage1(image1!, image2!, image3!);
print('pressed');
},
child: const Text(' upload '),
),
Do not use both await and then together. Just use await to wait for the execution of the asynchronous function to finish.
final response = await request.send();
if (response.statusCode == 200) {
print("Uploaded");
} else {
print('error');
}
I have a sample code that uploads local images to Pl#nNet, it can be of any help to you, the output for that sample code is like this:
Start fetching...
Fetching done!
{query: {project: all, images: [dc5f659df9a4bcf90fc109830564d821], organs: [leaf],
...
{id: 6411486}}], version: 2022-02-14 (5.1), remainingIdentificationRequests: 197}
Done!

I want to delete the captured image via wechat_camera_picker 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.

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