I try to use upload image from Flutter libary, but it doesn't work. The codes just run to gallery and choose the image, but the image doesn't show to the screen.
Please help me to make it work, from choosing the image and show the image result that I choose. Thanks
You have to update the state of the screen for seeing the changes. If you are using stateful just simply use setState to do this.
setState(() {
uploadFile = File(image!.path);
});
I hope this answer will help you.
static String? pickImage({bool useCamera = false, bool crop = true,
CropAspectRatio ratio = const CropAspectRatio(
ratioX: 1, ratioY: 1,
)}) {
ImagePicker().pickImage(source: useCamera ? ImageSource.camera : ImageSource.gallery, imageQuality: 60).then((pickedFile) {
if (pickedFile == null || !File(pickedFile.path).existsSync()) {
return Stream.error(Exception('No image picked!'));
}
if (crop) {
ImageCropper().cropImage(sourcePath: pickedFile.path ?? '', aspectRatio: ratio, uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: AppStyles.primary500Color,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
IOSUiSettings(
title: 'Cropper',
),
]).then((value) {
if (value != null) {
croppedFile = value;
// selectedPhotoStream.add(croppedFile);
/// ** You are missing **
setState((){
uploadFile = croppedFile.path;
});
return croppedFile?.path;
}
});
}
});
return croppedFile?.path;
}
Related
I am using the following code to pick an image from user's gallery.
Future getImageFromGallery(BuildContext context) async {
await ImagePicker.platform()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}
I am getting the following warning.
The member 'platform' can only be used within 'package:image_picker/image_picker.dart' or a test.
I'm not sure what the warning means. I tried looking it up but couldn't figure out the solution to resolve this warning.
Try below code hope its help to you
Declare File type form dart.io package
File? imagePicked;
Create Function for pick up the image
void gallaryImage() async {
final picker = ImagePicker();
final pickedImage = await picker.pickImage(
source: ImageSource.gallery,
);
final pickedImageFile = File(pickedImage!.path);
setState(() {
imagePicked = pickedImageFile;
});
}
Create your Widget
TextButton(
onPressed: gallaryImage,
child: Text(
'Gallery',
style: TextStyle(
color: Colors.black,
),
),
),
You can just change the code
ImagePicker.platform().pickImage(...)
to
ImagePicker().pickImage(...)
so
Future getImageFromGallery(BuildContext context) async {
await ImagePicker()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}
I have this form where I need to upload a profilePic and companyLogo. Earlier I faced some issues regarding updating images on the selection which I fixed using : imageCache.clear() & imageCache.clearLiveImages() and passing Unique key to Image.file widgets.
Now, the problem is, if I select the profile Pic then select the company Logo & When I send the images as Multipart in FormData, it uses the file which I selected later for both, i.e, if I select _companyLogo after _profilePic, it replaces _profilePic data with _companyLogo, however the displaying images remains correct for Image.file widget.
//Widgets using GestureDetector to call onAddProfilePic() and onAddCompanyLogo()
File _profilePic;
Key _keyProfilePic = Key('key1');
Image.file(
_profilePic,
fit: BoxFit.cover,
key: _keyProfilePic,
)
File _companyLogo;
Key _keyCompanyLogo = Key('key2');
Image.file(
_companyLogo,
fit: BoxFit.cover,
key: _keyCompanyLogo,
)
onAddProfilePic(){
Utils.selectImage(context, (newPic) {
if(newPic != null){
_profilePic = newPic;
_keyProfilePic = Key(Uuid().v4());
setState(() {});
}
});
}
onAddCompanyLogo(){
Utils.selectImage(context, (newPic) {
if(newPic != null){
_companyLogo = newPic;
_keyCompanyLogo = Key(Uuid().v4());
setState(() {});
}
});
}
The function selectImage is in Utils Class
static Future<void> selectImage(context, callback, {int minSize = 480, double ratioX = 1.0, double ratioY = 1.0}) async {
int sourceSelected = await showDialog(context: context, builder: (context) => DialogImagePicker());
if(sourceSelected == null) return;
var pickedImage = await ImagePicker().getImage(source: sourceSelected == 0 ? ImageSource.camera : ImageSource.gallery);
if(pickedImage==null) return;
File croppedFile = await ImageCropper.cropImage(
maxWidth: (minSize * ratioX).toInt(),
maxHeight: (minSize * ratioY).toInt(),
compressFormat: ImageCompressFormat.jpg,
sourcePath: pickedImage.path,
aspectRatio: CropAspectRatio(ratioX: ratioX, ratioY: ratioY),
compressQuality: 80,
androidUiSettings: AndroidUiSettings(
toolbarColor: kDarkBlueColor,
toolbarTitle: 'Crop Image',
hideBottomControls: true,
toolbarWidgetColor: Colors.white
),
);
if(croppedFile == null){
return;
}
croppedFile = croppedFile.renameSync(path.join(path.dirname(croppedFile.path), 'image'+'.jpg'));
print('Cropped file :$croppedFile');
imageCache.clear();
imageCache.clearLiveImages();
callback(croppedFile);
}
The problem is, since I was cropping the image & was changing the cropped file name, which was replacing previous images with newly selected ones. Not renaming so fixed the issue.
Additional to this, no unique key or image cache clearance is required.
Updated code:
File _profilePic;
Image.file(
_profilePic,
fit: BoxFit.cover,
)
File _companyLogo;
Image.file(
_companyLogo,
fit: BoxFit.cover,
)
onAddProfilePic(){
Utils.selectImage(context, (newPic) {
if(newPic != null){
_profilePic = newPic;
setState(() {});
}
});
}
onAddCompanyLogo(){
Utils.selectImage(context, (newPic) {
if(newPic != null){
_companyLogo = newPic;
setState(() {});
}
});
}
static Future<void> selectImage(context, callback, {int minSize = 480, double ratioX = 1.0, double ratioY = 1.0}) async {
int sourceSelected = await showDialog(context: context, builder: (context) => DialogImagePicker());
if(sourceSelected == null) return;
var pickedImage = await ImagePicker().getImage(source: sourceSelected == 0 ? ImageSource.camera : ImageSource.gallery);
if(pickedImage==null) return;
File croppedFile = await ImageCropper.cropImage(
maxWidth: (minSize * ratioX).toInt(),
maxHeight: (minSize * ratioY).toInt(),
compressFormat: ImageCompressFormat.jpg,
sourcePath: pickedImage.path,
aspectRatio: CropAspectRatio(ratioX: ratioX, ratioY: ratioY),
compressQuality: 80,
androidUiSettings: AndroidUiSettings(
toolbarColor: kDarkBlueColor,
toolbarTitle: 'Crop Image',
hideBottomControls: true,
toolbarWidgetColor: Colors.white
),
);
if(croppedFile == null){
return;
}
//croppedFile = croppedFile.renameSync(path.join(path.dirname(croppedFile.path), 'image'+'.jpg'));
callback(croppedFile);
}
I am using the image_picker and image_cropper plugin to select or capture the image with the help of the camera and Gallery. I got an image file from an image_picker. Now, I am using the Image.asset() widget to show the image in the Circle Avatar. Can anyone please tell me how I convert an image File to an asset image?
My code:
//Function that decides if image is returned or not(If not, then it will show the default circle avator)
File getImageWidget() {
if (_selectedImage != null) {
return _selectedImage;
} else {
return null;
}
}
//Function to set the image in the circle avatar
circleAva(){
return profileIconSelector(
setProfileIconHighQuality(getImageWidget() ?? userDetails.profile_pic,
userDetails.loginInitFrom),
userDetails.name,
SizeConfig.heightMultiplier * 5);
}
//Function to get image from Camera or Gallery
getImage(ImageSource source) async {
this.setState((){
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(
ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 700,
maxHeight: 700,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.deepOrange,
toolbarTitle: "Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.white,
)
);
this.setState((){
_selectedImage = cropped;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
}
You can't add asset images from your app. Asset images are images that you add to your project manually, but you can save the path to the image once it has been picked, then use Image.file(File.fromUri(Uri.file(IMAGE_PATH))).
Fortunately, I found the solution for this by myself.
In the case of the Image.file() widget, we have to provide the image of a File type.
And, In the case of the AssetImage() or Image.asset() widget, we need to pass the image path of String type.
So the Solution to use Image of File type in AssetImage() or
Image.asset() widget:
File _selectedImage = fetchedFromCameraOrGallery;
getImageWidget() {
if (_selectedImage != null) {
return CircleAvatar(
radius: SizeConfig.heightMultiplier * 5,
backgroundImage: AssetImage(
_selectedImage.path, //Convert File type of image to asset image path
),
);
}
}
We have to simply use the _selectedImage.path that will convert the image file of File type to a valid Asset image path format.
I managed to choose an image from gallery using the image picker and it is as follows
Future pickImage() async {
File _originalImage = await ImagePicker.pickImage(
source: ImageSource.camera);
if (_originalImage != null) {
File _croppedImage = await ImageCropper.cropImage(
sourcePath: _originalImage.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarColor: BaengColors.blue,
toolbarTitle: 'Baeng Omang Cropper',
statusBarColor: BaengColors.blue[700],
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false
)
);
this.setState(() {
_imagePicked = _croppedImage;
isLoaded = true;
getTextFromImage();
});
}
}
Tried to debug it several times and it was not showing any kind of bug nor problem, but the image cropping activity remains black(without) the image selected from the image picker.
Please help
Just add maxHeight And maxWidth in Image_Picker
File _originalImage = await ImagePicker.pickImage(source: ImageSource.camera,
imageQuality: 20,
maxHeight: 500,maxWidth: 500);
I am newbie in flutter, trying to put picked videos in a ListView or GridView. How can I put compressed videos in ListView.builder with the code below :
Future<void> _videoPicker() async {
if (mounted) {
final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
if (file?.path != null) {
final thumbnail = await _flutterVideoCompress.getThumbnail(
file.path,
quality: 50,
position: -1,
);
setState(() {
_videoImage = thumbnail;
});
final resultFile = await _flutterVideoCompress.getThumbnailWithFile(
file.path,
quality: 50,
position: -1,
);
debugPrint(resultFile.path);
assert(resultFile.existsSync());
debugPrint('file Exists: ${resultFile.existsSync()}');
final MediaInfo info = await _flutterVideoCompress.compressVideo(
file.path,
deleteOrigin: false,
quality: VideoQuality.LowQuality,
);
debugPrint(info.toJson().toString());
}
}
}
To use Listview.builder you need a List to make listview form it, or you can use just Listview Widget to manually make your Listview
ListView Widget