Ionic-transform image from base64 to JPG

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

  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;
  }
Author: Lucas Brito, 2019-07-31

2 answers

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

Since there are three most common ways to upload an image 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 it 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 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, follow the link .
  3. the last option is to use multipart / form-data, the difference is that in this case you need the image file object instead of base64. Follow the link of a very good tutorial.
 1
Author: victornjg, 2019-08-09 02:01:53

// 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;
}
 0
Author: i9on i9on, 2019-08-18 19:47:39