Resize image very slow when it process - flutter

I want to resize an image and when run my code but resize process is very slow.
My code as below :
void _selectImage() async {
try {
final checkDataImage =
await _imagePicker.pickImage(source: ImageSource.camera);
if (checkDataImage != null) {
print(checkDataImage.name);
print(checkDataImage.path);
setState(() {
pickedImage = checkDataImage;
});
}
} catch (err) {
print(err);
pickedImage = null;
}
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
Img.Image image = Img.decodeImage(await pickedImage.readAsBytes());
Img.Image smallerImg = Img.copyResize(image, width: 500);
int rand = new Math.Random().nextInt(999999999);
var compressImg = new File('$path/image_$rand.jpg')
..writeAsBytesSync(Img.encodeJpg(smallerImg, quality: 90));
setState(() {
if (!mounted) return;
_imageUpload = compressImg;
});}
What wrong my code, please help to faster it process ?
Thank you for your help.

As others have said, package:image is written in pure Dart and will never be as fast as native solutions that can be multithreaded and hardware accelerated.
While using another isolate will stop the image tasks blocking the UI, if you need to do this as fast as possible, I suggest you use something like the ImageMagick library, or if you only need Android and iOS support, package:flutter_image_compress.

Related

How to resolve Lost Connection to Device (Flutter Image Picker)

I'm building an app that requires me to use the camera of the device. I have followed all the procedures to set it up via the Image Picker Documentation and I am still having issues.
Funny enough, it was working fine when I tested it last time but as I added new widgets to screen and tried testing again, the app crashed with very minimal error message which says:
Lost connection to device.
This is how I capture the image:
Future<void> _pickImage() async {
try {
bool isPermisionGranted = await _requestFilePermission();
if (!isPermisionGranted) {
showToast('Please give us access to your camera.');
return;
}
final image = await ImagePicker().pickImage(source: ImageSource.camera, imageQuality: 90);
if (image == null) return;
final tempImageFile = File(image.path);
setState(() {
_imageFile = tempImageFile;
});
if (!mounted) return;
Navigator.of(context).pushNamed(Routes.chi, arguments: {'image_file': _imageFile});
} on PlatformException catch (e) {
debugPrint('Failed to pick image: $e');
showToast('Failed to pick image');
}
}
Could this be a memory issue? And how can I resolve it?

Flutter Newb, anyone tell me whats wrong with this code?

Following a tutorial for adding and saving images and getting errors for the below code, under ImagePicker, ImageSource and SelectedImage.
Future getImage() async {
var image = await ImagePicker.PickImage(source: ImageSource.camera);
setState(() {
selectedimage = image;
});
}
You need to create an instance first, then you will be able to use pickImage method.
Future getImage() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
if (image != null) {
setState(() {
selectedimage = image;
});
}
}
Fine more about image_picker
You have to be careful whenever playing with the setState() functions. This combined with how you pick the image and how you store it in the 'var' in your case could cause further trouble. To generally ease things up for further use I recommend creating a utils class, in which you would have an image picker method, just like this one:
import 'package:image_picker/image_picker.dart';
pickImage(ImageSource source) async {
final ImagePicker _imagePicker = ImagePicker();
XFile? _file = await _imagePicker.pickImage(source: source);
if (_file != null) {
return await _file.readAsBytes();
}
print('No Image Selected');
}
Afterwards, if you would like to call that in any other instance you would need something like this, though this is for a url image(I had it in hand), such as:
void selectImage() async {
Uint8List? im = await pickImage(ImageSource.gallery);
final ByteData imageData = await NetworkAssetBundle(Uri.parse(
"url for template image"))
.load("");
final Uint8List bytes = imageData.buffer.asUint8List();
// if null - use the template image
im ??= bytes;
// update state
setState(() {
_image = im!;
});
}
Hope it helped in a way.

how to handle the time lag after capturing the image ImagePicker Flutter

