How To Save An Image To A Specific Path In Ionic 3 Using Native Camera Plugin

In this article demonstrates how to take picture in camera and save a picture specific path in ionic 3 using native camera plugin. The following tools and requirements should prepare before starting this article.

Introduction

Ionic is a popular, open source, and cross-platform mobile app framework that is helpful in developing or building hybrid mobile apps quickly and easily. It will save you a lot of time and money.

This article demonstrates how to take a picture in a camera and save the picture's specific path in Ionic 3 using a native camera plugin. The following tools and requirements should be prepared before starting this article.

Once we've installed Node.js, we are able to install other tools on the terminal or command line. Run the following command.

npm install -g ionic cordova

Once the installation is finished, let’s start creating an Ionic 3 app.

Create Ionic 3 app

Open your node.js terminal and open a specific location to create the Ionic 3 app. Start a new Ionic project using ionic start command.

ionic start myApp

This command will take a few minutes because it has installed all dependencies and modules in a project. Now, change the location to myApp.

cd myApp

Once we've changed the location of myApp, add an Android platform to your app.

ionic cordova platform add android
ionic cordova platform add browser(For Browser)

Now, run the project using the following command.

ionic serve (For Browser)
ionic cordova run android(For Device)

Make sure that you have connected the device and the settings have been set.

Now, let’s start.

  • Camera
    The Camera Plugin is used to take a picture and also capture a video.

  • File
    Using the File Plugin, we can achieve the following -

    • Get the available free space
    • Check if the directory is available or not
    • Create a directory
    • Remove a directory
    • Move a directory from one place to another place,
    • Copy a directory
    • List an available directory
    • Set pre-defined path
    • Check if a file is available or not
    • Create a file
    • Remove a file
    • Write a file
    • Read a file as text
    • Read a file and return base64 data
    • Read a file and return data in a binary format
    • Read a file and return data in an array buffer format
    • Move and copy files
    • Get a directory or file etc.

Install and Configure Camera and File

Follow the below-mentioned steps.

Step1

Now, we have an Ionic app so we can move forward. First, install the camera plugin to our Ionic app using the following steps.

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera
 

Now, install the file plugin to the Ionic app using the following steps.

ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

Step 2

Now, we have already installed camera plugin and file so we need to add Camera plugin and File plugin to our app module file.

app.module.ts file            

  1. //here importing lines for access camera object and file plugin to our app.  
  2. import {  
  3.     Camera  
  4. } from '@ionic-native/camera';  
  5. import {  
  6.     File  
  7. } from '@ionic-native/file';  
  8. @NgModule({  
  9.     providers: [  
  10.         //here added class to our provider service block  
  11.         Camera,  
  12.         File  
  13.     ]  
  14. })  
  15. export class AppModule {}  

Step 3

Now, it’s  time to integrate with a component in our app.

