Encode image to photobase64 - flutter

I am encoding the image to photobase64 but I am only getting parts of the image. The encoded code given to me is not the full code.
Future pickGallery() async {
try {
final pickedImage = await ImagePicker().pickImage(
source: ImageSource.gallery,
);
if (pickedImage != null) {
image = File(pickedImage.path);
List<int> photobytes = await image!.readAsBytes();
setState(() {
String photobase = convert.base64Encode(photobytes);
print(photobase);
});
} else {
Utils.showAlertSnackBar('No image selected.');
}
} on PlatformException catch (e) {
print('Failed to pick image: $e');
}
}
This encoded code below gave me this result.
iVBORw0KGgoAAAANSUhEUgAAASUAAAFACAYAAAD6XmqeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAGIHSURBVHhe7Z0HYBzF3fafu1PvvXfbkuXeewFiU4LpPUBoIUASUkheUnkLpEBIQhL4SEgIIcEECBCaDQbj3rssF9mSrN5779J+86zvzPl0dzpJd7qVPb9k8Glvd3ZmduaZ/8z+b0anCCCRSCQaQW/8VyKRSDSBFCWJRKIppChJJBJNIUVJIpFoCilKEolEU0hRkkgkmkKKkkQi0RRSlCQSiaaQoiSRSDSFFCWJRKIppChJJBJNIUVJIpFoCilKEolEU0hRkkgkmkKKkkQi0RRSlCQSiaZw+SJvF+sacjqdzvjJdThato6kZai4nBHHhchYPOeLDZeKEqPu7+9HX1+f8cjFgcFggKenp/Ev18FyHRgYUIM12GD0er2aHv5rC17f29trV1SYH8ZjC0fiuNBgmXp4eNgtW8nwcZkoMdru7m7k5ubi1KlT6t/2KvWFABsmRXjSpEmYN2+e8ahroADk5+ejvLwcLS0tqkCZGofpkfr6+iIiIgITJ05U/7VFVVUV9u3bh46OjkFiynh5bP78+UhKSjIeHUxlZaUaR2dn55gIsrth+bNMZ8+ejbCwMClMTsRlosQG2tDQgBdeeAF//OMf1b99fHyM316YsAGzYX/961/Hc88951LTvrW1FS+//DI+/vhjVfTNBYVlzRAfH4+FCxfia1/7GhYsWKB+Z42tW7eqaS4rK0NQUJDx6Fna2toQEhKCP/zhD7jpppuMRwfz+eef4+GHH0ZFRcWgOC5EmpubsWjRIjz99NOYO3euajFJnARFyRUIi0ERPbDyjW98g6J3UYXbbrtNEaJgLAnX0NTUpPz0pz9VhFVmNQ0MAQEBypo1axQhOsarrLNu3TpFCKjVOEzh73//u/Fs67z//vtWr7uQQ0pKirJlyxalp6fHWAoSZ+B

I solved it. Using print() gives limited results. Therefore, I used log() to show the full the photobase64 code.

Related

how to handle the time lag after capturing the image ImagePicker Flutter

im learning flutter and now tried to capture the photo with ImagePicker package from the following method, but after I successfully capture the photo, there is always 1 sec until app get the data and jump to next page:
Future pickImage(ImageSource source) async {
try {
var image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final imagePermanent = await saveImagePermanently(image.path);
selectedImage = File(imagePermanent.path);
isUploaded.value = !isUploaded.value;
update();
} on PlatformException catch (e) {
print('Failed to pick image: $e');
}
}
Future<File> saveImagePermanently(String imagePath) async {
final directory = await getApplicationDocumentsDirectory();
final name = basename(imagePath);
final image = File('${directory.path}/$name');
return File(imagePath).copy(image.path);
}
now my solution is adding a listener onInit when image is created with GetX:
#override
void onInit() {
super.onInit();
ever(isUploaded, (value) {
Get.to(
() => AddPersonProfileAddDetails(),
);
});
}
So is there a way to detect the status of capturing the image like finished/failed/progressing, thanks for any clue or let me know a better way to jump to next page after capturing the image, thanks a lot!

How I can save each image in different folder for each click in flutter?

I am using gallery_saver package for saving image.
I want when I press the capture button Image will save different folder for each click. How I can archive it? Please help me.
Save Image method here:
CameraController? controller;
void _takePhoto() async {
try {
if (controller != null) {
if (controller!.value.isInitialized) {
image = await controller!.takePicture();
try{
GallerySaver.saveImage(image!.path);
} catch(e) {
Fluttertoast.showToast(msg: "Image not saved" + e.toString());
}
}
}
} catch (e) {
print(e); //show error
}
}
Copy file data to another location
And give that file to gallery saver.
CameraController? controller;
void _takePhoto() async {
try {
if (controller != null) {
if (controller!.value.isInitialized) {
XFile? image = await controller!.takePicture();
// Read file and save it to new location
final buffer = await image.readAsBytes();
await new File(<newPath>).writeAsBytes(buffer);
// Give that new path to Gallerysaver
try{
GallerySaver.saveImage(<newPath>);
} catch(e) {
Fluttertoast.showToast(msg: "Image not saved" + e.toString());
}
}
}
} catch (e) {
print(e); //show error
}
}

