Flutter Google-Ml-Kit-plugin - FaceDetector not working in iPhone cameras - iphone

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

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 set a unique UUID for my PickedFile?

I'm trying to give an image uploaded from camera a unique id before uploading to Firestore.
I've been using Reed Barger's https://www.udemy.com/course/build-a-social-network-with-flutter-and-firebase/ tutorial but some of the code he used has been deprecated. In this case, image compression.
His code to compress and set unique image id was
compressImage() async {
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
Im.Image imageFile = Im.decodeImage(file.readAsBytesSync());
final compressedImageFile = File('$path/img_$postId.jpg')
..writeAsBytesSync(Im.encodeJpg(imageFile, quality: 85));
setState(() {
file = compressedImageFile;
});
}
The libraries he used include
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as Im;
import 'package:uuid/uuid.dart';
His variables were
File file;
String postId = Uuid().v4();
Since then, the image_picker library allows me to compress the image by seting the imageQuality so there's no need for the image.dart package. How can I modify my code (below) to set a unique image id in the format Reed used?
PickedFile file;
String postId = Uuid().v4();
handleTakePhoto() async {
Navigator.pop(context);
file = (await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 675.0,
maxWidth: 960,
imageQuality: 85,
));
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
final compressedImageFile = File('$path/img_$postId.jpg');
setState(() {
this.file = file;
file = compressedImageFile;
});
}
As it is, it returns an error that compressedFileImage can't be assigned to type PickedFile.
I've tried adding the cast as PickedFile but that doesn't work.
That's because you're creating a File instead of a PickedFile:
final compressedImageFile = File('$path/img_$postId.jpg');
Just change it to:
final compressedImageFile = PickedFile('$path/img_$postId.jpg');
This has worked so far. I've created a variable File storedImage; Then changed
setState(() {
this.file = file;
file = compressedImageFile;
}
to
setState(() {
this.file = file;
storedImage = File(file.path);
storedImage = compressedImageFile;
print(compressedImageFile); //For debugging
}
The print statement gives me the new uuid and name.

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

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