Introduction
- Nodejs
- Latest Ionic 3 CLI
- Latest Cordova
- Node Command Line Window (Windows) or Terminal (OS X, Linux)
- Text Editor or IDE (e.g. Visual Studio Code, Atom,)
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 an 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 the 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.
- CameraThe Camera Plugin is used to take a picture and also capture a video.
- FileUsing 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 a 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 a camera plugin and file so we need to add a Camera plugin and File plugin to our app module file.
app.module.ts file
- //here importing lines for access camera object and file plugin to our app.
- import {
- Camera
- } from '@ionic-native/camera';
- import {
- File
- } from '@ionic-native/file';
- @NgModule({
- providers: [
- //here added class to our provider service block
- Camera,
- File
- ]
- })
- export class AppModule {}
Step 3
Now, it’s time to integrate with a component in our app.
app.ts file
- import {
- Camera,
- CameraOptions
- } from '@ionic-native/camera';
- import {
- File
- } from '@ionic-native/file';
- //here injecting camera and file class to our component part as object
- constructor(private camera: Camera, private file: File) {}
- //here this method is used to start a camera and take a picture and save a picture in specific mentioned part.
- public getPicture() {
- let base64ImageData;
- const options: CameraOptions = {
- //here is the picture quality in range 0-100 default value 50. Optional field
- quality: 100,
- /**here is the format of an output file.
- *destination type default is FILE_URI.
- * DATA_URL: 0 (number) - base64-encoded string,
- * FILE_URI: 1 (number)- Return image file URI,
- * NATIVE_URI: 2 (number)- Return image native URI
- */
- destinationType: this.camera.DestinationType.DATA_URL,
- /**here is the returned image file format
- *default format is JPEG
- * JPEG:0 (number),
- * PNG:1 (number),
- */
- encodingType: this.camera.EncodingType.JPEG,
- /** Only works when Picture Source Type is PHOTOLIBRARY or SAVEDPHOTOALBUM.
- *PICTURE: 0 allow selection of still pictures only. (DEFAULT)
- *VIDEO: 1 allow selection of video only.
- */
- mediaType: this.camera.MediaType.PICTURE,
- /**here set the source of the picture
- *Default is CAMERA.
- *PHOTOLIBRARY : 0,
- *CAMERA : 1,
- *SAVEDPHOTOALBUM : 2
- */
- sourceType: this.camera.PictureSourceType.CAMERA
- }
- this.camera.getPicture(options).then((imageData) => {
- //here converting a normal image data to base64 image data.
- base64ImageData = 'data:image/jpeg;base64,' + imageData;
- /**here passing three arguments to method
- *Base64 Data
- *Folder Name
- *File Name
- */
- this.writeFile(base64ImageData, “My Picture”, “sample.jpeg”);
- }, (error) => {
- console.log(Error Occured: ' + error);
- });
- }
- //here is the method is used to write a file in storage
- public writeFile(base64Data: any, folderName: string, fileName: any) {
- let contentType = this.getContentType(base64Data);
- let DataBlob = this.base64toBlob(content, contentType);
- // 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.
- let filePath = this.file.externalRootDirectory + folderName;
- this.file.writeFile(filePath, fileName, DataBlob, contentType).then((success) => {
- console.log("File Writed Successfully", success);
- }).catch((err) => {
- console.log("Error Occured While Writing File", err);
- })
- }
- //here is the method is used to get content type of an bas64 data
- public getContentType(base64Data: any) {
- let block = base64Data.split(";");
- let contentType = block[0].split(":")[1];
- return contentType;
- }
- //here is the method is used to convert base64 data to blob data
- public base64toBlob(b64Data, contentType) {
- contentType = contentType || '';
- sliceSize = 512;
- let byteCharacters = atob(b64Data);
- let byteArrays = [];
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
- let slice = byteCharacters.slice(offset, offset + sliceSize);
- let byteNumbers = new Array(slice.length);
- for (let i = 0; i < slice.length; i++) {
- byteNumbers[i] = slice.charCodeAt(i);
- }
- var byteArray = new Uint8Array(byteNumbers);
- byteArrays.push(byteArray);
- }
- let blob = new Blob(byteArrays, {
- type: contentType
- });
- return blob;
- }
Step 4
Calling the getPicture method.
- this.getPicture();
For further details, visit the official website.
- Camerahttps://ionicframework.com/docs/native/camera/
- File Writinghttps://ionicframework.com/docs/native/file/
- File LocationWhere 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.

Risto KurniawanPosted Dec 25, 2019, 7:37 AM
I want to save image in ion-img to internal storage, it is possible to use that code?
mahesh kumarPosted Aug 21, 2019, 7:50 AM
How to save csv file to desired loaction ionic 4
ravi patelPosted Jul 26, 2019, 7:27 AM
Getting this error please help
ravi patelPosted Jul 26, 2019, 7:26 AM
The string to be decoded is not correctly encoded.Error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
Harshitha PPosted Dec 19, 2018, 4:45 AM
Thank You.
Muthu KumarPosted Dec 13, 2018, 5:04 AM
Sorry that's my mistake, you can change like this, let DataBlob = this.base64toBlob(base64Data, contentType);
Harshitha PPosted Dec 12, 2018, 4:08 AM
What we need to pass in content to this method this.base64toBlob(content, contentType)