Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Calculate Base64 Image Size in Ionic and Angular project

Angular base64 image resize

In these articles, we will calculate an exact length Base64 photo from the 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. Calculate Base64 Image Size in ionic, let first create an ionic project, and install the required plugin.

Ionic or Angular Base64 image size calculation

To get the length of bytes we use the formula:

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

If you are building an ionic application only for a mobile device, then we can use the Ionic Cordova camera plugin otherwise is recommended to use the capacitor camera plugin. To demonstrate angular base64 image size calculation in kilobytes we’ll use an ionic Cordova camera to take an image in base64 and then perform the calculation of the image size.

Angular base64 image calculation

Step 1: Create an ionic project and add an ionic Cordova native camera
Once we execute the below command, it will allow us to select a framework and template. We have to select the Angular framework and select a blank template.

ionic start cordovaCameraApp
Angular base64 image resize
ionic cordova plugin add cordova-plugin-camera
npm install @ionic-native/camera

We have used an Ionic Cordova camera, you can use a Capacitor camera or another Angular camera. Once we had a base64 image from any one of the above sources, we can calculate the base64 image easily.

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

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  image: string;
  base64Str: any;
  kbytes: number;

  constructor(private camera: Camera) { }

  async takePhoto(sourceType) {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType
    };

    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64 (DATA_URL):
      this.image = 'data:image/jpeg;base64,' + imageData;
      this.base64Str = this.image.split(',');

      if (this.calculateImageSize(this.base64Str[1]) > 50) {
        alert('Reduce the size of image');
      }
    }, (err) => {
      // Handle error
      console.error(err);
    });
  }

  calculateImageSize(base64String) {
    let padding;
    let inBytes;
    let 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;
  }
}

In typescript, we first take images from the camera or image library in base64 format by specifying DestinationType.DATA_URL in-camera option. Once we have an image then we will use calculateImageSize method to get the ionic base64 image size in kilobytes. 

Step 3: Display base64 image in the home component template.
We have two variables one for image and another base64 image sizes in kilobytes. We use both to display image and size in our home page template.

<ion-header [translucent]="true">
  <ion-toolbar color="danger">
    <ion-title>
      Ionic base 64 image size calculation
    </ion-title>
  </ion-toolbar>
</ion-header>

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

Related posts

Calculate Base64 Image Size in Ionic and Angular project

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top