Flutter Image Crop Not Responding - flutter

I am trying to crop an image from picked image from gallery, the image is picked perfectly but while trying to crop an image it seems nothing happened in the screen, and some problem detected in console though I can't understand the problem. the code I have used is from official pub.dev site [https://pub.dev/packages/image_cropper/example]
My Task is : pick and crop an image for
Help me to Resolve this Problem, Thanks in Advance.
The Code:
....
class _EditGalleryScreenState extends State<EditGalleryScreen> {
File imageFile;
List _galleries = new List();
#override
void initState() {
.....
}
....
//SOME API CALLS
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Gallery"),
),
body: _galleries.isNotEmpty
? GridView.builder(/* DIAPLYING LIST OF IMAGES FROM API CALL */)
: SizedBox(),
//BUTTON TO TRIGGER IMAGE PICKER
floatingActionButton: FloatingActionButton(
tooltip: "Add Image",
onPressed: () {
_pickImage();
},
child: Icon(Icons.add_a_photo),
backgroundColor: AppColors.PRIMARY_COLOR,
),
);
}
Future<Null> _pickImage() async {
// imageFile = await ImagePicker.pickImage(source: ImageSource.gallery); // this was deprecated so i have updated to otherone
PickedFile imageFile = await ImagePicker().getImage(
source: ImageSource.gallery,
maxWidth: 500,
maxHeight: 500,
imageQuality: 20);
if (imageFile != null) {
setState(() {
state = AppState.picked;
debugPrint("Image Picked and State Changed");
_cropImage();//calling CROP FUNCTION
});
}
}
Future<Null> _cropImage() async {
debugPrint("Crop Image Called");
File croppedFile = await ImageCropper.cropImage(
sourcePath: imageFile.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
imageFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
}
}
Screen Shot of Console

Related

image_picker It does not allow me to load an image from gallery or camera

Everything works normally, but when I click to load an image from the gallery or from the camera, it does not load the image
The message in the VSC Debug Console is:
D/MediaScannerConnection( 5069): Scanned /data/user/0/com.lot.sig/cache/ce7735c2-8d36-4633-996f-bfae03424df26527509175807023631.jpg to null
This is my user_profile.dart:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
class UserProfile extends StatefulWidget {
UserProfile();
#override
_UserProfile createState() => _UserProfile();
}
enum AppState {
free,
picked,
cropped,
}
class _UserProfile extends State<UserProfile> {
AppState? state;
File? imageFile;
#override
void initState() {
super.initState();
state = AppState.free;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black87,
title: Text("Hola"),
),
body: Center(
child: imageFile != null ? Image.file(imageFile!) : Container(),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black87,
onPressed: () {
if (state == AppState.free)
_pickImage();
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) _clearImage();
},
child: _buildButtonIcon(),
),
);
}
Widget _buildButtonIcon() {
if (state == AppState.free)
return Icon(Icons.add);
else if (state == AppState.picked)
return Icon(Icons.crop);
else if (state == AppState.cropped)
return Icon(Icons.clear);
else
return Container();
}
Future<Null> _pickImage() async {
final _imageFile = await ImagePicker().pickImage(source: ImageSource.gallery);
if (_imageFile != null) {
imageFile = File(_imageFile.path);
setState(() {
state = AppState.picked;
});
}
}
Future<Null> _cropImage() async {
File? croppedFile = await ImageCropper.cropImage(
sourcePath: imageFile!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
imageFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
}
void _clearImage() {
imageFile = null;
setState(() {
state = AppState.free;
});
}
}
And this is my image_picker_handler.dart :
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sig/utilitary/image_picker_dialog.dart';
class ImagePickerHandler {
late ImagePickerDialog imagePicker;
AnimationController? _controller;
ImagePickerListener _listener;
ImagePickerHandler(this._listener, this._controller);
final ImagePicker _picker = ImagePicker();
openCamera() async {
imagePicker.dismissDialog();
var image = await (_picker.pickImage(source: ImageSource.camera) as FutureOr<XFile>);
cropImage(image);
}
openGallery() async {
imagePicker.dismissDialog();
var image = await (_picker.pickImage(source: ImageSource.gallery) as FutureOr<XFile>);
cropImage(image);
}
void init() {
imagePicker = new ImagePickerDialog(this, _controller);
imagePicker.initState();
}
Future cropImage(XFile image) async {
File? croppedFile = await ImageCropper.cropImage(
sourcePath: image.path,
maxWidth: 512,
maxHeight: 512,
);
_listener.userImage(croppedFile);
}
showDialog(BuildContext context) {
imagePicker.getImage(context);
}
}
abstract class ImagePickerListener {
userImage(File? _image);
}

how to show selected image in alert dialog?