im learning flutter and now tried to capture the photo with ImagePicker package from the following method, but after I successfully capture the photo, there is always 1 sec until app get the data and jump to next page:
Future pickImage(ImageSource source) async {
try {
var image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final imagePermanent = await saveImagePermanently(image.path);
selectedImage = File(imagePermanent.path);
isUploaded.value = !isUploaded.value;
update();
} on PlatformException catch (e) {
print('Failed to pick image: $e');
}
}
Future<File> saveImagePermanently(String imagePath) async {
final directory = await getApplicationDocumentsDirectory();
final name = basename(imagePath);
final image = File('${directory.path}/$name');
return File(imagePath).copy(image.path);
}
now my solution is adding a listener onInit when image is created with GetX:
#override
void onInit() {
super.onInit();
ever(isUploaded, (value) {
Get.to(
() => AddPersonProfileAddDetails(),
);
});
}
So is there a way to detect the status of capturing the image like finished/failed/progressing, thanks for any clue or let me know a better way to jump to next page after capturing the image, thanks a lot!

What is the right way of reducing image size captured from flutter camera plugin

I am using the example code from Flutter Camera Plugin. I want to reduce Image size once I capture the image and store it in imageFile variable.
I am not sure is there a built in feature available. didn't find any information in their documentation.
I tried to use Image Plugin to achieve it like below. but it is not working. the entire application stops it function when you use it.
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
XFile resizeImage(img) {
var image = imageP.decodeJpg(File(img.path).readAsBytesSync());
var thumbnail = imageP.copyResize(image, width: 400);
File(img.path).writeAsBytesSync(imageP.encodeJpg(thumbnail));
return XFile(img.path);
}
There is a bug in Image Package.... I used flutter_native_image Package and it worked....
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
here is the image compression function code.
Future<XFile> resizeImage(img) async {
ImageProperties properties =
await FlutterNativeImage.getImageProperties(img.path);
File compressedFile = await FlutterNativeImage.compressImage(img.path,
quality: 90,
targetWidth: 500,
targetHeight: (properties.height! * 500 / properties.width!).round());
// delete original file
try {
if (await img.exists()) {
await img.delete();
}
} catch (e) {
// Error in getting access to the file.
}
return XFile(compressedFile.path);
}

Using Google ML-Kit On-Device Text Recognition in Flutter

Is it possible to use Google ML-Kit On-Device Text Recognition in Flutter? All of the tutorials and resources I am finding online are all firebase_ml_vision, but I am looking for one that uses the no-cost OCR from Google ML-Kit. How would I do this in Flutter?
as #Sayan Nath said you can use mlkit, but I think the better choice would be google_ml_kit, the firebase team who have worked on firebase_ml_vision also recommended using it.
use this package https://pub.dev/packages/camera_google_ml_vision
It's exactly the same in terms of how to use firebase_ml_vision
Yes surely you can use this package https/pub.dev/packages/mlkit this is google's mlkit. OCR has also support for both ios and android. Happy Coding ;)
ML Kit for Text Recognition
Follow the installation of Google ML Kit (https://pub.dev/packages/google_ml_kit). (Flutter 2.8)
Set this thing up
bool hasImage = false;
File? image;
TextDetector textDetector = GoogleMlKit.vision.textDetector();
String? imagePath;
String scanText = '';
To get the image, use image picker: https://pub.dev/packages/image_picker
Future getImage(ImageSource source) async {
try {
final image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
this.image = imageTemporary;
imagePath = imageTemporary.path;
debugPrint(imagePath);
hasImage = true;
});
} on PlatformException catch (e) {
debugPrint('Failed to pick image: $e');
}
}
Code for getting the text from the image
Future getText(String path) async {
final inputImage = InputImage.fromFilePath(path);
final RecognisedText recognisedText =
await textDetector.processImage(inputImage);
for (TextBlock block in recognisedText.blocks) {
for (TextLine line in block.lines) {
for (TextElement element in line.elements) {
setState(() {
scanText = scanText + ' ' + element.text;
debugPrint(scanText);
});
}
scanText = scanText + '\n';
}
}
}
Call the getText function and pass the image path. getText(imagePath).