Calculate Base64 Image Size

In this articles, we will get exact length Base64 photo from ionic native Camera|Gallery in Kilobytes.
Base64 encodes three bytes to four characters. Sometimes, padding is added in the form of one or two ‘=’ characters.

To get the length of bytes we use the formula:

(3 * (LengthInCharacters / 4)) - (numberOfPaddingCharacters)

Step 1: Create and add an ionic native-camera plugin

Step 2: Add Typescript code to calculate base64 image size in KiloBytes in home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public image: string;
  public base64Str: any;
  private kbytes: number;
  constructor(private camera: Camera, public navCtrl: NavController) {
  }

  async takePhoto(sourceType) {
    try {
      const options: CameraOptions = {
        quality: 50,
        targetHeight: 300,
        targetWidth: 400,
        destinationType: this.camera.DestinationType.DATA_URL,
        encodingType: this.camera.EncodingType.JPEG,
        saveToPhotoAlbum: false,
        correctOrientation: true,
        mediaType: this.camera.MediaType.PICTURE,
        sourceType: sourceType
      }
      const result = await this.camera.getPicture(options);
      this.image = `data:image/png;base64,${result}`;
      console.log(this.image);
      this.base64Str = this.image.split(',');

      if (this.calculateImageSize(this.base64Str[1]) > 50 ){
        alert("Reduce the size of image");
      }
    }
    catch (err) { 
      console.error(err);
    }
  }

  calculateImageSize(base64String){
    let padding, inBytes, base64StringLength;
    if(base64String.endsWith("==")) padding = 2;
    else if (base64String.endsWith("=")) padding = 1;
    else padding = 0;

    base64StringLength = base64String.length;
    console.log(base64StringLength)
    inBytes =(base64StringLength / 4 ) * 3 - padding;
    console.log(inBytes);
    this.kbytes = inBytes / 1000;
    return this.kbytes;
  }

}

Step 3: Add User Interface in home.html

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      ID Card
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <img [src]="image" *ngIf="image">
  <p *ngIf="kbytes">Image size: {{ kbytes}} KB</p>
  <ion-row class="center">
    <ion-col width-50>
      <button ion-button (click)="takePhoto(1)">Show Camera</button>
    </ion-col>
    <ion-col width-50>
      <button ion-button (click)="takePhoto(0)">Show Album</button>
    </ion-col>
  </ion-row>
</ion-content>