Use your phone's camera in Ionic apps with Capacitor
Tags: ionic, capacitor
Published: 2020-01-31 18:28:00

---
title: "Use your phone's camera in Ionic apps with Capacitor"
published: true
description: "In this guide, you'll learn how to use the native camera of your phone using Capacitor, works for hybrid apps and web apps as well."
tags: ["ionic", "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](https://capacitor.ionicframework.com/docs/), 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:

```sh
ionic integrations enable capacitor
```

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:

```sh
ionic build
```

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:

```sh
npx cap add ios
npx cap add android
```

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:

```sh
npx cap sync
```

## 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:

```js
import { Plugins, CameraResultType } from '@capacitor/core';
const { Camera } = Plugins;
```

Then you can create a function that takes the picture:

```js
async takePicture() {
  try {
    const profilePicture = await Camera.getPhoto({
      quality: 90,
      allowEditing: false,
      resultType: CameraResultType.Base64,
    });
    this.guestPicture = profilePicture.base64String;
  } catch (error) {
    console.error(error);
  }
}
```

- The line `Camera.getPhoto({});` opens up the camera for you to take the picture, you can see [all the properties here](https://capacitor.ionicframework.com/docs/apis/camera#api).
- 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:

```sh
npm install @ionic/pwa-elements
```

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

```js
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);
```

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](https://twitter.com/javebratt) 😃.

If you want to get started with Ionic & Firebase to build serverles applications consider enrolling in my [free course here](https://javebratt.com/).