PWA mobile camera access
Asked Answered
L

7

25

My requirement is to access the mobile camera in iOS and android using the mobile browser.

Using Ionic PWA app can I access mobile camera in iOS and android device browsers? Looking for PWA solution using Cordova (not native solution).

Laurynlausanne answered 6/7, 2017 at 15:40 Comment(2)
Hi, I'm lokking for this answer too. Have you found anything please ?Jolt
Check this site, perhaps it can help you: whatwebcando.today/camera-microphone.htmlDissonance
O
48

While working on a PWA. I came across the need to access a mobile device's camera/images.(a native app was out of the question). After doing some research I came across this little nugget.

<input type="file" accept="image/*" capture="camera" />

By adding the accept and capture attributes I was able to access my phone's camera and images. I should also point out that you don't need to do anything special with your Server side (Node or PHP). It acts just like a standard file upload input in a browser.

Octo answered 19/5, 2018 at 16:35 Comment(2)
The only issue with HTML camera, when you turn to landscape (top to right), the photo is upside downVashtee
Shouldn't capture be user or environment?Impurity
F
4

You can open video devices in the web browser...

<video id="cameraPlayer"></video>

// find the video devices (font/back cameras etc)
navigator.mediaDevices.enumerateDevices().then(function (devices) {
    // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices
    devices.forEach(function (device) {
        if (device.kind === 'videoinput') {
            cameraDeviceIds.push(device.deviceId)
        }
    })
})

// attach camera output to video tag
navigator.mediaDevices.getUserMedia({
    video: { deviceId: { exact: cameraDeviceIds[currentCameraIndex] } }
}).then(function (stream) {
    document.getElementById("cameraPlayer").srcObject = stream
})

If you just want an image you can use an input

<input type="file" accept="image/*" id="inputPhoto" class="hidden" capture="environment" />

   // trigger capture
   document.getElementById('inputPhoto').click()

  // event handler for change
    function onInputPhotoChange() {
    if (document.getElementById('inputPhoto').files.length === 0) {
        return
    }


    var reader = new window.FileReader()
    reader.onloadend = function (event) {
        event.target.result
        // image data
        // note you may need to rotate using EXIF data on a canvas
    }

    // Read the file into memory as dataurl
    var blob = document.getElementById('inputPhoto').files[0]
    reader.readAsDataURL(blob)
}
Francklin answered 27/8, 2019 at 23:34 Comment(0)
V
3

If you want to use the camera in an Ionic PWA app, you can use Capacitor: https://capacitor.ionicframework.com/docs/apis/camera

I implemented the camera feature and it works 100%:

enter image description here

Vashtee answered 26/6, 2019 at 9:18 Comment(1)
I found Capacitor good, but my live video is flipped. It's a style problem but I have spent a long time and not found, how to fix this problem.Sewole
S
0

In addition to the above answers, you will have to add this in your index.html file, for the camera to work on PWA

<script nomodule="" src="https://unpkg.com/@ionic/[email protected]/dist/ionicpwaelements/ionicpwaelements.js"></script>
Sailing answered 29/6, 2019 at 18:26 Comment(2)
Could you add explanation/reference to how this answers the question.Lovieloving
yes, please have a look at these two post comments.. github.com/ionic-team/capacitor/issues/… forum.getcapacitor.com/t/camera-in-pwa-via-capacitor/59/…Sailing
C
0

The solution given above only make selection of file resticted to i mages category only. But we want to access camera or audio device here of browser. So, to rescue this challege here come api from browser("browsers are powerfull now yeah").

getUserMedia(:true/false)

Here <media_type> is type of media you want to access like audio,video You can set it as {audio: true/false} and {video:true/false}. But error "NotFoundError" will be returned if media not found.

Here is eg; :>

if('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices){ const stream = await navigator.mediaDevices.getUserMedia({video: true}) }

County answered 16/11, 2019 at 7:0 Comment(0)
V
0

It will run on Android and Ios platform with PWA and on a browser

home.page.ts file

import { Component } from '@angular/core';
import { Plugins, CameraResultType, Capacitor, FilesystemDirectory, 
CameraPhoto, CameraSource } from '@capacitor/core';
const { Camera, Filesystem, Storage } = Plugins;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor() {}
  async capturedImage(){
    const image = await Camera.getPhoto({
      resultType: CameraResultType.DataUrl, 
      source: CameraSource.Camera, 
      quality: 90 
    });
    console.log('image',image)
  }
}

home.page.html

 <ion-button expand="full" (click)="capturedImage()"> Captured Image</ion-button>
 
Ventilator answered 2/2, 2021 at 9:39 Comment(0)
F
-2

Accessing the camera via Cordova (and more specifically ionic since you tagged the ionic-framework in your question) is a matter of installing the plugin, whether you're using ionic or not. There are several camera plugins but the one recommended by ionic can be found here:

https://github.com/apache/cordova-plugin-camera

For example to add the plugin to your ionic project, simply run:

ionic Cordova plugin add cordova-plugin-camera

You would use it like this in your component's .ts file (for example):

import { Camera, CameraOptions } from '@ionic-native/camera';

constructor(private camera: Camera) { }

...


const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE
}

this.camera.getPicture(options).then((imageData) => {
 // imageData is either a base64 encoded string or a file URI
 // If it's base64:
 let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
 // Handle error
});

The above implementation was taken from here, where more details can also be found:

https://ionicframework.com/docs/native/camera/

Fungal answered 8/9, 2017 at 10:36 Comment(3)
A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.Marmalade
Thanks for the heads-up @paper1111Fungal
why you give code of cardova here we talk about capacitor only.Bare

© 2022 - 2024 — McMap. All rights reserved.