I use Image_picker and provider and some other things to access to camera and gallery and get the photo and save it with Sqlite . there is no problem here but I want to ask is there any solution for editing photo while we take the photo using camera? for example highlight a part of the photo
Future<void> _takePicture() async {
final picker = ImagePicker();
final imageFile =
await picker.pickImage(source: ImageSource.camera, maxHeight: 600);
if (imageFile == null) {
return;
}
setState(() {
_imageFile = File(imageFile.path);
});
this is my method
should I use Image_painter or Image_editor_plus?
you can use Image package in flutter, you can change the brightness using this method from image package
Image image = decodeImage(file.readAsBytesSync());
Image brightenedImage = adjustColor(image, brightness: 0.2);
you can read details of this package here.
Related
i'm trying to upload an image to the cloud firestore and the firebase storage. I'm saving the image url in a variable called imgUrl, this variable is later on passed inside a function called addIntervention(). The problem is that the upload task takes few time so if I upload and click the save button directly, imgUrl will be having null value cus the image is still getting uploaded.
Here is my code:
IconButton(
icon: Icon(
Icons.image,
color: Palette.primaryColor,
),
onPressed: () async {
ImagePicker imagePicker = ImagePicker();
XFile? file = await imagePicker.pickImage(
source: ImageSource.gallery);
if (file == null) return;
Reference referenceRoot =
FirebaseStorage.instance.ref();
Reference dirImages =
referenceRoot.child("iv_images");
Reference imgToUpload = dirImages.child(file.name);
try {
await imgToUpload.putFile(File(file.path));
var x = imgUrl = await imgToUpload.getDownloadURL();
imgUrl = x;
} catch (e) {}
},
),
And for the button I took this snippet:
if (imgUrl.isEmpty) {
QuickAlert.show(
context: context,
type: QuickAlertType.error,
title: 'Error',
text:
'Please upload an image');
} else {
await addIntervention(
imgUrl,
etatLabel,
numIntv,
intervention,
myPrice!,
note,
dateTime);
Noting that i'm using async/await for the save button as well, is there any way I can solve this? thanks in advance.
You can try these tips:
First thing to make your upload time a lot less is to compress a picture, you don't have to compress the image till it gets blurry but a small amount of compression will significantly reduce your upload time. Also if a use selects an image then he/she may want to crop it too. So it will be better if you add that functionality too.
Luckily there's a package called image_cropper(link), which you can use to crop as well as for compressing your image.
If you don't want to show any loading indicator then you can directly pass the image to the next screen and run your processes in the background(which is called optimistic updating), but if you want to show a loading indicator then you can use this package called flutter_spinkit. It has a very large variety of loading indicators which you will love.
When a user clicks on a button, you can show a progress indicator on the button itself to indicate how much percent has been uploaded, has to be uploaded before the user can click on the button.
In the firebase, you can get percentage like this:
Future getImage(BuildContext context) async {
final picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('profile/${Path.basename(_image.path)}}');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
setState(() {
_imageURL = dowurl.toString();
});
print(_imageURL);
}
uploadTask.events.listen((event) {
setState(() {
_progress = event.snapshot.bytesTransferred.toDouble() /
event.snapshot.totalByteCount.toDouble();
});
}).onError((error) {
// do something to handle error
});
Then you can display progress like this:
Text('Uploading ${(_progress * 100).toStringAsFixed(2)} %')
I am building a music streaming mobile app like Spotify in Flutter. One of the functionalities I would like to implement is so the user can share a music video to Instagram story. My question is how would you go about this / is this possible to implement in Flutter. I have pasted a photo of how Spotify implements this for reference. Any help would be very appreciated :)enter image description here
I have looked into Meta's Developers for info(https://developers.facebook.com/docs/instagram/sharing-to-stories/) but there are only instructions for Swift and Kotlin.
As suggested in the comments, you can use the share_plus package.
Add share_plus: ^4.0.0 to your pubspec.yaml dependencies
import 'package:share_plus/share_plus.dart';
Share.shareXFiles([pickedImage], text: 'Great picture');
Note that pickedImage is an XFile. You can have a user choose an xFile from their local file system or gallery using the image_picker package.
Full example on how to use image_picker with share_plus
class ImageHandler extends StatefulWidget {
const ImageHandler({super.key});
#override
State<ImageHandler> createState() => _ImageHandlerState();
}
class _ImageHandlerState extends State<ImageHandler> {
var _image; // type File
var pickedImage; // type XFile (needed for sharing)
var imageButtonText = "Choose an image from Gallery";
/// Get from gallery
_getFromGallery() async {
final ImagePicker _picker = ImagePicker();
pickedImage = await _picker.pickImage(source: ImageSource.gallery);
// Pick an image
setState(() {
if (pickedImage != null) {
_image = File(pickedImage.path);
imageButtonText = "Replace";
}
});
}
_shareImage() async {
Share.shareXFiles([pickedImage], text: 'Great picture');
}
Although I've never tried it, image_picker should work with videos as well. Docs are here
This should work just like how spotify does it in the example you gave.
I am trying to save an image to my local mobile device when I use this code from the pub.dev example page of the camera package. However I am not finding the file saved on the device. Can anyone please help me with how to save the image taken to a given path
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) {
showInSnackBar('Picture saved to ${file.path}');
}
}
});
}
Using await ImagePicker.pickImage(...), you are already on the right track because the function returns a File.
The File class has a copy method, which you can use to copy the file (which is already saved on disk by either the camera or by lying in gallery) and put it into your application documents directory:
// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});
You should also note that you can get the path of the image file from ImagePicker using image.path, which will also contain the file ending that you might want to extract and you can save your image path by using newImage.path.
You can use path provider and save the images like this
https://pub.dev/packages/path_provider
final XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final String newFile = await getApplicationDocumentsDirectory().path;
final var fileName = basename(file.path);
final File localImage = await image.saveTo('$newFile/$fileName');
I am creating a widget in which I want to display a gridview of image clicked through mobile camera at runtime. I had used image_picker package from flutter. But it is only working for picking image from gallery and everytime I click image it crashes.
class _ImageInputState extends State<ImageInput>
with AutomaticKeepAliveClientMixin {
// list of images
final List<File> _imageFileList = [];
final ImagePicker _picker = ImagePicker();
Function for picking image from camera using image_picker
final imageFile = await _picker.pickImage(source: imageSource);
if (imageFile == null) return;
File tmpFile = File(imageFile.path);
final appDir = await getApplicationDocumentsDirectory();
final fileName = basename(imageFile.path);
final localFile = await tmpFile.copy('${appDir.path}/$fileName');
// setState(() {
// _imageFileList.add(localFile);
//
// });
_pickImageGall(ImageSource.gallery);
}
function for picking images from the gallery of phone
Future<void> _pickImageGall(ImageSource imageSource) async {
final _pickedImage = await _picker.pickImage(source: imageSource);
if (_pickedImage != null) {
setState(() {
_imageFileList.add(File(_pickedImage.path));
});
}
}
and in the ui there is a gridview to display the images in which the last index is a input widget where there is two IconButton one for camera input and other for gallery input. As I am making this thing for the first time I am confused how to procedure will be . I had try to implement every solution from the stackoverflow but none worked for me. Please give the solution.
Here is a what's happening : I'm trying to upload an image from gallery to my app on iOS simulator. Image Picker opens the gallery but can't select an image and return to app. Here's my simple code:
File _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
and my widget:
body: Center(
child: _image != null ? Image.file(_image) : Text('no Image'),
),
Thank you all in advance
For the iOS, as stated in the documentation, you'll need some config in the native side relating to permission:
Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
NSMicrophoneUsageDescription - describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.
Other than that, it should work perfectly fine with your code. The image should be fit within a Flexible like this, or maybe a SizedBox to avoid overflowing:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MaterialApp(
home: SampleScreen(),
));
}
class SampleScreen extends StatefulWidget {
#override
_SampleScreenState createState() => _SampleScreenState();
}
class _SampleScreenState extends State<SampleScreen> {
File _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(onPressed: () => getImage(), child: Text('Press me')),
Flexible(child: _image != null ? Image.file(_image) : Text('no Image')),
],
),
),
);
}
}
File _image;
String _image1 = "";
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image1 = pickedFile.path;
_image = File(pickedFile.path);
print(json.encode(_image1));
print("file path...");
} else {
print('No image selected.');
}
});
}
In my case, I update my Image picker library from 0.6.3 to 0.8.4
hope this helps anyone.
You need to add the user permissions(key) and add the purpose(values) of these in info.plist file in iOS module.
Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
dependencies:
image_picker: ^0.8.4+4
import 'package:image_picker/image_picker.dart';
final picker = ImagePicker();
Future pickImage() async {
setState(() {
picselected1 = false;
});
ImagePicker picker = ImagePicker();
PickedFile pickedFile;
pickedFile = await picker.getImage(
source: ImageSource.gallery,
);
setState(() {
if (pickedFile != null) {
picselected1 = true;
// _images.add(File(pickedFile.path));
_image = File(pickedFile.path); // Use if you only need a single picture
} else {
print('No image selected.');
}
});
}
For everyone still dealing with this problem
Please not this in the image_picker documentary and make sure you tested it on a real device:
Starting with version 0.8.1 the iOS implementation uses PHPicker to
pick (multiple) images on iOS 14 or higher. As a result of
implementing PHPicker it becomes impossible to pick HEIC images on the
iOS simulator in iOS 14+. This is a known issue. Please test this on a
real device, or test with non-HEIC images until Apple solves this
issue