How to convert a Image file to Asset Image in flutter? - flutter

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.

Related

File Picker png format images is giving issues

I was using ImagePicker in my application to select and upload images, but it recently started giving me errors, and constantly glitches when selecting png format images.
For this reason I switched to File picker. But it only works somewhat, and my application still gets stuck. I can only see its display, the image unfortunately does not get stored in the backend (jpg and jpeg images work fine).
Here is the image picker code (if there is a workaround uploading png images using this package, it would be much appreciated):
final ImagePicker _picker = ImagePicker();
Future imageSelectorGallery() async {
var image = (await _picker.pickImage(
source: ImageSource.gallery,
));
if (image != null) {
Uint8List imageBytes = await image
.readAsBytes(); // A fixed-length list of 8-bit unsigned integers which is the file read as bytes
String baseimage = base64Encode(imageBytes);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(context,MaterialPageRoute(builder: (context) => CreatePosts(post,user,caption,upvotes)));
}
}
Here is the file picker code which I have implemented, any help figuring out the error here would also be appreciated:
Future imageSelectorGallery() async {
FilePickerResult? image = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
);
if (image != null) {
Uint8List? imageBytes = image.files.first.bytes;
String baseimage = base64Encode(imageBytes!);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreatePosts(post, user, caption, upvotes)));
} else {
print("File picker error");
}
}
The image is displayed using:
child: Container(
height:
MediaQuery.of(context).size.height / 4.3,
width: MediaQuery.of(context).size.width / 3.4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
image: DecorationImage(
fit: BoxFit.cover,
image: Image.memory(
_bytesImage,
gaplessPlayback: true,
).image,
))),
),

upload Image to firebase storage and NOT File

There are lot of references of uploading a dart:io 'File' but I want to upload a material.dart Image to firebase.
My Image comes from a processed Thumbnail of a video and not just picked by a Image picker.
This is how I generate a thumbnail,
Future<ThumbnailResult> genThumbnail(url) async {
//WidgetsFlutterBinding.ensureInitialized();
Uint8List bytes;
final Completer<ThumbnailResult> completer = Completer();
bytes = await VideoThumbnail.thumbnailData(
video: url,
imageFormat: ImageFormat.JPEG,
maxHeight: 250,
maxWidth: 300,
timeMs: 0,
quality: 0);
int _imageDataSize = bytes.length;
print("image size: $_imageDataSize");
final _image = Image.memory(bytes);
//final _file =File.fromRawPath(bytes);
_image.image
.resolve(ImageConfiguration())
.addListener(ImageStreamListener((ImageInfo info, bool _) {
completer.complete(ThumbnailResult(
image: _image,
dataSize: _imageDataSize,
height: info.image.height,
width: info.image.width,
));
}));
return completer.future;
}
and this is how File is uploaded to firebase
String Thumbfileurl = await uploadFile(thumbResult.image, fileName, fileType);
And inside uploadFile()
final StorageUploadTask uploadTask = storageReference.putFile(file);
So as you see , A File is needed , but i have an Image , is there a way to Convert Image to File or is there any workaround to achieve this .

Display Default Image if wasn't picked by Image Picker in Flutter

I have an image picker function, that picks image from gallery and then assigns that to _image variable which is String. It converts it to base64 because that is what was necessary. I want to know how would I go about getting the default image from assets as the _image if no image was picked (picked image is null). Here's the code and things I've tried commented out, it is under else in code:
Future _getImage() async {
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
final file = File(pickedFile.path);
_image = Utility.base64String(file.readAsBytesSync());
} else {
//if image wasn't picked, get the default one from assets
print('No image selected.');
// final file = File(AssetImage('assets/defaultfood.jpg').toString());
// _image = Utility.base64String(file.readAsBytesSync());
//final file = File('assets/defaultfood.jpg');
//_image = Utility.base64String(file.readAsBytesSync());
}
});
}
add image placeholder like this ternary condition
child: pickedFile == null ? Image.asset("assets/images/man_user.png",height: 100, width: 100): Image.file(pickedFile, height: 100, width: 100),

How to use preference for showing profile picture in my application in flutter

I want to display a profile picture of the user when they log in. I am using the image URL stored in firestore database.
I want to keep the image in the app until logout. Every time I start the app, Image is called from that URL but I want to store it. I am new to flutter and have no clue to achieve this task.
Future<void> _getImage(ImageSource source) async {
var image = await ImagePicker.pickImage(source: source);
if (image != null) {
setState(() {
_cropImage(image);
});
}
Navigator.pop(context);
}
// Crop fetched image
_cropImage(File image) async {
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(ratioY: 1.0, ratioX: 1.0));
if (cropped != null) {
setState(() {
_imageFile = cropped;
uploadFile();
});
}
}
// Upload image file to firestrore Storage and get image URL
Future uploadFile() async {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('${Path.basename(_imageFile.path)}}');
StorageUploadTask uploadTask = storageReference.putFile(_imageFile);
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
var url = downUrl.toString();
await uploadTask.onComplete;
setState(() {
imageUrl = url.toString();
});
// Show message on successful image upload
AppUtils.showToast('Picture Uploaded', green, white);
// Updating database with Image URL
Firestore.instance
.collection('account')
.document(widget.user)
.updateData({"url": imageUrl});
}
// Display Image
ClipRRect(
borderRadius: BorderRadius.circular(200.0),
clipBehavior: Clip.hardEdge,
child: Container(
height: 200,
width: 200,
child: widget.photoUrl == null
? Image(
image: NetworkImage(
'https://cdn1.iconfinder.com/data/icons/technology-devices-2/100/Profile-512.png'),
fit: BoxFit.fill,
)
: Image(
image: NetworkImage(widget.photoUrl),
fit: BoxFit.fill,
))),
What you need is a proper State Management throughout your app.
You can check the Provider Package to get started.
You can find more information about State Management here and here

Flutter: why image_picker doesn't open the photos from my gallery?

I'm new in Flutter and can't get image_picker to open a picture from gallery.
It opens Gallery, but when I tap on a picture, just close gallery
My code is like this.. what i'm missing?
File _imagenTemporal;
var imagen;
Future getImagen(String opcion) async {
if (opcion == "camara") {
imagen = await ImagePicker.pickImage(source: ImageSource.camera);
} else if (opcion == "galeria") {
imagen = await ImagePicker.pickImage(source: ImageSource.gallery);
}
setState(() {
_imagenTemporal = imagen;
}
);
}
ImagePicker is just a FileChooser function that returns a Future<File> widget when the user selects a File from the gallery or takes a picture. You should use the returned file to construct an Image.file widget:
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: showSelectedImage();
),
Future<Image> showSelectedImage() async {
_imagenTemporal = await ImagePicker.pickImage(source: ImageSource.gallery);
return Image.file(_imageTemporal);
}