美文网首页
拍照功能

拍照功能

作者: 厦门_小灰灰 | 来源:发表于2017-10-30 16:59 被阅读6次

今天来实现一个简单的拍照功能,页面很简单就是一个按钮,一个图片展示区;

1.在layout的xml文件中创建Button和ImageView

<Button
    android:id="@+id/take_photo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Take Photo">

</Button>

<ImageView
    android:id="@+id/show_photo_imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

代码就不解释了,很简单的布局。

2.第一步,首先将之前的需要的控件创建好以及Uri:

    private Button takePhotoBtn;
    private ImageView photoImageView;
    private Uri imageUri = null;
    public static final int TAKE_PHOTO = 1;

 photoImageView = (ImageView) findViewById(R.id.show_photo_imageview);
        takePhotoBtn = (Button) findViewById(R.id.take_photo);

3.第二步,图片输出路径与文件

 //创建File
 File outputImageFile = new File(getExternalCacheDir(), "output_image.jpg");
   if ( outputImageFile.exists() ) {
      outputImageFile.delete();
   }

 try {
  outputImageFile.createNewFile();
   } catch (IOException e) {
       e.printStackTrace();
}

 //创建imageUri
 if (Build.VERSION.SDK_INT >= 24) {
   //使用新的方式
   imageUri = FileProvider.getUriForFile(MainActivity.this, "com.lee.application.camera", outputImageFile);
                } else {
   · imageUri = Uri.fromFile(outputImageFile);
  }

4.第三步,启动相机

 //启动相机
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);

注意是用startActivityForResult,因为我们需要回调图片数据流;

5.第四步,在onActivityResult接收图片数据流

//获取输出流
 try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    photoImageView.setImageBitmap(bitmap);
                } catch ( FileNotFoundException e ) {
                    e.printStackTrace();
 }

6.在AndroidManifest.xml,配置provider以及相应权限

访问sd卡的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
provider 配置,其中authorities是在刚才代码中初始化imageUri的时候的值是一样的,name都是android.support.v4.content.FileProvider
<provider
            android:authorities="com.lee.application.camera"
            android:name="android.support.v4.content.FileProvider"
            android:grantUriPermissions="true"
            android:exported="false">

            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                />

</provider>

上面meta-data里面是配置路径的,需要在res目录下,创建xml目录,然后创建file_paths文件;

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path name="my_images" path=""/>

</paths>

OK,收工!

相关文章

网友评论

      本文标题:拍照功能

      本文链接:https://www.haomeiwen.com/subject/fvxmpxtx.html