Ionic Vue Camera Application using Capacitor



In this tutorial, we will be learning about the integration of the Camera plugin with the Ionic Vue application. We will be using the Camera plugin of the Capacitor and creating an application in which we click the photograph and save it in our gallery. You will also learn the basic Vue JS app structure in this blog. However, if you are new to Vue JS or Ionic you can visit our BLOGS.

What is Ionic?

You probably already know about Ionic, but we put this section in every blog just for the sake of beginners, feel free to skip it

Ionic is a complete open-source SDK for hybrid mobile app development. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.

In other words — If you create native apps in Android, you code in Java. If you create native apps in iOS, you code in Obj-C or Swift. Both of these are powerful, but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS. I’m a huge fan of Ionic and have been developing Ionic apps for the last 4+ years.

Capacitor — How is it different from Cordova?

This section is relevant to only those who have been working with Ionic / Cordova for some time. Cordova has been the only choice available for Ionic app developers for quite some time. Cordova helps build an Ionic web app into a device installable app.

Capacitor is very similar to Cordova, but with some key differences in the app workflow

Here are the differences between Cordova and Capacitor (You’ll appreciate these only if you have been using Cordova earlier, otherwise you can just skip)

  1. Capacitor considers each platform project a source asset instead of a build time asset. That means Capacitor wants you to keep the platform source code in the repository, unlike Cordova which always assumes that you will generate the platform code on build time
  2. Because of the above, Capacitor does not use config.xml a similar custom configuration for platform settings. Instead, configuration changes are made by editing AndroidManifest.xml for Android and Info.plist for Xcode
  3. Capacitor does not “run on device” or emulate through the command line. Instead, such operations occur through the platform-specific IDE. So you cannot run an Ionic-capacitor app using a command like ionic run ios . You will have to run iOS apps using Xcode, and Android apps using Android studio
  4. Since platform code is not a source asset, you can directly change the native code using Xcode or Android Studio. This gives more flexibility to developers

In essence, Capacitor is like a fresh, more flexible version of Cordova.

What is Vue?

Vue is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

Now let's create our awesome Camera Application with the essence of Vue JS and capacitor.



Steps to Create Camera Application:-

  1. Create a new Ionic 5 Vue project using ionic-cli.
  2. Integrate Capacitor Camera plugin with Ionic 5 application.
  3. To build an Android Application on the device.
  4. Demonstration for the Camera Application.

Step 1:- Create a new Ionic 5 Vue project using CLI

To create a new Ionic 5 project with Vue JS, ionic-cli should be updated. If you do not have the latest CLI (Ionic-cli V6.12.2 — At the time of blog). You can run the below command to update/install the CLI:-

$ npm install -g @ionic/cli

Once the update is complete, Now we can create a new Ionic + Vue application. To create you can run the below command:-

$ ionic start cameraApp blank --type vue

The above command contains the name of the project after that you can pass template types like ‘blank’, ‘tabs’ to choose the layout of the Ionic Vue project. And at last, we have given vue as the type of framework to use. The command will take some time to create the project, and after that, a new project will be created in the working directory. Now we have the new project and we are all set to implement our Camera application.

Step 2:- Integrate the Capacitor Camera plugin with the Ionic 5 application

In the Ionic 5 project, the Home.vue page is already created and we will use this as the main view. Before continuing we will look at the basic structure of a Vue page.

Vue page code is divided into three major parts:-

  1. Template Part:- The HTML or the View part is enclosed by the template tags.
  2. Functional Part (i.e. JavaScript part):- In this part, most of the logic and events reside. We can import various components here and then use them in the template.
  3. CSS part:- In this part, we can define the CSS classes and IDs.

So first of all we will define the template of the HTML code for the camera application:- (src/views/Home.vue)


Here in this HTML code is enclosed between template tag and we have added the click event on button (@click=”ClickImage()”) and to add the conditional rendering we use the v-if=”render” like *ngIf in ionic angular. Complete explanation of functions is in a later section.

The above HTML code will compile and the application will look like this:-



We have to define the button click methods in the options of the Vue JS part. we have the option named as methods [Line 20 in below code] - we can define the functions [Like ClickImage() - Line 21, convertBlobToBase64() - Line 32, Save() - Line 42] inside it. Below is the implementation of Vue JS options:-


The logical part of the Vue page is enclosed inside the <script> tag and we first import all necessary modules inside the <script> tag. After Importing we define the modules inside the components option and then we can use Ion Components inside the <template> tag:-