I want to delete the captured image via wechat_camera_picker Flutter

For image_picker MainActivity destruction I wanted to use other plugin to pick image. And I found wechat_camera_picker as an alternative. But there was a problem while capturing the image. The captured image saved on Local Storage after selecting the image. Here is my code.
Future<File> getImageByCamera(BuildContext context) async {
try{
final AssetEntity result = await CameraPicker.pickFromCamera(
context,
pickerConfig: CameraPickerConfig(
shouldDeletePreviewFile: true,
enableRecording: false,
textDelegate: EnglishCameraPickerTextDelegate(),
),
);
if(result != null){
File pickedFile = await result.file;
pickedFile = await compressFile(pickedFile);
return pickedFile;
}else{
return null;
}
}catch(error){
print(error);
return null;
}
}
Does anyone have any solution of this problem?
you can use the below function to delete the locally stored file.
Future<bool> deleteFile(File pickedFile) async {
try {
await pickedFile.delete();
return true;
} catch (e) {
return false;
}
}
You can check the Delete Function Documation for referenece.

Upload image to server flutter (Image picker)

I want to upload an image to server
I'm using the Image Picker plugin to pick image
this code work without any exception on samsung tab
but Catch error on xiaomi phone.
the onImageButtonPressed run in all devices.
Future<void> onImageButtonPressed({
BuildContext? context,
}) async {
try {
final XFile? pickedFile =
await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
imageFileList!.add(pickedFile);
logger.i('done , image picked');
File image = File(pickedFile.path);
logger.i(image); // on xiaomi and samsung log the same result "File: '/data/user/0/com.grand.technology.driver/cache/8227d4f4-df70-441d-9677-b95b64b1bf323122241454085685040.jpg'"
await uploadOrderPic(order.id.toString(), image);
}
update();
} catch (e) {
pickImageError = e;
logger.e(e);
update();
}
}
but the exception happen here
uploadOrderPic(String id, File image) async {
uploading.value = true;
var response = await OrderApi()
.uploadOrderPic(orderID: id, image: image)
.then((value) {
logger.i(value.data); //samsung tab log Instance of 'UploadedImage' but xiaomi phone catch error
uploading.value = false;
var uploadedImage = (value.data) as UploadedImage;
imageURLsList.add(uploadedImage.url!);
}).catchError((error) {
Get.snackbar('Failed', 'Uploading Image Failed',
backgroundColor: redColor);
logger.e(error); // type 'Null' is not a subtype of type 'UploadedImage' in type cast
});
try {
} on TimeoutException {
Get.snackbar(
'Connection Error', 'Check Your Internet Connection Please!');
} catch (e) {
logger.e(e);
}
}
this code upload image to server
Future<ApiResponse> uploadOrderPic(
{required String orderID,
required File image}) async {
ApiResponse apiResponse = ApiResponse();
var token = await getToken();
try {
var request = http.MultipartRequest("POST", Uri.parse(uploadPicUrl));
request.files.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['id'] = orderID;
request.headers[HttpHeaders.authorizationHeader] = 'Bearer $token';
var response =
await request.send().then((value) => http.Response.fromStream(value));
apiResponse.data =
UploadedImage.fromJson(jsonDecode(response.body)['data']);
} catch (e) {
logger.e(e);
apiResponse.error = serverError;
}
return apiResponse;
}

What is the right way of reducing image size captured from flutter camera plugin

I am using the example code from Flutter Camera Plugin. I want to reduce Image size once I capture the image and store it in imageFile variable.
I am not sure is there a built in feature available. didn't find any information in their documentation.
I tried to use Image Plugin to achieve it like below. but it is not working. the entire application stops it function when you use it.
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
XFile resizeImage(img) {
var image = imageP.decodeJpg(File(img.path).readAsBytesSync());
var thumbnail = imageP.copyResize(image, width: 400);
File(img.path).writeAsBytesSync(imageP.encodeJpg(thumbnail));
return XFile(img.path);
}
There is a bug in Image Package.... I used flutter_native_image Package and it worked....
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
resizeImage(file) // this is what I tried to add to achieve it...
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) showInSnackBar('Picture saved to ${file.path}');
}
});
}
here is the image compression function code.
Future<XFile> resizeImage(img) async {
ImageProperties properties =
await FlutterNativeImage.getImageProperties(img.path);
File compressedFile = await FlutterNativeImage.compressImage(img.path,
quality: 90,
targetWidth: 500,
targetHeight: (properties.height! * 500 / properties.width!).round());
// delete original file
try {
if (await img.exists()) {
await img.delete();
}
} catch (e) {
// Error in getting access to the file.
}
return XFile(compressedFile.path);
}