Android调用摄像头拍照开发教程

作者:小朵八 时间:2023-05-24 11:33:33 

现在很多应用中都会要求用户上传一张图片来作为头像,首先我在这接收使用相机拍照和在相册中选择图片。接下来先上效果图:

Android调用摄像头拍照开发教程

Android调用摄像头拍照开发教程 

Android调用摄像头拍照开发教程

Android调用摄像头拍照开发教程

接下来看代码:

1、布局文件:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="com.gyq.cameraalbumtest.MainActivity">

<Button
   android:id="@+id/btn_take_photo"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="take photo"/>

<Button
   android:id="@+id/choose_from_album"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="choose from album"/>

<ImageView
   android:id="@+id/iv_picture"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"/>
</LinearLayout>

2、MainActivity.java逻辑代码:


package com.gyq.cameraalbumtest;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {
 public static final int TAKE_PHOTO = 1;
 public static final int CHOOSE_PHOTO = 2;
 private Button mTakePhoto, mChoosePhoto;
 private ImageView picture;
 private Uri imageUri;

@Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

mTakePhoto = (Button) findViewById(R.id.btn_take_photo);
   mChoosePhoto = (Button) findViewById(R.id.choose_from_album);
   picture = (ImageView) findViewById(R.id.iv_picture);

mTakePhoto.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
       //创建file对象,用于存储拍照后的图片;
       File outputImage = new File(getExternalCacheDir(), "output_image.jpg");

try {
         if (outputImage.exists()) {
           outputImage.delete();
         }
         outputImage.createNewFile();

} catch (Exception e) {
         e.printStackTrace();
       }

if (Build.VERSION.SDK_INT >= 24) {
         imageUri = FileProvider.getUriForFile(MainActivity.this,
             "com.gyq.cameraalbumtest.fileprovider", outputImage);
       } else {
         imageUri = Uri.fromFile(outputImage);
       }

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

mChoosePhoto.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
       if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
       } else {
         openAlbum();
       }
     }
   });
 }

//打开相册
 private void openAlbum() {
   Intent intent = new Intent("android.intent.action.GET_CONTENT");
   intent.setType("image/*");
   startActivityForResult(intent, CHOOSE_PHOTO);
 }

@Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
   switch (requestCode) {
     case 1:
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
         openAlbum();
       } else {
         Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show();
       }
       break;

}
 }

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   switch (requestCode) {
     case TAKE_PHOTO:
       if (resultCode == RESULT_OK) {
         try {
           Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
           picture.setImageBitmap(bm);
         } catch (Exception e) {
           e.printStackTrace();
         }

}
       break;
     case CHOOSE_PHOTO:
       if (resultCode == RESULT_OK) {
         if (Build.VERSION.SDK_INT >= 19) { //4.4及以上的系统使用这个方法处理图片;
           handleImageOnKitKat(data);
         } else {
           handleImageBeforeKitKat(data); //4.4及以下的系统使用这个方法处理图片
         }
       }
     default:
       break;
   }
 }

private void handleImageBeforeKitKat(Intent data) {
   Uri uri = data.getData();
   String imagePath = getImagePath(uri, null);
   displayImage(imagePath);
 }

private String getImagePath(Uri uri, String selection) {
   String path = null;
   //通过Uri和selection来获取真实的图片路径
   Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
   if (cursor != null) {
     if (cursor.moveToFirst()) {
       path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
     }
     cursor.close();
   }
   return path;
 }

private void displayImage(String imagePath) {
   if (imagePath != null) {
     Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
     picture.setImageBitmap(bitmap);
   } else {
     Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
   }
 }

/**
  * 4.4及以上的系统使用这个方法处理图片
  *
  * @param data
  */
 @TargetApi(19)
 private void handleImageOnKitKat(Intent data) {
   String imagePath = null;
   Uri uri = data.getData();
   if (DocumentsContract.isDocumentUri(this, uri)) {
     //如果document类型的Uri,则通过document来处理
     String docID = DocumentsContract.getDocumentId(uri);
     if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
       String id = docID.split(":")[1];   //解析出数字格式的id
       String selection = MediaStore.Images.Media._ID + "=" + id;

imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
     } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
       Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID));

imagePath = getImagePath(contentUri, null);

}

} else if ("content".equalsIgnoreCase(uri.getScheme())) {
     //如果是content类型的uri,则使用普通方式使用
     imagePath = getImagePath(uri, null);
   } else if ("file".equalsIgnoreCase(uri.getScheme())) {
     //如果是file类型的uri,直接获取路径即可
     imagePath = uri.getPath();

}

displayImage(imagePath);
 }
}

3、清单文件:


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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
   <activity android:name=".MainActivity">
     <intent-filter>
       <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
     </intent-filter>
   </activity>

<provider
     android:authorities="com.gyq.cameraalbumtest.fileprovider"
     android:name="android.support.v4.content.FileProvider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
           android:resource="@xml/file_paths"/>
   </provider>

</application>

</manifest>

4、xml文件夹中的文件

Android调用摄像头拍照开发教程


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

OK,完成收工。请继续关注我的博客。谢谢!

来源:https://blog.csdn.net/duoduo_11011/article/details/53885613

标签:Android,摄像头,拍照
0
投稿

猜你喜欢

  • Java使用DateTimeFormatter格式化输入的日期时间

    2023-03-09 04:52:38
  • C#开发微信公众号接口开发

    2023-10-14 11:49:01
  • DevExpress实现禁用TreeListNode CheckBox的方法

    2022-07-20 22:17:43
  • C# 获取枚举值的简单实例

    2023-09-01 00:13:23
  • Java 常见排序算法代码分享

    2023-09-30 08:23:09
  • Android中ListActivity用法实例分析

    2022-08-14 21:52:34
  • 阿里nacos+springboot+dubbo2.7.3统一处理异常的两种方式

    2022-12-05 03:50:25
  • Spring整合Quartz开发代码实例

    2022-03-12 16:37:26
  • Android Glide的简单使用

    2022-12-22 01:37:14
  • 详细解读Java Spring AOP

    2022-10-09 11:06:06
  • C#实现创建标签PDF文件的示例代码

    2023-09-15 07:04:58
  • 用java实现杨辉三角的示例代码

    2023-08-12 09:02:21
  • Swagger及knife4j的基本使用详解

    2023-02-13 09:34:00
  • c#实现汉诺塔问题示例

    2023-08-09 13:20:02
  • Android利用RenderScript实现毛玻璃模糊效果示例

    2021-05-26 02:32:07
  • android开发仿ios的UIScrollView实例代码

    2023-08-07 01:55:20
  • Java如何实现自定义异常类

    2023-06-21 23:44:01
  • C#实现输入10个数存入到数组中并求max和min及平均数的方法示例

    2023-11-30 05:58:54
  • 使用C#获取远程图片 Form用户名与密码Authorization认证的实现

    2022-01-22 21:44:06
  • C#写差异文件备份工具的示例

    2022-02-21 02:14:00
  • asp之家 软件编程 m.aspxhome.com