Save ImagePicker Image in Shared Preferences - Flutter - flutter

I'm trying to save image picked from ImagePicker and store it in shared preferences and then retrieve it from there but no luck so far
To make my question more specific, how to save an image as a string in shared preference and then later retrieve it
Here is my code
File? profileImage;
void saveData(String key, String value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(key, value);
}
void getData(String key) async {
final prefs = await SharedPreferences.getInstance();
final image = await prefs.getString(key);
setState(() {
profileImage = image; //this would result into error because profileImage expect file type value
});
}
Future pickProfile() async {
final profileImagePicker = await ImagePicker().pickImage(source: ImageSource.gallery);
final File profile = File(profileImagePicker!.path);
final directoryPath = await getApplicationDocumentsDirectory();
final path = directoryPath.path;
final imageFile = await File(profileImagePicker.path).copy('$path/image1.png'); // What am I supposed to do after this step
saveData('profile', path); what value needs to be stored here, it expects a string
setState(() {
profileImage = profile;
});
}

To convert image into String you can use below code
final bytes = imageFile.readAsBytesSync();
String imageString = base64Encode(bytes);
To convert String to Image
Uint8List bytes = BASE64.decode(base64ImageString);
You can use the Image widget to diplay the Image
Image.memory(bytes);

Related

Upload image to Firebase Storage and show as Profile Image after login again

My problem is that, if I select or capture an image then it update and store to firebase but when I login again then the defualt image shows. below is the code for get image.
Future takePhoto(ImageSource source) async {
final pickedFile = await _picker.pickImage(
source: source
);
selectedImage = File(pickedFile!.path);
final _firebaseStorage = FirebaseStorage.instance;
var snapshot = await _firebaseStorage.ref()
.child('images/imageName')
.putFile(selectedImage!);
var downloadUrl = await snapshot.ref.getDownloadURL();
print("hi there is a print statement with url "+downloadUrl);
setState(() {
imageUrl = downloadUrl;
_imageFile = pickedFile;
});
}

Print QR code using esc_pos_printer flutter

I'm using esc_pos_printer package which can print a receipt over network. I need two features
Save a qr/bar code in the gallery
Print said qr/bar code using the thermal printer/regular printer
For saving the qr code I did:
static Future<File> _saveBarCode(GlobalKey key, String productId) async {
print("save bar code");
RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "/" + productId + ".png";
File imgFile = File(path);
print(imgFile.path);
return imgFile.writeAsBytes(pngBytes);
}
and
static void save(GlobalKey key, String productId) async {
_saveBarCode(key, productId).then((value) async {
bool? saved = await GallerySaver.saveImage(value.path);
print("saved: $saved");
}).catchError((error) {
print(error);
});
}
But the printing part is giving me trouble:
void printOverNetwork(GlobalKey key, String productId) async {
const PaperSize paperSize = PaperSize.mm80;
final profile = await CapabilityProfile.load();
final printer = NetworkPrinter(paperSize, profile);
final PosPrintResult result =
await printer.connect('192.168.0.123', port: 9100);
_saveBarCode(key, productId).then((value) {
if (result == PosPrintResult.success) {
// print the qr/barcode
}
});
}
How can I solve the issue?

Save Image From ImagePicker Locally as a Memory(cache)

I want to save an Image from ImagePicker as a Memory but error Occured . Can you Please help me with this function and if another function needed to load image please Mentioned it below.
Uint8List? memoryImage;
Future getImage() async {
final picker = ImagePicker();
final image = await picker.getImage(source: ImageSource.camera);
if (image == null) return;
final Directory directory = await getApplicationDocumentsDirectory();
final path=directory.path;
final Filename=basename(image.path);
File file = File('$directory/$Filename.jpg');
final bytes = await file.readAsBytes();
final byte1= file.writeAsBytes(bytes);
setState(() {
memoryImage = byte1 as Uint8List?;
});
}
With this line you can write image bytes as a file.
File imageFile = await File(fileSavePath).writeAsBytes(imageBytes);
To access the Uint8List from the file you need to use
Uint8List memoryImage = File(imagePath).readAsBytesSync();
Or
Uint8List memoryImage = await File(imagePath).readAsBytes();
here the problem in your code is you are assigning file to a Uint8List. That's the error I guess

how can i store multiple data in sharedpreferences?

I am getting user information like the username , profile pic and name .I want to store all that info inside Sharedpreferences so that i wont have to call firebase every time I need them.
here is how i am getting the data ,how can i store this data so that later on i can get user's name and its profilepic by checking it through its username ?
storeUsersInfo()async{
print('STORE CALLED');
QuerySnapshot querySnapshot = await DatabaseMethods().getUsers();
var length = querySnapshot.docs.length ;
print(length);
int i = 0 ;
while ( i < length ) {
print(name = "${querySnapshot.docs[i]["name"]}");
print(profilePicUrl = "${querySnapshot.docs[i]["profileURL"]}");
i++;
}
}
here is the firebase call
Future<QuerySnapshot> getUsers() async {
return await FirebaseFirestore.instance
.collection("users")
.get();
}
and if anyone needs anything else please ask .
You can store all the information in SharePreference by encoding picture objects to Base64String before storing them.
How you can encode it:
Future<String> encodeImageToBase64String(String imageUrl) async {
final response = await client.get(Uri.parse(imageUrl));
final base64 = base64Encode(response.bodyBytes);
return base64;
}
After Encoding the image, you can cache it to sharedPreference using
SharedPreferences pref = await SharedPreferences.getInstance();
//Save string to SharedPreference
pref.setString('image', encodedImageString);
How to Decode and use Image Later
//Get Encoded Image String from SharedPreferences
final base64String = pref.getString('image');
///Decodes Images file encoded to Base64String to Image
Uint8List decodeImageFromBase64String(String base64String) {
return base64Decode(base64String);
}
Finally, you can use this in your Image Widget like so
...
Image(image: MemoryImage(decodeImageFromBase64String))
Assuming you want to cache name, username and image gotten from firebase
//Create a model for the firebase data
class UserModel{
final String name;
final String username;
final String encodedImage;
UserModel(this.name, this.username, this.encodedImage);
String toJson(){
Map<String, dynamic> userMap = {
'name': name,
'username': username,
'image': encodedImage,
};
return json.encode(userMap);
}
}
//Encode the image HERE
encodeImageToBase64String(imageUrl);
//Pass in the parameters to the UserModel() constructor and Call //the toJson(), then Cache the Resulting String
String stringToCache = UserModel(nameString, usernameString, encodedImageString).toJson();
SharedPreferences takes a key and the data.
use this in an async funtion.
This syntax is sharedPreferences.setString(key, value)
So in a function,
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString("token", jsonResponse['access_token'].toString());
sharedPreferences.setString("userId", jsonResponse['customer_id'].toString());
You can get the stored data by sharedPreferences.getString(key).Like
var token = sharedPreferences.getString("token");
You can use a cache like https://pub.dev/packages/firestore_cache which does that for you.

Convert Uint8List to File

I'm using Image Picker web which works well. I can display image in Image.memory(), but this image in format Uintlist8. For save in storage need format File, my issue is how to save an image in Firebase Storage.
Web image picker:
class _SecondPageState extends State<SecondPage> {
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
});
}
}
Please Try ....
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.jpg').create();
file.writeAsBytesSync(_image);
});
}
}