AngularJS uses HTML5 mobile phone cameras to take photos _ AngularJS

Source: Internet
Author: User
This article mainly introduces AngularJS's materials for taking photos using HTML5 mobile phone cameras. For more information, see 1. Project Background

The company developed a website. when making changes to the user's profile picture, the leaders mentioned the addition of a function for modifying the profile picture by taking a camera. Because our website is developed based on Html5, we use H5 to take photos directly. At first, I thought this function was very simple, but I found it was not that simple.

In AngularJs, this is an example of successfully calling the camera to take a photo and upload it:

2. how to call a camera

$scope.photoErr = false;$scope.photoBtnDiable = true;var mediaStream = null,track = null;navigator.getMedia = (navigator.getUserMedia ||navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||navigator.msGetUserMedia);if (navigator.getMedia) {navigator.getMedia({video: true},// successCallbackfunction (stream) {var s = window.URL.createObjectURL(stream);var video = document.getElementById('video');video.src = window.URL.createObjectURL(stream);mediaStream = stream;track = stream.getTracks()[0];$scope.photoBtnDiable = false; $scope.$apply();},// errorCallbackfunction (err) {$scope.errorPhoto();console.log("The following error occured:" + err);});} else {$scope.errorPhoto();}

Code parsing:

Navigator is a browser object that contains information about the browser. this object is used to open the camera. $ Scope is the AndularJs syntax. Step 1 declare navigator. getMedia calls different camera-opening functions of the browser. Currently, only getUserMedia, webkitGetUserMedia, javasgetusermedia, and msGetUserMedia correspond to general browsers, Google browsers, Firefox browsers, and IE browsers respectively, the browser automatically determines which function to call. The second step is to call the open browser, which contains three parameters: the multimedia type to be used, the stream data processing function to obtain the success response, and the error message processing function to return if the operation fails. In this example, you can set not only the video but also the microphone. the setting method is as follows:

{video: true,audio: true}

When the call succeeds, the camera is turned on and the video stream data is returned. we can set the stream data to the video tag to display the image in real time on the interface. MediaStream is used to record the obtained stream data. track is used to track the camera status in Chrome. both variables can be used to close the camera.

3. take a photo

$scope.snap = function () {var canvas = document.createElement('canvas');canvas.width = "400";canvas.height = "304";var ctx = canvas.getContext('2d');ctx.drawImage(video, 0, 0, 400, 304);$scope.closeCamera();$uibModalInstance.close(canvas.toDataURL("image/png"));};

When taking a photo, you need to use the canvas label to create a canvas label, set the size of the image we want to take, and save the current video image to the canvas label through the drawImage function, finally, convert the image data to base64 and return the data and turn off the camera. this completes our photo taking function. Here, the $ uibModalInstance object is an object that opens the pop-up layer in our project to control the display of the pop-up layer.

4. how to close the camera

$scope.closeCamera = function () {if (mediaStream != null) {if (mediaStream.stop) {mediaStream.stop();}$scope.videosrc = "";}if (track != null) {if (track.stop) {track.stop();}}}

As mentioned above, the way to close the camera is through mediaStream and track variables, except that the track can only close the camera in the Chrome browser, which is also the way to close the camera in Chrome Version 45 or later.

5. integrate into AndularJs

As a matter of fact, all we mentioned above are implemented in AndularJs. of course, here we only implement taking a photo and returning the photo data. if we want to use it elsewhere, we need to separate this part, here we use the service mechanism in AngularJs to separate this part into a service and inject it into the project. then we can call it elsewhere.

Service registration:

app().registerService("h5TakePhotoService", function ($q, $uibModal) {this.photo = function () {var deferred = $q.defer();require([config.server + "/com/controllers/photo.js?7.1.1"], function () {$uibModal.open({templateUrl: config.server + "/com/views/modal_take_photo.html",controller: "photoModalController",windowClass: "modal-photo"}).result.then(function (e) {deferred.resolve(e);});});return deferred.promise;}
});

Call method:

$scope.takePhoto = function () {h5TakePhotoService.photo().then(function (res) {if (res != null && res != "") {$scope.myImage = res;}});}

H5TakePhotoService is the image service object injected into the controller. it processes the returned image data and sets the data to be displayed on the interface.

6. Compatibility issues

It mainly exists in the Chrome browser. during local testing, the Chrome browser can be used normally, but it cannot be used normally after being deployed to the server. the error message is [object NavigatorUserMediaError]. this is because Chrome only supports secure source access when using cameras, so it can only be used through https access.

Finally, you can only use http: // url for access during the test. you cannot use file: // url for access. that is, you must deploy the code to access the service, it can be completed in Visual Studio, java web, and php.

The above section describes how to use HTML5 mobile phone cameras to take photos in AngularJS. I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.