Flutter save Image in Gallery folder - flutter

I am currently working on an alert box with the option to take a photo or select a picture from the gallery.
The status so far is:
I can get pictures from the gallery with the ImagePicker, this works perfectly.
Now I come to my problem:
Saving the captured images also works, but it is saved in the storage and therefore not displayed in the gallery. Please help me
Image AlertBox: https://imgur.com/a/IhZ5Sgh
Image Empty rencent folder
https://imgur.com/a/W3FvPtS
Made pictures: https://imgur.com/a/VIZOTBH
Here is the path where the image is stored:
File: '/storage/emulated/0/Android/data/com.example.supportanfrage/files/Pictures/1cd284f4-3632-4ed8-8c6a-14d7be83a8335698897692938961258.jpg'
Methode for saving images
Future getAndSaveImage() async {
final File image = await ImagePicker.pickImage(source: ImageSource.camera);
debugPrint(image.toString());
if (image == null) return;
final directory = await getExternalStorageDirectory();
final String path = directory.path;
this._fileName = path;
final File localImage = await image.copy(path);
}
I using the following dependencies / plugins:
file_picker: ^1.3.8
camera: ^0.5.2+2
image_picker: ^0.6.0+17
image_gallery_saver: ^1.1.0
path_provider: ^1.1.2
Thanks.

This is the sample source code provided for the flutter camera plugin. It will take timeStamp and then save your photo with the name of that timeStampValue.jpg in your phone storage.
Future<String> takePicture() async {
if (!controller.value.isInitialized) {
return null;
}
String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
final Directory extDir = await getApplicationDocumentsDirectory();
final String dirPath = '${extDir.path}/Pictures/flutter_test';
await Directory(dirPath).create(recursive: true);
final String filePath = '$dirPath/${timestamp()}.jpg';
if (controller.value.isTakingPicture) {
return null;
}
try {
await controller.takePicture(filePath);
} on CameraException catch (e) {
return null;
}
return filePath;
}

Related

Saving image permenantly after user upload it in flutter

In my flutter app, if the user is signing in for the first time, he will be directed to profile page where he gets to key in his personal details and upload his profile pic. now my issue is with the profile pic. First of all, Im using Image picker package.
Future pickImage(ImageSource source) async {
try {
final image = await ImagePicker().pickImage(
source: source);
if (image == null) return;
final UserImage = File(image.path);
setState(() => this.image = UserImage );
}on PlatformException catch (e){
Utils.showSnackBar(e.message);
}
}
But with this code alone, everytime the app gets restarted the image will be null. So I tried to upload the image to the Firebase Storage when the user picks an image and generate a url:
Future uploadImage () async {
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child(userID.toString());
UploadTask uploadTask = ref.putFile(image!);
uploadTask.whenComplete(() async {
url = await ref.getDownloadURL(); }
).catchError((onError){
print(onError);
});
return url;
}
But again every time I restart the app, the url will be null.
What is the best way to save the image permenantly when the user signs in for the first time.
edit: I want to store the image locally so that the user doesnt need an internet connection to load the image everytime he open the app.
Your answers and responses are highly appreciated.
you need to get folder directory first
Future<String> getStorageDirectory() async {
if (Platform.isAndroid) {
return (await getExternalStorageDirectory()).path;
} else {
return (await getApplicationDocumentsDirectory()).path;
}
}
Add image in path
uploadImage() async{
String dir= getStorageDirectory();
File directory = new File("$dir");
if (directory.exists() != true) {
directory.create();
}
final image = await ImagePicker().pickImage(
source: source);
if (image == null) return;
final userImage = File(image.path);
var newFile = await userImage.writeAsBytes(/* image bytes*/);
await newFile.create();
}

Image is not saving on mobile device after taking picture with camera package

I am trying to save an image to my local mobile device when I use this code from the pub.dev example page of the camera package. However I am not finding the file saved on the device. Can anyone please help me with how to save the image taken to a given path
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) {
showInSnackBar('Picture saved to ${file.path}');
}
}
});
}
Using await ImagePicker.pickImage(...), you are already on the right track because the function returns a File.
The File class has a copy method, which you can use to copy the file (which is already saved on disk by either the camera or by lying in gallery) and put it into your application documents directory:
// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});
You should also note that you can get the path of the image file from ImagePicker using image.path, which will also contain the file ending that you might want to extract and you can save your image path by using newImage.path.
You can use path provider and save the images like this
https://pub.dev/packages/path_provider
final XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final String newFile = await getApplicationDocumentsDirectory().path;
final var fileName = basename(file.path);
final File localImage = await image.saveTo('$newFile/$fileName');

Is there a way to download folder from firebase storage with flutter?