components: {
IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
IonButton,
IonImg,
},

After that, we define the data object (i.e. the variables that can be used inside the template tag). To define the variable, we use the data option of the Vue JS, and the way we can define that is stated below (we simply return the object containing the variables):-

data(){ return  {imageUrl : '', render: false}},

We have imported the components, and plugins and defined the variables. And for defining methods we use the methods option in Vue JS. We can define methods option like below:-

methods: {
async ClickImage() {
const { Camera } = Plugins;
await Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri
}).then((image) => {
this.render = true;
this.imageUrl = String(image.webPath)
});
},
convertBlobToBase64 (blob: Blob) {
return new Promise((resolve, reject) =>{
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
},
async Save() {
const {Filesystem} = Plugins;
const response = await fetch(this.imageUrl);
const blob = await response.blob();
const base64Data = await this.convertBlobToBase64(blob) as string;
console.log('url', base64Data);
const savedFile = await Filesystem.writeFile({
path: new Date().getTime() + '.jpeg',
data: base64Data,
directory: FilesystemDirectory.Data
});
}
}

In the above code we have defined 3 methods:-

  1. ClickImage() :- In this method, we have used the Camera plugin and using its getPhoto() method with options of quality, allowEditing, resultType as its parameter. Basically, this function helps us to click the photograph.
  2. Save():- This method uses the File System plugin, which helps us to save the Image on our PC or the mobile phone. It uses the writeFile() method which saves the method.
  3. convertBlobToBase64():- This method helps us to convert the blob to base64 format to save the image on PC or mobile phone.

We are finally done with the template and script part, and we will add the styles part to our Home.vue page.

<style scoped>
.container {
flex: 1;
display: flex;
width: 100%;
justify-content: center;
align-content: center;
margin-top: 12px;
}
.img {
height: 300px;
width: 300px;
}
</style>

The above code adds the styles to our Home page. And if you want to add this functionality for PWA you can add the PWA-elements and then define them in main.ts file like this:-

$ npm install @ionic/pwa-elements

Once the package is installed, then import that into main.ts file :-

// Importing PWA Elements
import { defineCustomElements } from '@ionic/pwa-elements/loader';
// Defining PWA elements on window object
defineCustomElements(window);

We are done with our code and will demonstrate the application.

Step 3:- To build an Android Application on the device.

Platform install

Add the Android platform with

$ npm install @capacitor/android
$ npx cap add android

Build the app

Build the app once using

$ ionic build

Sync your assets and plugins with Android platform using

$ npx cap sync android

You should ideally open the project in Android Studio and run using the Android Studio IDE. Open the project in Android Studio using

$ npx cap open android

Now run the app on your device using Android Studio, and you get this!

Note: After adding a platform, if you make any changes in the app, you need to run ionic build and then npx cap sync to reflect those changes in the native platform

Step 4:- Demonstration of Camera Application.

In this section, we will demonstrate the application by clicking the photograph and saving it on a mobile phone.



Demonstration of Camera App

Conclusion

In this tutorial, we have learned how to implement the Camera application using an Ionic Vue application with a Capacitor. And if you want to know more about Ionic 5 features you can visit our Blog Section. And if you have any problem with the code, you can go and check the code HERE.


Next Steps

If you liked this blog, you will also find the following Ionic blogs interesting and helpful. Feel free to ask any questions in the comment section


Ionic React Full App with Capacitor

If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using Ionic 5 React Full App in Capacitor


Ionic 5 React Full App in Capacitor from Enappd

Ionic 5 React Full App in Capacitor from Enappd

Ionic Capacitor Full App (Angular)

If you need a base to start your next Angular Capacitor app, you can make your next awesome app using Capacitor Full App


Capacitor Full App with huge number of layouts and features

Capacitor Full App with huge number of layouts and features

Ionic Full App (Angular and Cordova)

If you need a base to start your next Ionic 5 app, you can make your next awesome app using Ionic 5 Full App


Ionic Full App with huge number of layouts and features

Ionic Full App in Cordova, with huge number of layouts and features



Title
Subtitle
Kicker


ionic-vue-camera-application-with-capacitor
Vaibhav Gehani

Full Stack Developer

SHARE BLOG

PUBLISHED BY

ionic-vue-camera-application-with-capacitor

Vaibhav Gehani

Full Stack Developer
ENAPPD