I want to implement that after clicking upload button it will pick image from gallery. After picking image then open Image cropper screen lastly cropped image will show in alert dialog. But here clicking upload button it pick image again clicking upload button open crop screen lastly clicking upload button it shows alert dialog.i want to change state automatically .. How can i fix that. Here is a sample code i have tried
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late AppState state;
File? imageFile;
#override
void initState() {
super.initState();
state = AppState.free;
}
#override
Widget build(BuildContext context) {
Future pickedImage() async {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
imageFile = pickedImage != null ? File(pickedImage.path) : null;
if (imageFile != null) {
setState(() {
state = AppState.picked;
});
}
}
Future<Null> _cropImage() async {
var croppedFile = await ImageCropper().cropImage(
sourcePath: imageFile!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
imageFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
}
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
if (state == AppState.free)
pickedImage();
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) {
showAlertDialog(context);
} else {
Container();
}
},
child: Text("Upload"))
],
));
}
showAlertDialog(BuildContext context) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
);
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Simple Alert"),
content: Container(
width: 250,
height: 100,
child: imageFile != null ? Image.file(imageFile!) : Container(),
),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
}
enum AppState {
free,
picked,
cropped,
}
Maybe you should add this line to setState block also.
if (croppedFile != null) {
//imageFile = croppedFile;
setState(() {
imageFile = croppedFile; //to here
state = AppState.cropped;
});
}
ImagePicker return a nullable CroppedFile?.
You can create a state variable to hold it.
File? imageFile;
CroppedFile? croppedFile;
/// you can also directly assing it on `croppedFile = await ImageCropper().cropImage(`
if (croppedFile != null) {
croppedFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
Now to view the croppedFile
croppedFile != null ? Image.file(File(croppedFile!.path)) : null),

I am having error using Image cropper in my project

I am using image cropper dependency in my flutter project.
I am using image_cropper: ^1.4.1, And I am getting an error showing
Error: Member not found: 'ImageCropper.cropImage'.
final croppedFile = await ImageCropper.cropImage(
^^^^^^^^^
This is my code
Future<File?> cropImage(File imageFile) async {
File? croppedFile;
try {
croppedFile = await ImageCropper.cropImage(
sourcePath: imageFile.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: accentColor,
toolbarWidgetColor: white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
return croppedFile;
} catch (e) {
print(e);
}
return croppedFile;
}
I don't know what is causing the error
try replacing ImageCropper.cropImage with ImageCropper().cropImage

How to use image_picker in flutter

I am confused about how to use image_picker, this is how I use it in my application (like in many tutorials):
class AddDialogState extends State<AddDialog> {
File galleryFile;
Widget _onlyStatus() {
getLocalImage() async {
var _galleryFile = await ImagePicker.pickImage(
source: ImageSource.gallery
};
setState(() {
galleryFile = _galleryFile;
});
print(_galleryFile.path);
}
return Column(
........
FlatButton.icon(
onPressed: () {
getLocalImage();
}
)
)
}
#override
Widget build(BuildContext context) {
// fullscreen dialog
.........
body: _onlyStatus()
}
}
The problem was, the above code doesn't start ImagePicker, when i click the FlatButton, the above code just produce an error the getter 'path' was called on null, it doesn't start any new activity related to gallery, so what's wrong with my code?
Actually pickImage() is deprecated now. So you have to use ImagePicker.getImage(source: ImageSource.gallery)
Click here for more
void getImage(ImageSource imageSource) async {
PickedFile imageFile = await picker.getImage(source: imageSource);
if (imageFile == null) return;
File tmpFile = File(imageFile.path);
final appDir = await getApplicationDocumentsDirectory();
final fileName = basename(imageFile.path);
tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
setState(() {
_image = tmpFile;
});
}
The code also store image file in device directory. Path pacakage is also used.
Here is my example you only need to call the SelectionItem and pass the required parameters and it's done, also it includes support for Android and iOS.
class SelectionItem {
String text;
GestureTapCallback action;
SelectionItem({
this.text,
this.action,
});
}
Widget _getOptionWidget(SelectionItem item) {
return SimpleDialogOption(
onPressed: item.action,
child: Text(item.text),
);
}
Widget _getCupertinoOptionWidget(SelectionItem item) {
return CupertinoActionSheetAction(
onPressed: item.action,
child: Text(item.text),
);
}
showSelector(
BuildContext context, {
String title,
List<SelectionItem> actions,
}) {
bool isAndroid = Injector.instance.platform == Platform.ANDROID;
if (isAndroid) {
final items = actions.map((action) => _getOptionWidget(action)).toList();
return SimpleDialog(
title: Text(title),
children: items,
);
} else {
final items =
actions.map((action) => _getCupertinoOptionWidget(action)).toList();
return Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
CupertinoActionSheet(
title: Text(title),
actions: items,
cancelButton: CupertinoActionSheetAction(
onPressed: () {
NavigationUtils.pop(context);
},
child: Text("Cancel"),
),
),
],
);
}
}
your showDialog should be something like this:
Container(
width: 300,
height: 300,
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) => showSelector(
context,
"Select",
actions: [
SelectionItem(
"Camera",
action: () {
getImage(ImageSource.camera);
Navigator.of(context).pop();
},
),
SelectionItem(
"Gallery",
action: () {
getImage(ImageSource.gallery);
Navigator.of(context).pop();
},
)
],
),
);
},
),
)
Here is my code for image_picker: ^0.8.4+4 (flutter 2.8.1)
bool hasImage = false;
File? image;
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;
hasImage = true;
});
} on PlatformException catch (e) {
debugPrint('Failed to pick image: $e');
}
}

