Converting of Image File created using image_picker package of flutter to AssetImage/Image.asset? - flutter

I am new to flutter, i am building an app where i need to convert the file(image) generated after using image_picker package to asset image to use in the app.
example code as follows, which creates file(Image)
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Thanks in advance

You can create an image variable which you can rever to and update when you selected the image.
See the following code:
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Image _tempImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
setState(() {
_tempImage = imageFile;
});
}
#override
Widget build(BuildContext context) {
return _tempImage == null ? Container(child:null) : Image(image: _tempImage);
}

Related

How can I upload mutiple-photo in flutter app via ImgePicker

I want to add the function which can upload multiple Photo image via ImagePicker
In this code, I can just upload single photo, not mutiple.
This app operating by flutter, dart and firebase server.
[Code]
void dispose() {
textEditingController.dispose();
super.dispose();
}
File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1000,
maxHeight: 1000,
);
setState(() {
_image = image;
});
}
Future _uploadFile(BuildContext context) async {
if (_image != null) {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().millisecondsSinceEpoch}.png');
final task = firebaseStorageRef.putFile(
_image,
StorageMetadata(contentType: 'image/png'),
);
final storageTaskSnapshot = await task.onComplete;
final downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
}
final images = await _picker.pickMultiImage(
maxHeight: 1024,
maxWidth: 1024,
imageQuality: 50,
);
I created here 3 functions used to pick files from imagePicker and to upload them to firebase storage.
first, pick images from gallery:
final imageFiles = await pickImages();
second, upload the images:
final path = 'path/where/you/want/to/save/your/images';
final imageUrls = uploadImages(imagesFiles, path)
print(imageUrls);
you can now use the images urls to save to firestore
Future<List<File>> pickeImages() async {
ImagePicker picker = ImagePicker();
final images = await picker.pickMultiImage(
maxHeight: 1000, maxWidth: 1000, imageQuality: 90);
List<File> files = [];
if (images == null || images.isEmpty) return [];
for (var i = 0; i < images.length; i++) {
final file = File(images[i].path);
files.add(file);
}
return files;
}
Future<String?> _uploadImageFile(File file, String path) async {
try {
final storage = FirebaseStorage.instance;
TaskSnapshot? taskSnapshot;
final storageRef = storage.ref().child(path);
final uploadTask = storageRef.putFile(file);
taskSnapshot = await uploadTask.whenComplete(() {});
final imageUrl = await taskSnapshot.ref.getDownloadURL();
return imageUrl;
} catch (e) {
throw Exception(e.toString());
}
}
Future<List<String>> uploadImages(
List<File> files,
String path,
) async {
final urls = <String>[];
try {
if (files.isNotEmpty) {
for (var i = 0; i < files.length; i++) {
final file = files[i];
final imagePath = '$path/${Random().nextInt(10000)}.jpg';
final url = await _uploadImageFile(file, imagePath);
urls.add(url!);
}
}
return urls;
} on FirebaseException {
rethrow;
}
}
Instead of using ImagePicker.pickImage, use ImagePicker.pickMultiImage. That gives you a List instead of an XFile. Then you can just upload all images in the list. For instance, add an image parameter to your _uploadFile Function so that its function signature is
Future _uploadFile(BuildContext context, XFile image)
and just upload all images like
for (final image of images) {
_uploadFile(context, image)
}

Flutter image_gallery_saver image not-showing after saving

I want to take a screenshot of my widget. For that, I am using the RepaintBoundary widget and to save the screenshot I use the image_gallery_saver plugin. But after saving the image it is not showing to the gallery. How to solve this issue?
class Utils {
static Future capture(GlobalKey key) async {
DateTime now;
now = DateTime.now();
if (key == null) return null;
final RenderRepaintBoundary boundary =
key.currentContext.findRenderObject();
final image = await boundary.toImage(pixelRatio: 3.0);
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final pngByte = byteData.buffer.asUint8List();
// print(pngByte);
if (!(await Permission.storage.status.isGranted)) {
await Permission.storage.request();
}
final result = await ImageGallerySaver.saveImage(
Uint8List.fromList(pngByte),
quality: 90,
name:
'Screeshoot_${now.day.toString()}${now.hour.toString()}${now.minute.toString()}${now.second.toString()}');
return result;
// return pngByte;
}
}
I have done the same in my app but I have used the GallerySaver package instead.
First I have created a method that returns me the path where the image is located and then I use GallerySaver to save the image file.
Future<String> getImagePath() async {
RenderRepaintBoundary boundary = _renderQRandImageWidgetKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDirectory = (await getTemporaryDirectory()).path;
final String filePath = '$tempDirectory/MyQRCode.png';
File imgFile = new File('$filePath');
await imgFile.writeAsBytes(pngBytes);
return filePath;
}
_saveImage(String userName) async {
try {
String filePath = await getImagePath();
bool isImageSaved = await GallerySaver.saveImage(filePath, albumName:"AlbumName");
SnackBar _snackbar = SnackBar(
content: isImageSaved ? Text('Image saved in gallery') : Text("There was an error while saving image"),
duration: const Duration(seconds: 1),
);
_scaffoldKey.currentState.showSnackBar(_snackbar);
} catch (exception) {
print("Error $exception");
SnackBar _snackbar = SnackBar(
content: Text('Something went wrong'),
duration: const Duration(seconds: 1),
);
_scaffoldKey.currentState.showSnackBar(_snackbar);
}

How can I cast an Image object to a File object in flutter?

I am attempting to cast an Image to a File in Flutter. Is there a method for this?
This is how to pick an image as a file
File _image;
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
}
Also We can convert this image as Bytestream
var convertedImage;
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
convertedImage = await pickedFile.readAsBytes();
convertedImage = await decodeImageFromList(convertedImage);
setState(() {
convertedImage = convertedImage;
});
}
Hope this helps!

How to copy the path of image and store it in? Error:- The method copy isnt defined fo type 'PickedFile'

This is the error when using the copy function. How do I save the image clicked from the camera?
Future _takePicture() async {
final imageFile = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 600,
);
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
}
you should copy _storedImage instead of imageFile
imageFile type is PickedFile and hasn't copy method
Future _takePicture() async {
final imageFile = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 600,
);
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await _storedImage.copy('${appDir.path}/$fileName');
}

Convert Uint8List to File

I'm using Image Picker web which works well. I can display image in Image.memory(), but this image in format Uintlist8. For save in storage need format File, my issue is how to save an image in Firebase Storage.
Web image picker:
class _SecondPageState extends State<SecondPage> {
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
});
}
}
Please Try ....
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.jpg').create();
file.writeAsBytesSync(_image);
});
}
}