Ionic - Transform image from Base64 to JPG

Asked

Viewed 289 times

0

I’m making an app and I need to send an image to an api. But I only have the image in Base64 and I need it in jpg. Does anyone have any idea how I do it?

  public sendOnePhoto(photo: any) {
    const body = { file: photo, email: this.storage.getItem('access') };
    const data: Observable<any> = this.http.post(`${this.API_URL}/picture/upload`, body);
    return data;
  }

2 answers

1


Hello, you really need to send this image in jpg format to the server?

Because there are three most common ways to upload images to the server, they are:

  1. Send the Base64 of the image within a parameter of your http request, and when it arrives on the server you read this Base64 and save as an image in jpg format.
  2. Convert Base64 to blob, add the blob in the body of your http request and send. When the blob arrives on the server you can save it as an image in jpg format. There is already an answer from a user in Stackoverflow on how to do this conversion from Base64 to blob, follows the link.
  3. The last option is to use Multipart/form-data, the difference is that in this case you need the File object of the image instead of Base64. Follow the link of a very good tutorial.
  • The last reply (Point 3) was correct in my case! Thank you very much!

0

// Base64 url of image trimmed one without data:image/png;base64
string base64="/9j/4AAQSkZJRgABAQE...";
// Naming the image
const date = new Date().valueOf();
let text = '';
const possibleText = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 5; i++) {
   text += possibleText.charAt(Math.floor(Math.random() *    possibleText.length));
}
// Replace extension according to your media type
const imageName = date + '.' + text + '.jpeg';
// call method that creates a blob from dataUri
const imageBlob = this.dataURItoBlob(base64);
const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' });


dataURItoBlob(dataURI) {
   const byteString = window.atob(dataURI);
   const arrayBuffer = new ArrayBuffer(byteString.length);
   const int8Array = new Uint8Array(arrayBuffer);
   for (let i = 0; i < byteString.length; i++) {
     int8Array[i] = byteString.charCodeAt(i);
   }
   const blob = new Blob([int8Array], { type: 'image/jpeg' });    
   return blob;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.