How to crop Image from image picker in flutter?

I want to allow the user to crop the Image he chose from the image picker and save it(Similar to uploading profile pic on Whatsapp). How can I do this in flutter?
Sample Image:
You can use these 2 flutter libraries to achieve this,
image_picker;
image_cropper
The image picker use the native libraries in iOS and Android to achieve it, therefore it will delivery a good performance way.
Here is a sample available in image_picker:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(new ConfigScreen());
class ConfigScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ImageCropper',
theme: ThemeData.light().copyWith(primaryColor: Colors.deepOrange),
home: MyHomePage(
title: 'ImageCropper',
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({this.title});
#override
_MyHomePageState createState() => _MyHomePageState();
}
enum AppState {
free,
picked,
cropped,
}
class _MyHomePageState extends State<MyHomePage> {
AppState state;
File imageFile;
#override
void initState() {
super.initState();
state = AppState.free;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: imageFile != null ? Image.file(imageFile) : Container(),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.deepOrange,
onPressed: () {
if (state == AppState.free)
_pickImage();
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) _clearImage();
},
child: _buildButtonIcon(),
),
);
}
Widget _buildButtonIcon() {
if (state == AppState.free)
return Icon(Icons.add);
else if (state == AppState.picked)
return Icon(Icons.crop);
else if (state == AppState.cropped)
return Icon(Icons.clear);
else
return Container();
}
Future<Null> _pickImage() async {
imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
if (imageFile != null) {
setState(() {
state = AppState.picked;
});
}
}
Future<Null> _cropImage() async {
File croppedFile = await ImageCropper.cropImage(
sourcePath: imageFile.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
imageFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
}
void _clearImage() {
imageFile = null;
setState(() {
state = AppState.free;
});
}
}
The image_picker already can crop the image. You pass in the specified width and height for the image you want and the plugin actually crops the original image.
_imageFile = ImagePicker.pickImage(source: source, maxWidth: 200.0, maxHeight: 300.0);
What you are asking for is another plugin to crop images after one has been selected and that would be outside the scope of the image_picker.
I am facing something similar and you can always have the user edit the photo or video with the built in camera app until there is a plugin made for cropping images.
For cropping images on the UI level you can do something like this:
https://stackoverflow.com/a/44665742/7303311
To crop the image from image_cropper library you case just set the
aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1)
Here's the sample code:
CroppedFile? croppedFile = await ImageCropper().cropImage(
sourcePath: pickedImage.path,
aspectRatio: imagePickingType == ImagePickingType.profilePic ? CropAspectRatio(ratioX: 1, ratioY: 1) :
imagePickingType == ImagePickingType.communityWall ? CropAspectRatio(ratioX: 16, ratioY: 9) : null,
uiSettings: [
AndroidUiSettings(
toolbarTitle: cropPageTitle ?? 'Edit Image',
toolbarColor: toolbarTextColor ??
theme.scaffoldBackgroundColor,
toolbarWidgetColor: toolbarBackgroundColor ??
theme.primaryColor,
initAspectRatio:
initialAspectRation ?? CropAspectRatioPreset.original,
lockAspectRatio: (imagePickingType == ImagePickingType.profilePic) || (imagePickingType == ImagePickingType.communityWall),
backgroundColor: theme.scaffoldBackgroundColor,
activeControlsWidgetColor: theme.primaryColor,
),
IOSUiSettings(
title: cropPageTitle ?? 'Edit Image',
rotateClockwiseButtonHidden: true,
aspectRatioPickerButtonHidden: true,
aspectRatioLockEnabled: (imagePickingType == ImagePickingType.profilePic) || (imagePickingType == ImagePickingType.communityWall),
rotateButtonsHidden: true,
),
],
);
if (croppedFile != null) {
return File(croppedFile.path);
} else {
File(pickedImage.path);
}