Using cordova-camera plugin in your Ionic 2 Apps


http://tphangout.com/using-cordova-camera-plugin-in-your-ionic-2-apps/


Hi friends,

Hope you are all well. Now this post deals with using the cordova-camera plugin in your Ionic 2 apps to take photos using your smartphone camera. As with my previous posts I will try to keep this as much simple as possible.

The complete code of this tutorial can be found here.

A screencast of this tutorial is available below

Create an Ionic 2 application using the below command.

Let’s get started. Once you have created the Ionic 2 application; install the camera plugin using the below command.

1
ionic plugin add cordova-plugin-camera --save

Now once the plugin is installed, open up the app in an editor of your choice, navigate to app -> pages -> home and in the home.html file add the below code in between the <ion-content> tags.

Now this will add a button which upon clicking would trigger a takepic function and a card that holds an image.

If you with to use ionic-native to access camera, please skip the below steps and read the update at the end of this post.

Lets wire this up to the takepic function. Open up home.js and add the below code.

Let’s break this down.

  1. NgZone is used to execute services outside of angular and then get back in using run(). Read more about it here.
  2. Options specify the options considered while taking/saving the picture.
  3. navigator.camera is global when you install the plugin and can be used anywhere in the app.
  4. The image is captured and stored in the form of base64 encoding and then placed in this.image which is then used in the src attribute in the img tag.

Now this code is enough to use camera in our app. To execute this in your android phone please add the android platform using the below command.

and then run the app (on your mobile or emulator) using the below command.

This is a very simple way to use the smartphone camera in our app for taking pictures using the cordova camera plugin in our Ionic 2 apps.

Hope this helped you guys. Peace.. :)

Update:

The same could be done using ionic-native a new successor to ngCordova from driftyco. Once you install the plugin install ionic-native using the below command

Now modify the home.js as shown below:

Things to notice:

  1. We use numbers now to denote sourceType, destinationType and encodingType.
  2. Camera.getPicture returns a promise which is then resolved.

I have made a repo on this updated code and this is available here.

Thanks.


posted @   张同光  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示