Converting image to base 64

can anyone help me converting the image to base64 before sending it to the server
below is the code I’m using…

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ActionSheetController, ToastController, Platform, LoadingController, Loading  } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { File } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { FilePath } from '@ionic-native/file-path';


declare var cordova: any;


/**
 * Generated class for the SecFourPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-sec-four',
  templateUrl: 'sec-four.html',
})
export class SecFourPage {

  ionViewDidLoad() {
    console.log('ionViewDidLoad SecFourPage');
  // }
  // pickImg(){
  //   let options = {
  //     destinationType   : Camera.DestinationType.DATA_URL,
  //     sourceType        : Camera.PictureSourceType.PHOTOLIBRARY
  // };
  //   navigator.camera.getPicture(
  //     (data)  => {
  //       let image = "data:image/jpeg;base64," + data;
  //     },
  //     (error) => {  },
  //     options
  // );
    
  }
  lastImage: string = null;
loading: Loading;
constructor(public navCtrl: NavController, private camera: Camera, private transfer: FileTransfer, private file: File, private filePath: FilePath, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, public platform: Platform, public loadingCtrl: LoadingController) { }
public presentActionSheet() {
  let actionSheet = this.actionSheetCtrl.create({
    title: 'Select Image Source',
    buttons: [
      {
        text: 'Load from Library',
        handler: () => {
          this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
        }
      },
      {
        text: 'Use Camera',
        handler: () => {
          this.takePicture(this.camera.PictureSourceType.CAMERA);
        }
      },
      {
        text: 'Cancel',
        role: 'cancel'
      }
    ]
  });
  actionSheet.present();
}
public takePicture(sourceType) {
  // Create options for the Camera Dialog
  var options = {
    quality: 100,
    sourceType: sourceType,
    saveToPhotoAlbum: false,
    correctOrientation: true
    
  };
 
  // Get the data of an image
  this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
    
    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
      this.filePath.resolveNativePath(imagePath)
        .then(filePath => {
          let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
          let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
        });
    } else {
      var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
      var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
      this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    }
  }, (err) => {
    this.presentToast('Error while selecting image.');
  });
}
private createFileName() {
  var d = new Date(),
  n = d.getTime(),
  newFileName =  n + ".jpg";
  return newFileName;
}
 
// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
  this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
    this.lastImage = newFileName;
  }, error => {
    this.presentToast('Error while storing file.');
  });
}
 
private presentToast(text) {
  let toast = this.toastCtrl.create({
    message: text,
    duration: 3000,
    position: 'top'
  });
  toast.present();
}
 
// Always get the accurate path to your apps folder
public pathForImage(img) {
  if (img === null) {
    return '';
  } else {
    return cordova.file.dataDirectory + img;
  }
}
public uploadImage() {
  // Destination URL
  var url = "http://;
 
  // File for Upload
  var targetPath = this.pathForImage(this.lastImage);
 
  // File name only
  var filename = this.lastImage;
 
  var options = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,
    mimeType: "multipart/form-data",
    params : {'i2': filename}
  };
 
  const fileTransfer: FileTransferObject = this.transfer.create();
 
  this.loading = this.loadingCtrl.create({
    content: 'Uploading...',
  });
  this.loading.present();
 
  // Use the FileTransfer to upload the image
  fileTransfer.upload(targetPath, url, options).then(data => {
    this.loading.dismissAll()
    this.presentToast('Image succesful uploaded.');
  }, err => {
    this.loading.dismissAll()
    this.presentToast('Error while uploading file.');
  });
}

}



Why would you want to convert it to base 64? Aren’t you submitting a form? I see that you are using file transfer plugin, which is deprecated, but shouldnt hurt anything. But, why not just submit the form directly?

A base 64 string will inflate the size of the image quite a bit. I’d recommend you just don’t do that and instead just submit the image as a file/blob with form data.

Actually the backend requires the image in base64. That’s why I need it.
Can You help me out.

Eww…that is not great. You’re data transfer will be slower and you’ll use more of your users data.

But, if you have to then you have to. Base64 is just a string. The camera and image picker plugins both have options to get back a data url, which is ultimately just a base64 string. Simply pass those as form values, they’re just strings like just like someone name or whatever.

But, if the server truly needs base64…you don’t want the file transfer plugin for sure, because you aren’t transfering files. You’re just sending a string over the internet.

Can you please help me through code because I have tried but was not successful in my attempts. I have already given my code above.
Thanks.

Sorry the guy above answered your question with “Eww…” just rude and unhelpful. Currently stuck on the same issue and the response frustrated me enough to comment - I have nothing else to offer to help.

I thought it was a great response. The “Eww” was targeted at the backend, which is apparently mandating that the app use a transport format that needlessly wastes an extra 33% of user resources. The rest of the comment explained exactly how to go ahead and do it anyway.