调用摄像头拍照
在应用程序中调用摄像头是非常常见的功能,接下来就开启学习之路吧!
1.修改布局文件
修改activity_main.xml中的内容,新建一个Button和ImageView,分别用来拍照和显示图片,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="take photo"/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
2.编写调用摄像头的具体逻辑
(1)获取Button和ImageView的实例,并注册button的点击事件,click后调用摄像头,具体处理逻辑如下:
- 创建file对象,存储拍下的图片
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
- 判断设备的系统版本,若低于Android7.0则将File对象转换成Uri对象,否则调用FileProvider的getUriForFile方法将File对象转换成封装过的Uri对象
if(Build.VERSION.SDK_INT>=24){
imageUri=FileProvider.getUriForFile(MainActivity.this,
"com.example.cameraalbumtest.fileprovider",outputImage);
}else{
imageUri=Uri.fromFile(outputImage);
}
- 构建Intent对象,指定action为
android.media.action.IMAGE_CAPTURE
,并调用putExtra方法指定图片输出地址
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);
Android7.0系统开始,直接使用本地真实路径的Uri会抛出异常,FileProvider是一种特殊的内容提供器,可将封装过的Uri对外部进行共享,提高安全性
(2)注册内容提供器
在AndroidManifest.xml中注册FileProvider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.cameraalbumtest.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
(3)在onActivityResult()方法中显示图像
启动活动后,会返回结果到该方法中,调用BitmapFactory的decodeStream()方法解析照片,并显示在ImageView中,具体代码如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode){
case TAKE_PHOTO:
if(resultCode==RESULT_OK){
try{
Bitmap bitmap=BitmapFactory.decodeStream
(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
break;
default:
break;
}
}
(4)创建file_paths.xml文件,提供引用
external-path用来指定Uri共享,其中path属性表示具体路径,设置为空说明将整个SD卡进行共享
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="" />
</paths>
(5)声明权限
在配置文件中声明访问SD卡的权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cameraalbumtest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
</manifest>
Android4.4系统之前,访问SD卡的应用关联目录需要声明权限,之后不再需要
3.一个小小的问题
在file_paths.xml文件中,若设置path属性值为空,会标红提示“Value must not be empty”,但是并不影响运行。可设置path=“/”表示路径就不报错了…
调用相册
除了调用摄像头拍照外,直接从相册中选择图片往往更加常用,下面实现从相册中选取图片并显示。
1.修改布局文件
添加一个button用于从相册中选择照片
<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="choose photo"/>
2.加入调用相册的逻辑
(1)获取button实例,并注册点击事件,在事件中进行运行时权限申请,获取WRITE_EXTERNAL_STORAGE权限,可向sd卡中读和写
Button chooseFromAlbum=findViewById(R.id.choose_from_album);
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
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();
}
}
});
(2)创建openAlbum()方法,启动相册程序
在该方法中构建Intent,并指定action为android.intent.action.GET_CONTENT,具体代码如下:
private void openAlbum(){
Intent intent=new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHOTO);
}
(3)在onActivityResult方法中处理图片
启动活动后,传入CHOOSE_PHOTO值,在该方法中进行系统版本判断,分别调用不同的方法处理图片
case CHOOSE_PHOTO:
if(resultCode==RESULT_OK){
//判断手机系统版本号
if(Build.VERSION.SDK_INT>=19){
//4.4及以上系统
handleImageOnKitKat(data);
}else{
//4.4以下系统
handleImageBeforeKitKat(data);
}
}
break;
Android系统从4.4版本开始,选取图片不再返回真实的Uri,而是对其进行封装再返回,因此4.4版本以上的系统需要对这个Uri进行解析
(4)创建handleImageOnKitKat()方法对图片进行解析
首先判断Uri类型,对于不同类型的uri采取不同的处理方式,然后通过getImagePath方法获取图片路径,之后再调用displayImage方法显示图片
- handleImageOnKitKat()方法
@TargetApi(19)
private void handleImageOnKitKat(Intent data){
String imagePath=null;
Uri uri=data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){
//document类型的Uri处理方式
String docId=DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id=docId.split(":")[1];
String seletion=MediaStore.Images.Media._ID+"="+id;
imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,seletion);
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_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);
}
Android API在高版本中的某些功能无法在低版本中使用,且会报错,所以要使用@TargetApi(19)防止报错
- getImagePath()方法
private String getImagePath(Uri uri,String selection){
String path=null;
//获取真实的图片路径
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;
}
- displayImage()方法
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();
}
}
(5)创建handleImageBeforeKitKat()方法对4.4以下版本系统的图片进行处理
由于Uri未封装过,故可以直接调用getImagePath方法获取图片路径,之后再调用displayImage方法显示图片即可
private void handleImageBeforeKitKat(Intent data){
Uri uri=data.getData();
String imagePath=getImagePath(uri,null);
displayImage(imagePath);
}
至此,成功实现了调用相机拍照以及从相册中选取图片。