Ionic 4 – Camera with Capacitor

Hi Friends,

Hope you are all well. I know, it’s been a long time since I made a post on Ionic., but as I have been mentioning repeatedly, I am waiting for a stable release of Capacitor as I believe it would literally change the world of Ionic. Native apps written in Angular.. How does that sound ?

Anyway, in this post, let’s talk about bringing camera into your Ionic app built with capacitor.

A screencast of this post:

Scaffold out a new Ionic project with Ionic cli, ensuring that you choose no when asked whether you want your app to be integrated with Cordova.

Once that is done go ahead and install capacitor using the below command.

Now go ahead and uninstall cordova-splashscreen plugin using the below command.

Go ahead and initialise capacitor in your app using the following command.

Now simply take a build using npm run build command and then to copy the files from the build directory to android directory use the below command.

You are all set for it.

Now open up home.html and modify the code as shown below.

We are simply placing an image tag and a button here which upon clicked will invoke a function called captureImage().

Open up home.ts and wire this up with some functions.

Cool right ? The code is pretty much self explanatory.  We are simply using the camera plugin and invoking one of the methods present in it named getPhoto() to capture and get the path of the image which we are then passing on to yourImage. This is property binded to the image tag and hence the image would be displayed on your screen now.

Now to run this app.

Build the project once again using npm run build. The use the below command.

This is similar to npx cap copy and will synchronise the files between the www directory and the android directory.

Now open android-studio and open your project’s android directory there. As soon as it’s opened, it should automatically try to build the project. Now simply run the project on your app from android studio.

Note that we need to use android-studio here since we are not using Apache cordova to build our project. We are using the native android sdk and this is what separates capacitor from cordova.

Hope this helped you guys, if you found this helpful, kindly share it with someone and help them too.

Thanks for reading. Peace.. :)

Liked it? Take a second to support admin on Patreon!