DEV Community

Jorge Vergara for Ionic

Posted on

Use your phone's camera in Ionic apps with Capacitor

We're going to use Capacitor to communicate with the native layer of the phone. In this example, we'll use the Camera API to be able to take pictures with the phone's camera.

One cool thing we're also going to do is to allow Capacitor to use web APIs if available, which means that if your app is running as a PWA it will also be able to use the camera.

You can find capacitor's official docs here, but I'll do my best to explain every bit we need to get our functionality ready.

Let's start with understanding a bit more about capacitor and its role in mobile development. The easiest way to "get it" is by seeing it as a replacement for Cordova.

Capacitor allows you to wrap your app into a native container and helps you communicate with the phone's native capabilities. You can use it to create a native build of your application (iOS and Android).

Configuring Capacitor

The first thing we need to do to 'activate' capacitor is to enable it through the Ionic CLI, so open your terminal (while inside of the project's folder) and type:

ionic integrations enable capacitor
Enter fullscreen mode Exit fullscreen mode

It will create the necessary files and install the capacitor packages, one thing to keep in mind, it creates a file called capacitor.config.json where you need to go and edit your appId.

By default, it sets it up to be io.ionic.starter, It's a good idea to change it to something more on-brand. The usual convention is to go with com.myDomainName.myProjectName so I'll name it com.javebratt.myApp.

Before adding the android/ios platforms, we need to generate a build of our project, or else capacitor will have unexpected errors.

Open your terminal and type:

ionic build
Enter fullscreen mode Exit fullscreen mode

That command will generate a build of our application inside the www/ folder, which is the folder Capacitor is watching.

> SIDE-NOTE: That command generates a development build. If you want to create a production build for your application, add the --prod flag.

Now we can add our platforms. You can add either iOS or Android by using the commands:

npx cap add ios
npx cap add android
Enter fullscreen mode Exit fullscreen mode

Remember that you need XCode installed on a Mac to build for iOS. Once you add your platforms, it's time to sync them and copy them over the build to the platform's respective folder. You do that by opening up the terminal and typing:

npx cap sync
Enter fullscreen mode Exit fullscreen mode

Using the Camera API

Now capacitor is ready to use, and we'll start by connecting the camera API.

For using the camera API the first thing we need is to import capacitor in the file we're using:

import { Plugins, CameraResultType } from '@capacitor/core';
const { Camera } = Plugins;
Enter fullscreen mode Exit fullscreen mode

Then you can create a function that takes the picture:

async takePicture() {
  try {
    const profilePicture = await Camera.getPhoto({
      quality: 90,
      allowEditing: false,
      resultType: CameraResultType.Base64,
    });
    this.guestPicture = profilePicture.base64String;
  } catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode
  • The line Camera.getPhoto({}); opens up the camera for you to take the picture, you can see all the properties here.
  • And profilePicture.base64String returns a base64 string of the picture (This one always makes me giggle because I made the PR for that 😃)

And that's it. You can use that base64 string to upload to your favorite storage provider, (I use Firebase Cloud Storage).

But Jorge, you said it was going to work on the web

Heck yeah, you can! That's the beauty of using Capacitor.

Some Capacitor plugins, such as Camera, have web-based UI available when not running natively.

For example, calling Camera.getPhoto() will load a responsive photo-taking experience when running on the web.

To enable these controls, you must add @ionic/pwa-elements to your app.

For that, the first thing to do is to stop our ng serve or ionic serve.

Then in the terminal, you type:

npm install @ionic/pwa-elements
Enter fullscreen mode Exit fullscreen mode

And then go into the main.ts file and define the custom elements:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

import { defineCustomElements } from '@ionic/pwa-elements/loader';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.log(err));

// Call the element loader after the platform has been bootstrapped
defineCustomElements(window);
Enter fullscreen mode Exit fullscreen mode

And that is it. Now you have a fully functional way of capturing photos with your camera.

Got any questions? You can find me on twitter as @javebratt 😃.

If you want to get started with Ionic & Firebase to build serverles applications consider enrolling in my free course here.

Latest comments (4)

Collapse
 
sagarkakad profile image
sagarkakad

hi
camera working while ionic serve but when we build app using ionic build --prod and host the camera showing err camera not found

any solution please

Collapse
 
robbsadler profile image
RobbSadler

Thanks for the tutorial, Jorge!

I'm interested in creating an app that uses the camera, but puts the photos in the camera's folder. All of the examples I have found save the files to a local storage, which makes them unavailable to other app that use the camera's photos. Do you know where an example might be like this, or would you be able to extend this tutorial?

Thanks again!

Collapse
 
dotnetkow profile image
Matt Netkow

Great stuff, Jorge! Keep it coming :)

Collapse
 
javebratt profile image
Jorge Vergara

Thanks Matt! 😃