Tl:DR: i keep images as base64 strings in the database but I wanna start saving them as binary because i’ve heard it occupies less space. I don’t know where to get started in converting the image to binary and the binary to image.
Hey I have an app where I use camera plugin and allow the users to browse through their gallery and choose an image to use as their profile’s avatar, that image when chosen is returned as a base64 string and saved on the database in the user’s table. Later the app can get his database row and keep it as an object locally, which brings the image as a property and then I simply make an img take the base64 string and it displays the image just like that.
PS: im using mysql
this is some data from my test app so its okay to show it
Ricardo’s photo for example in my gallery is 17KB, I checked, but in base64 string to be stored in the database its 137KB, insane.
Thing is, I read a post on stackoverflow where an user said how base64 strings are 33% heavier than saving right away the binary of the image, so I’m now wondering, how can I achieve this? I’ve googled around but didn’t figure anything out.
Code I use to get the image and then update the image locally and also update the database with that image
async getPhoto(sourceType:number) {
const options: CameraOptions = {
quality: 100,
targetHeight: 300,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true,
sourceType: sourceType,
saveToPhotoAlbum: false,
allowEdit: true
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpeg;base64,' + imageData;
// set the image locally but also update the database
this.authenticationService.utilizador.avatar = base64Image;
this.utilizadorService.update(this.authenticationService.utilizador);
}, (err) => {
// Handle error
});
}
This is me using the image
<ion-avatar class="custom-avatar">
<img src="{{this.authenticationService.utilizador.avatar}}" alt="" srcset="">
</ion-avatar>