Xamarin.Android 调用手机拍照功能

简介:   最近开发Android遇到了调用本地拍照功能,于是在网上搜了一些方法,加上自己理解的注释,在这儿记录下来省的下次用时候找不到,同事也给正在寻找调用本地拍照功能的小伙伴一些帮助~  实现思路:首先加载-->判断是否具备拍照功能-->创建图片目录(文件夹)-->点击拍照事件-->返回图片并绑定在控件上显示。

  最近开发Android遇到了调用本地拍照功能,于是在网上搜了一些方法,加上自己理解的注释,在这儿记录下来省的下次用时候找不到,同事也给正在寻找调用本地拍照功能的小伙伴一些帮助~

  实现思路:首先加载-->判断是否具备拍照功能-->创建图片目录(文件夹)-->点击拍照事件-->返回图片并绑定在控件上显示。

引用命名空间:

    using System;
    using System.Collections.Generic;
    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.Graphics;
    using Android.OS;
    using Android.Provider;
    using Android.Widget;
    using Java.IO;
    using Environment = Android.OS.Environment;
    using Uri = Android.Net.Uri; 

加载:

     protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
             
            if (IsThereAnAppToTakePictures())   //判断本设备是否存在拍照功能
            {
                CreateDirectoryForPictures();

                Button button = FindViewById<Button>(Resource.Id.myButton);
                _imageView = FindViewById<ImageView>(Resource.Id.imageView1);
                button.Click += TakeAPicture;
            } 
        }

判断是否具备拍照功能:

        /// <summary>
        ///  判断是否具备拍照功能
        /// </summary>
        /// <returns></returns>
        private bool IsThereAnAppToTakePictures()
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);
            IList<ResolveInfo> availableActivities =
                PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
            return availableActivities != null && availableActivities.Count > 0;
        }     

创建图片目录(文件夹):

        /// <summary>
        /// 创建目录图片
        /// </summary> 
        private void CreateDirectoryForPictures()
        {
            App._dir = new File(
                Environment.GetExternalStoragePublicDirectory(
                    Environment.DirectoryPictures), "CameraAppDemo");        //CameraAppDemo
            if (!App._dir.Exists())
            {
                App._dir.Mkdirs();
            }
        }

点击拍照事件:

        /// <summary>
        /// 拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void TakeAPicture(object sender, EventArgs eventArgs)
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);

            App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));       //保存路径

            intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));

            StartActivityForResult(intent, 0);
        }

返回图片并绑定在控件上显示:

        /// <summary>
        /// 拍照结束执行
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data); 

            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            Uri contentUri = Uri.FromFile(App._file);
            mediaScanIntent.SetData(contentUri);
            SendBroadcast(mediaScanIntent);

            // Display in ImageView. We will resize the bitmap to fit the display
            // Loading the full sized image will consume to much memory 
            // and cause the application to crash.

            int height = Resources.DisplayMetrics.HeightPixels;
            int width = _imageView.Height;

            //获取拍照的位图
            App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
            if (App.bitmap != null)
            {
                //将图片绑定到控件上
                _imageView.SetImageBitmap(App.bitmap); 

                //清空bitmap 否则会出现oom问题
                App.bitmap = null;
            }

            // Dispose of the Java side bitmap.
            GC.Collect();
        }

LoadAndResizeBitmap方法:

        public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height)
        {
            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true };
            BitmapFactory.DecodeFile(fileName, options);

            // Next we calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.
            int outHeight = options.OutHeight;
            int outWidth = options.OutWidth;
            int inSampleSize = 1;

            if (outHeight > height || outWidth > width)
            {
                inSampleSize = outWidth > outHeight
                                   ? outHeight / height
                                   : outWidth / width;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);

            return resizedBitmap;
        }

App类:

    public static class App
    {
        public static File _file;
        public static File _dir;
        public static Bitmap bitmap;
    }

最后再附上下载地址:

  链接: https://pan.baidu.com/s/1h0Zg1jkCyKrZKN6N5eIB8Q

  密码: wgdm

目录
相关文章
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
102 0
|
1月前
|
Java
【Java每日一题】— —第二十一题:编程把现实生活的手机事物映射成一个标准类Phone,并定义一个测试类PhoneDemo测试Phone类的功能
【Java每日一题】— —第二十一题:编程把现实生活的手机事物映射成一个标准类Phone,并定义一个测试类PhoneDemo测试Phone类的功能
36 0
|
2月前
|
监控 安全 Android开发
【新手必读】Airtest测试Android手机常见的设置问题
【新手必读】Airtest测试Android手机常见的设置问题
|
2月前
|
机器学习/深度学习 人工智能 Android开发
安卓智能手机操作系统演化史
【2月更文挑战第5天】 本文通过对安卓智能手机操作系统的演化历程进行探讨,分析了安卓系统从诞生至今的发展脉络和关键技术革新,从最初的版本到如今的最新版本,探讨了其在移动互联网时代的重要作用,以及未来可能的发展方向。
|
1月前
|
安全 Java 数据库连接
【Java每日一题】——第四十四题:综合案例:编程模拟智能手机和普通手机功能。
【Java每日一题】——第四十四题:综合案例:编程模拟智能手机和普通手机功能。
49 0
|
3月前
|
JavaScript Android开发
手机也能搭建个人博客?安卓Termux+Hexo搭建属于你自己的博客网站
手机也能搭建个人博客?安卓Termux+Hexo搭建属于你自己的博客网站
36 0
|
3天前
|
Java Android开发
Android Mediatek 应用层重置USB设备功能
Android Mediatek 应用层重置USB设备功能
11 0
|
1月前
|
数据挖掘 数据处理 API
使用TransBigData组件实现个人手机定位功能
使用TransBigData组件实现个人手机定位功能
21 0
|
1月前
|
Web App开发 前端开发 网络安全
前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
【2月更文挑战第21天】前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
50 1
前端分析工具之 Charles 录制 Android/IOS 手机的 https 应用
|
1月前
|
网络协议 关系型数据库 MySQL
安卓手机termux上安装MariaDB数据库并实现公网环境下的远程连接
安卓手机termux上安装MariaDB数据库并实现公网环境下的远程连接