I want to download .epub files from firebase storage. I can download image file cause I know imageUrl but not .epub file url. How should I do? I store fileName, imageUrl in Firestore but I don't know epub file's url . So I can't store it.
downloadFile(fileName,imageUrl) async{
Dio dio=Dio();
final storageRef=FirebaseStorage.instance.ref();
final imageUrls =await storageRef.child("Featured").child('a clock orange/Anthony-Burgess-A-Clockwork-Orange-W.-W.-Norton-_-Company-_1986_.epub').getDownloadURL();
String savePath= await getPath(fileName);
dio.download(imageUrls, savePath,
onReceiveProgress: (rcv,total){
setState((){
progress=((rcv/total) *100).toStringAsFixed(0);
});
if (progress == '100') {
setState(() {
isDownloaded = true;
});
}
}).then((_){
if (progress=="100"){
setState(() {
isDownloaded=true;
});
}
});}
I tried this. But it didn't work.
.
Use Firebase's writeToFile instead of dio's download.
final fileRef = storageRef.child("<path here>");
final appDocDir = await getApplicationDocumentsDirectory();
final filePath = "${appDocDir.absolute}/<path here>";
final file = File(filePath);
final downloadTask = fileRef.writeToFile(file);
downloadTask.snapshotEvents.listen((taskSnapshot) {
...
}
See Download to a local file for details.

How to get Download URL from Firebase Storage in flutter

The Following Code is used to Upload any image from gallery/Camera to Firebase storage. I was successful in uploading the image to storage along with meta data. Now the problem is I am not able to get the download URL of the uploaded image. Tried a lot but didn't find any solution.
FirebaseStorage storage = FirebaseStorage.instance;
final picker = ImagePicker();
PickedFile pickedImage;
File imageFile;
Future<void> _upload(String inputSource) async {
try {
pickedImage = await picker.getImage(
source: inputSource == 'camera'
? ImageSource.camera
: ImageSource.gallery,
maxWidth: 1920);
final String fileName = path.basename(pickedImage.path);
imageFile = File(pickedImage.path);
try {
// Uploading the selected image with some custom meta data
await storage.ref(fileName).putFile(
imageFile,
SettableMetadata(
customMetadata: {
'uploaded_by': 'A bad guy',
'description': 'Some description...'
},
),
);
// Refresh the UI
setState(() {});
} on FirebaseException catch (error) {
print(error);
}
} catch (err) {
print(err);
}
}
Hope You're Doing Well …
You Can Try This Method To Get The URL Of The Image(Any File) From Firebase Storage To Firebase Store And Then You Can Retrieve Image .
class _UploadAdState extends State<UploadAdPage> {
final formKey = GlobalKey<FormState>();
File _myimage;
String imgUrl;
Future getImage1(File chosenimage) async {
PickedFile img =
await ImagePicker.platform.pickImage(source: ImageSource.gallery);
if (chosenimage == null) return null;
File selected = File(img.path);
setState(() {
_myimage = chosenimage;
});
}
// changing the firestore rules and deleteing if request.auth != null;
sendData() async {
// to upload the image to firebase storage
var storageimage = FirebaseStorage.instance.ref().child(_myimage.path);
UploadTask task1 = storageimage.putFile(_myimage);
// to get the url of the image from firebase storage
imgUrl1 = await (await task1).ref.getDownloadURL();
// you can save the url as a text in you firebase store collection now
}
}
I am using in my app this function. Pass image file and download with getDownloadUrl .
Future <String> _uploadphotofile(mFileImage) async {
final Reference storageReference = FirebaseStorage.instance.ref().child("products");
UploadTask uploadTask = storageReference.child("product_$productId.jpg").putFile(imgfile);
String url = await (await uploadTask).ref.getDownloadURL();
return url;
}

Flutter form builder package image picker firestore flutter

i am using FormBuilderImagePicker from package Flutter form builder
I want to use the img path but i am not able to do so
sending() async {
var storageimage =
FirebaseStorage.instance.ref().child('/google/google');
var task = storageimage.putFile();
imgurl = await (await task.onComplete).ref.getDownloadURL();
// await Firestore.instance.collection('twst').add(
// {
// 'img': imgurl.toString(),
// },
// );
}
i want to use that function with the imagepicker
but the problem is i am not able to find path to use putfile
To get the path of the FormBuilderImagePicker, the toString() method of the class prints the path.
Here is an example of how you can print in a container the Text field including FormBuilderImagePicker which have the path.
Then you will need to pass the image or file to the putFile method.
You can also use the ImagePicker pickImage class method to get the file.
sending() async {
File image;
try {
//Get the file from the image picker and store it
image = await ImagePicker.pickImage(source: ImageSource.gallery);
// Throws error when you don't select any image or when you don't have permissions
} on PlatformException catch (e) {
return;
}
//Create a reference to the location you want to upload to in firebase
StorageReference reference = FirebaseStorage.instance.ref().child("/google/google");
//Upload the file to Firebase
StorageUploadTask uploadTask = reference.putFile(image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// Waits till the file is uploaded then stores the download URL
String url = await taskSnapshot.ref.getDownloadURL();
}