app.ts file

  1. import {  
  2.     Camera,  
  3.     CameraOptions  
  4. } from '@ionic-native/camera';  
  5. import {  
  6.     File  
  7. } from '@ionic-native/file';  
  8. //here injecting camera and file class to our component part as object  
  9. constructor(private camera: Camera, private file: File) {}  
  10. //here this method is used to start a camera and take a picture and save a picture in specific mentioned part.  
  11. public getPicture() {  
  12.         let base64ImageData;  
  13.         const options: CameraOptions = {  
  14.             //here is the picture quality in range 0-100 default value 50. Optional field  
  15.             quality: 100,  
  16.             /**here is the format of an output file. 
  17.              *destination type default is FILE_URI. 
  18.              * DATA_URL: 0 (number) - base64-encoded string,  
  19.              * FILE_URI: 1 (number)- Return image file URI, 
  20.              * NATIVE_URI: 2 (number)- Return image native URI        
  21.              */  
  22.             destinationType: this.camera.DestinationType.DATA_URL,  
  23.             /**here is the returned image file format 
  24.              *default format is JPEG 
  25.              * JPEG:0 (number), 
  26.              * PNG:1 (number), 
  27.              */  
  28.             encodingType: this.camera.EncodingType.JPEG,  
  29.             /** Only works when Picture Source Type is PHOTOLIBRARY or  SAVEDPHOTOALBUM.  
  30.              *PICTURE: 0 allow selection of still pictures only. (DEFAULT) 
  31.              *VIDEO: 1 allow selection of video only.        
  32.              */  
  33.             mediaType: this.camera.MediaType.PICTURE,  
  34.             /**here set the source of the picture 
  35.              *Default is CAMERA.  
  36.              *PHOTOLIBRARY : 0,  
  37.              *CAMERA : 1,  
  38.              *SAVEDPHOTOALBUM : 2 
  39.              */  
  40.             sourceType: this.camera.PictureSourceType.CAMERA  
  41.         }  
  42.         this.camera.getPicture(options).then((imageData) => {  
  43.                 //here converting a normal image data to base64 image data.  
  44.                 base64ImageData = 'data:image/jpeg;base64,' + imageData;  
  45.                 /**here passing three arguments to method 
  46.                 *Base64 Data 
  47.  
  48.                 *Folder Name 
  49.  
  50.                 *File Name 
  51.                 */  
  52.                 this.writeFile(base64ImageData, “My Picture”, “sample.jpeg”);  
  53.             }, (error) => {  
  54.                 console.log(Error Occured: ' + error);       
  55.                 });  
  56.         }  
  57.         //here is the method is used to write a file in storage  
  58.         public writeFile(base64Data: any, folderName: string, fileName: any) {  
  59.             let contentType = this.getContentType(base64Data);  
  60.             let DataBlob = this.base64toBlob(content, contentType);  
  61.             // here iam mentioned this line this.file.externalRootDirectory is a native pre-defined file path storage. You can change a file path whatever pre-defined method.  
  62.             let filePath = this.file.externalRootDirectory + folderName;  
  63.             this.file.writeFile(filePath, fileName, DataBlob, contentType).then((success) => {  
  64.                 console.log("File Writed Successfully", success);  
  65.             }).catch((err) => {  
  66.                 console.log("Error Occured While Writing File", err);  
  67.             })  
  68.         }  
  69.         //here is the method is used to get content type of an bas64 data  
  70.         public getContentType(base64Data: any) {  
  71.             let block = base64Data.split(";");  
  72.             let contentType = block[0].split(":")[1];  
  73.             return contentType;  
  74.         }  
  75.         //here is the method is used to convert base64 data to blob data  
  76.         public base64toBlob(b64Data, contentType) {  
  77.             contentType = contentType || '';  
  78.             sliceSize = 512;  
  79.             let byteCharacters = atob(b64Data);  
  80.             let byteArrays = [];  
  81.             for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {  
  82.                 let slice = byteCharacters.slice(offset, offset + sliceSize);  
  83.                 let byteNumbers = new Array(slice.length);  
  84.                 for (let i = 0; i < slice.length; i++) {  
  85.                     byteNumbers[i] = slice.charCodeAt(i);  
  86.                 }  
  87.                 var byteArray = new Uint8Array(byteNumbers);  
  88.                 byteArrays.push(byteArray);  
  89.             }  
  90.             let blob = new Blob(byteArrays, {  
  91.                 type: contentType  
  92.             });  
  93.             return blob;  
  94.         }  

Step 4

Calling the getPicture method.

  1. this.getPicture();   

For further details, visit the official website.

  • Camera
    https://ionicframework.com/docs/native/camera/

  • File Writing
    https://ionicframework.com/docs/native/file/

  • File Location
    Where to Store a file,
    https://github.com/apache/cordova-plugin-file#where-to-store-files 

Summary

In this article, we discussed how to take a picture in a camera and save a picture's specific path in Ionic 3 using a native camera plugin.

If you have any questions/issues about this article, please let me know in the comments.