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

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');
}

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 Google-Ml-Kit-plugin - FaceDetector not working in iPhone cameras

If we take photos in iPhone
final XFile? image = await picker.pickImage(
source: ImageSource.camera,
maxWidth: 300,
maxHeight: 300,
preferredCameraDevice: CameraDevice.front,
);
final List faces = await faceDetector.processImage(inputImage);
always give empty list
final FaceDetector faceDetector = FaceDetector(
options: FaceDetectorOptions(
enableTracking: true,
enableContours: true,
enableClassification: true,
enableLandmarks: true,
performanceMode: FaceDetectorMode.accurate));
final inputImage = InputImage.fromFilePath(image.path);
final List faces = await faceDetector.processImage(inputImage);
print(faces.length); // IS ALWAYS ZERO
Works perfectly fine if source: ImageSource.gallery in iPhone
Fixed by Giving
import 'dart:math' as Math;
import 'dart:math';
import 'package:image/image.dart' as Im;
class CompressObject {
File imageFile;
String path;
int rand;
CompressObject(this.imageFile, this.path, this.rand);
}
Future<String> compressImage(CompressObject object) async {
return compute(decodeImage, object);
}
String decodeImage(CompressObject object) {
Im.Image? image = Im.decodeImage(object.imageFile.readAsBytesSync());
I.m.Image smallerImage = Im.copyResize(
image!,width: 200,height: 200
); // choose the size here, it will maintain aspect ratio
var decodedImageFile = File(object.path + '/img_${object.rand}.jpg');
decodedImageFile.writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
return decodedImageFile.path;
}
Then:
void chooseImage(bool isFromGallery) async {
final XFile? image = await picker.pickImage(
source: isFromGallery ? ImageSource.gallery : ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
if (image != null) {
if (Platform.isIOS) {
final tempDir = await getTemporaryDirectory();
final rand = Math.Random().nextInt(10000);
CompressObject compressObject = CompressObject(File(image.path), tempDir.path, rand);
String filePath = await compressImage(compressObject);
print('new path: ' + filePath);
file = File(filePath);
} else {
file = File(image.path);
}
}
final inputImage = InputImage.fromFilePath(i file.path);
final List<Face> faces = await faceDetector.processImage(inputImage);
/.........../
}

upload image by flutter in firebase Storage

I try to upload an image on firebase storage and get the error.
Future selectImage(ImageSource source) async {
try {
XFile? xImage = await ImagePicker().pickImage(source: source);//getting picture from phone
if(xImage == null ) return 'there is no image';
final File file = File(xImage.path);
//final Image image = Image.file(File(xImage.path));
print(xImage.path);
Directory appDocDir = await getApplicationDocumentsDirectory();
String filePath = '${appDocDir.absolute}/file-to-upload.png';
print(filePath);
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(file);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try like this.
Future selectImage(ImageSource source) async {
try {
ImagePicker imagePicker = ImagePicker();
XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
File imageFile = File(pickedFile.path);
if(imageFile == null ) return 'there is no image';
print(imageFile.path);
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(imageFile);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try this
import 'package:path/path.dart' as Path1;//for storing image path in firestore
DatabaseReference reference = FirebaseDatabase.instance.reference();
FirebaseStorage storage = FirebaseStorage.instance;
File? fileImage;
//call this function for picking image
pickedImage() async{
PickedFile? file = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 1000,
maxWidth: 1000
);
File image = file!.path;
setState((){
fileImage = image;
});
}
//call this function for storing image in firestore
_storeImage() async{
Reference storagerefrence = storage.ref().child('card_images/${Path1.basename(fileImage!.path)}');
TaskSnapshot uploadTask = await storagerefrence.putFile(fileImage!);
String url = await storagerefrence.getDownloadURL();//download url from firestore and add to firebase database
reference.child("image").push().set({
'image' : url
});
}

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!

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

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);
}