Saving Flutter image from gallery with ImagePicker - flutter

I have this function to save image from gallery and display it as a background:
Future _getImage() async {
// ImagePicker picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
if (pickedFile == null) return;
File tmpFile = File(pickedFile.path);
tmpFile = await tmpFile.copy(tmpFile.path);
setState(() {
if (pickedFile != null) {
//_image = File(pickedFile.path);
_image = tmpFile;
print('_image: $_image');
} else {
print('No image selected');
}
});
}
but after I invoke it, it says that the image is empty:
File: '/data/user/0/com.app.flutter/cache/image_picker5156338879856055740.jpg' is empty and cannot be loaded as an image.
I'm not sure what's happening here, since it prints the image in the console fine like this:
_image: File: '/data/user/0/com.app.flutter/cache/image_picker5156338879856055740.jpg
so it means that it is in the cache, but for some reason it returns as empty and won't add the image to the background:
decoration: BoxDecoration(
image: DecorationImage(
image: _image == null
? MemoryImage(kTransparentImage)
: FileImage(_image),
fit: BoxFit.cover,
added the build just in case there is an error there, but I don't think there is. Basically I just need the image from gallery to be persistent and stay in the app.
EDIT: Added the setState() to the code, but it is still not persistent, there must be something I'm missing:
Future _getImage() async {
// ImagePicker picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
if (pickedFile == null) {
return null;
}
Directory appDirectory = await getApplicationDocumentsDirectory();
File newImage = File(appDirectory.path + 'fileName');
newImage.writeAsBytes(File(pickedFile.path).readAsBytesSync());
setState(() {
_image = newImage;
print(newImage.path + ' test');
});
}

Try this
Future _getImage() async {
ImagePicker picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.gallery);
if (pickedFile == null) {
return null;
}
Directory appDirectory = await getApplicationDocumentsDirectory();
File newImage = File(appDirectory.path + 'fileName');
await newImage.writeAsBytes(File(pickedFile.path).readAsBytesSync());
setState(() {
_image = newImage;
});
}

Nevermind, I managed to make it persistent with SharedPreferences, I simply made two different functions, each to save or load the image, and added _loadImage() to initState
void _saveImage(path) async {
SharedPreferences saveImage = await SharedPreferences.getInstance();
saveImage.setString('imagepath', path);
print('Image Saved!');
void _loadImage() async {
SharedPreferences saveImage = await SharedPreferences.getInstance();
setState(() {
_imagepath = saveImage.getString('imagepath');
});
}

Related

flutter: How to show the image uploading progress bar in notification Tray of the image user is uploading

i am uploading image to Firebase storage, so i want to show the progress in the notification Tray....
Future<bool> imageBannerPick(BuildContext context, ImageSource source) async {
final pickedFile = await picker.pickImage(source: source);
if (pickedFile == null) {
return false;
}
File image = File(pickedFile.path);
String uploadString = await uploadingFile(uploadFile: image);
//storing the string to your profile
await firestore.collection('users').doc(auth.currentUser?.uid).update({
'backBannerPicture': uploadString,
});
return true;
}
now my problem how to show the progress of the uploading in the notification tray...

Can't get image file through image picker in flutter

i can't get images file through image picker in flutter.
void _getImage() async {
print("getImage");
final ImagePicker picker = ImagePicker();
XFile? image = await picker.pickImage(source: ImageSource.gallery);
print(image);
}
and error's occur, look at this
enter image description here
my enviroment is M1 pro, ios15.2
Try this
_getImage(BuildContext context) async {
var picture = await ImagePicker().pickImage(source: ImageSource.gallery);
setState(() {
imageFile = File(picture!.path);
dirPath = picture.path;
print('path');
print(dirPath);
});
}

Image Picker Flutter and Progress Indicator

I have implmented image picker, it is working great on both ios and android.
However, after i have captured an image, it is taking quite long for it to appear on my Image.file(image) widget.
I cannot decrease the quality of image, as it matters in the app.
So i need something like CachedNetworkImage but to load from file, not from internet, any ideas?
I just want to show an progress bar or indicator, just to let the user know that there is a process.
File? image;
Future pickImage(ImageSource source, BuildContext context) async {
try {
final image = await ImagePicker().pickImage(source: source);
if (image == null) return;
var imageTemporary = File(image.path);
if (source == ImageSource.camera) {
final img.Image? capturedImage =
img.decodeImage(await File(image.path).readAsBytes());
final img.Image orientedImage = img.bakeOrientation(capturedImage!);
imageTemporary =
await File(image.path).writeAsBytes(img.encodeJpg(orientedImage));
}
setState(() {
this.image = imageTemporary;
});
} on PlatformException catch (e) {print(e.toString());}
}
Thats my function to call image picker.
And passing it to ElevatedButton like:

Compress muliple images from JPG to PNG

I have done a single image selected from gallery conversion from JPG to PNG now I want to convert multiple images selected from the gallery below is the code for single image conversion
getImages() async {
var _image;
// Use the getImage() method from the image_picker package
final _pickedImage = await ImagePicker.pickImage(source: ImageSource.gallery);
final pickedFile = decodeImage(File(_pickedImage.path).readAsBytesSync());
setState(()async {
if (pickedFile != null) {
final output = await getExternalStorageDirectory();
var destination = '${output.path}/test_image$index.png';
index = index + 1;
// Convert your image to PNG using the encodePng method from the image package
_image = File(destination)..writeAsBytesSync(img.encodePng(pickedFile));
print("_image");
GallerySaver.saveImage(_image.path, albumName: 'Image Resizer')
.then((bool success) {
Fluttertoast.showToast(
msg: "Image saved",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
});
print(_image.toString());
} else {
print('No image selected.');
}
return _image;
});
}

App crashes when back button press while picking Image

My flutter app crashes when pressing of back button while picking an image.How can I solve that?
Here is Image picking part
_openGallery(BuildContext context) async{
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
this.setState((){
imageFile = picture;
});
if (picture==null) {
Navigator.of(context).pop();
} else{
final File newImage = await imageFile.copy('$_localPath/name.jpg');
}
Navigator.of(context).pop();
}