flutter upload imagage file - flutter

There is a place to upload images in the flutter app, it is uploaded to S3, and it takes an average of 10 seconds to upload via the API in the backend, the image size is 800:800, the size is around 300 kb, how can I speed it up?
uploadFile(image) async {
var file = File(image.path);
await apiController.newUploadImage(file).then((data) async{
if(data != null){
await updateStatus("", data['id']);
}
});
Future getImage(bool isFromCamera) async {
return await imagePicker.getImage(
source: isFromCamera ? ImageSource.camera
: ImageSource.gallery,
maxHeight: 800.0,
maxWidth: 800.0
);
}

Related

Flutter Firebase: storage on web with imagePicker

I have an implementation of imagePicker working with the mobile portion of my app, but i am currently trying to make it work on web too. Im getting an image with the following code:
ImagePicker _picker = ImagePicker();
final XFile? _image = await _picker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
);
if (_image == null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('No image was selected.')));
}
if (_image != null) {
var f = await _image.readAsBytes();
StorageRepository()
.updateImage(user, _image, index);
}
Which leads to my confusion. My current storage method looks like this:
Future<void> uploadImageWeb(User user, XFile image, int? index) async {
try {
await storage
.ref('${user.id}/${image.name}')
.putFile(
File(image.path),
)
.then(
(p0) => FirestoreRepository().updateUserPictures(
user,
image.name,
index,
),
);
} catch (err) {
print(err);
}
}
Which obviously i cant use xfile, i have to use the Uint8List. But how do i read any data from that in a meaningful way to upload it to the storage bucket?
Thanks!

flutter firebase storage throwing unknown error [duplicate]

This question already has an answer here:
Firebase Storage Only showing when on certain VPN
(1 answer)
Closed 7 months ago.
edit: i notice that the code only runs till the below code and then gets out with the error. also, do note that the code provided used to work today
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName+getRandomString(50)}");
i am trying to upload a profile picture to firebase storage and then display it on a circular avatar. my code is as follows.
void pickUploadCameraImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.camera,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName + getRandomString(50)}");
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName+getRandomString(50)}");
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
however, the terminal is throwing me with this error.
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: [firebase_storage/unknown] An unknown error occurred, please check the server response.
i have tried to deleting the firebase storage bucket and recreating a new one but it is still giving me this error. tia for all inputs
update: turns out, i have to use a vpn where my storage is located to access the file. everything works as it should be now
Try this way.
import 'package:firebase_storage/firebase_storage.dart' as prefixStorage;
final int timestamp = DateTime.now().millisecondsSinceEpoch;
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickVideo(source:ImageSource.gallery);
final prefixStorage.Reference firebaseStorageRef = firebaseStorage
.ref()
.child('images')
.child(
'/$timestamp${image?.path.substring(image.path.indexOf('.'), image.path.length)}');
await firebaseStorageRef.putData(await image.readAsBytes());
final String? imageURL = await firebaseStorageRef.getDownloadURL();
Try giving it a child when you are uploading image to 'member_profile_pictures'.
void pickUploadCameraImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.camera,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures").child('${fileName + getRandomString(50)}');
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures").child('${fileName + getRandomString(50)}');
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
Im also in Singapore and facing firebase storage upload issue from this morning (yesterday still no issue), our own system haven't update anything.

Difference between image and video in XFile

This is my method for taking a picture:
handleTakePhoto() async {
Navigator.pop(context);
XFile? file = await ImagePicker()
.pickImage(source: ImageSource.camera, maxWidth: 960, maxHeight: 675);
setState(() {
this.file = file;
bytes = File(file!.path).readAsBytesSync();
});
}
while this is the one for taking a video:
handleTakeVideo() async {
Navigator.pop(context);
XFile? file = await ImagePicker()
.pickVideo(source: ImageSource.camera, maxDuration: const Duration(seconds: 10));
setState(() {
this.file = file;
bytes = File(file!.path).readAsBytesSync();
});
}
As you can see they are pratically identical, but later on my program I need to know if file is an image or a video. How can I do?
They method for taking pictures and video might be identical but the image file and video file are not identical, the contain different file extensions. an image file will either be .jpg, .jpeg or .png. you can print the file path to see these yourself. print(file.path).
check out this Flutter: Is the file an image or not? to help differentiate them.

Flutter rebuilds widget without waiting for code execution

I have a function to upload image to the server. However the widgets starts rebuilding while the image is being uploaded and does not execute code after image is uploaded.
InkWell(
child: Icon(
Icons.camera,
size: 50,
color: Colors.red[400],
),
onTap: () {
_imageFile =
_picker.getImage(source: ImageSource.camera);
_imageFile.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
)
This is the output on the console from print statements
I/flutter (10171): Calling build Method
I/Timeline(10171): Timeline: Activity_launch_request time:68831133
I/flutter (10171): Uploading image to server
I/flutter (10171): Calling build Method
I/flutter (10171): Image uploaded successfully
As can be seen above no other code is executed and the widget has rebuilt itself. What am I possibly doing wrong?
_imageFile = _picker.getImage(source: ImageSource.camera);
its not right, getImage is an Asynchronous function so you need to wait for it to finish.
do this - _imageFile = await _picker.getImage(source: ImageSource.camera);
If you want to use then do it like this,
_picker.getImage(source: ImageSource.camera).then((image)...your code...)
That's because when you're using _imageFile = _picker.getImage(source: ImageSource.camera); the _imageFile result will come in the future and your next code is executed.
You can fixed the problem either using await:
onTap: () async {
_imageFile =
await _picker.getImage(source: ImageSource.camera);
if (_imageFile != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
},
Or keep using then with a slight change:
onTap: () {
_picker.getImage(source: ImageSource.camera)
.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
See explanation about await & then: Async/Await/then in Dart/Flutter

image_picker plugin for flutter shows unusual warning

I am using the following code to pick an image with maxHeight/width to save space.
void openGallery()async {
var gallery = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxHeight: maxImageSize,
maxWidth: maxImageSize,
);
if (gallery!=null) {
var bytes = await gallery.readAsBytes();
if (DEBUG) print('Image bytes: ${bytes.length / 1024} KB');
if (DEBUG) print('Image path: ${gallery.path}');
setState(() {
List<int> imageBytes = gallery.readAsBytesSync();
_imageB64 = base64Encode(imageBytes);
// decoded = base64Decode(_imageB64);
if (DEBUG) print('Base64 String length: ${_imageB64.length / 1024} KB');
});
}
}
I am getting this following warning in my console:
image_picker: compressing is not supported for type (null). Returning the image with original quality
flutter: Image bytes: 153.583984375 KB
flutter: Image path: ...myimagpath.jpg
flutter: Base64 String length: 204.78125 KB
1) On one side I can see that my image is reduced in size as it is only 200kB but on the other hand the first line is confusing me.
2) Also, I was under the impression that BASE64 encoded images get smaller in size, As I want to save them to Firebase, will there be a problem saving them as just 'bytes' (as it is 153kb)?
Try this, It's working fine with my code.
var selectedProfileImage;
Future _getImage(bool fromCamera) async {
File image;
if (fromCamera) {
image = await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 150.0, maxHeight: 150.0);
} else {
image = await ImagePicker.pickImage(source: ImageSource.gallery, maxWidth: 150.0, maxHeight: 150.0);
}
if (image != null) {
// Initiate the ProgessBar
selectedProfileImage = image;
}
}