说明:
1.android 调用系统相机拍照用两种方式:
a.获取原图;b.获取压缩图
二者主要区别在于是否设置图片保存路径,设置则保存的是原图,否则系统默认会对图片进行压缩。
2.本文是基于郭霖大神相关案例增加剪切功能。郭霖博客地址:
http://blog.csdn.net/guolin_blog/
3.本文是基于第一种方案的开发的简单案例,诸如其它各种适配问题会在后续逐步完善…
activity源码:
package com.dyb.testcamerademo;
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.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.dyb.testcamerademo.R.id.take_btn;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;//拍照
public static final int CHOOSE_PHOTO = 2;//选择相册
public static final int PICTURE_CUT = 3;//剪切图片
private Uri imageUri;//相机拍照图片保存地址
private Uri outputUri;//裁剪万照片保存地址
private String imagePath;//打开相册选择照片的路径
private boolean isClickCamera;//是否是拍照裁剪
@BindView(take_btn)
Button takeBtn;//打开相机按钮
@BindView(R.id.album_btn)
Button albumBtn;//选择相册按钮
@BindView(R.id.iv)
ImageView iv;//裁剪完照片展示控件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick({R.id.take_btn, R.id.album_btn})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.take_btn:
openCamera();//打开相机
break;
case R.id.album_btn:
//动态权限
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 {
selectFromAlbum();//打开相册
}
break;
}
}
//图片结果处理方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO://拍照
if (resultCode == RESULT_OK) {
cropPhoto(imageUri);//裁剪图片
}
break;
case CHOOSE_PHOTO://打开相册
// 判断手机系统版本号
if (Build.VERSION.SDK_INT >= 19) {
// 4.4及以上系统使用这个方法处理图片
handleImageOnKitKat(data);
} else {
// 4.4以下系统使用这个方法处理图片
handleImageBeforeKitKat(data);
}
break;
case PICTURE_CUT://裁剪完成
isClickCamera = true;
Bitmap bitmap = null;
try {
if (isClickCamera) {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(outputUri));
} else {
bitmap = BitmapFactory.decodeFile(imagePath);
}
iv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
}
private void openCamera() {
// 创建File对象,用于存储拍照后的图片
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT < 24) {
imageUri = Uri.fromFile(outputImage);
} else {
//Android 7.0系统开始 使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri
//参数二:fileprovider绝对路径 com.dyb.testcamerademo:项目包名
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.dyb.testcamerademo.fileprovider", outputImage);
}
// 启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
private void selectFromAlbum() {
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, String[] permissions, 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;
default:
}
}
/**
* 裁剪图片
*/
private void cropPhoto(Uri uri) {
// 创建File对象,用于存储裁剪后的图片,避免更改原图
File file = new File(getExternalCacheDir(), "crop_image.jpg");
try {
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
outputUri = Uri.fromFile(file);
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(uri, "image/*");
//裁剪图片的宽高比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("crop", "true");//可裁剪
// 裁剪后输出图片的尺寸大小
//intent.putExtra("outputX", 400);
//intent.putExtra("outputY", 200);
intent.putExtra("scale", true);//支持缩放
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出图片格式
intent.putExtra("noFaceDetection", true);//取消人脸识别
startActivityForResult(intent, PICTURE_CUT);
}
// 4.4及以上系统使用这个方法处理图片 相册图片返回的不再是真实的Uri,而是分装过的Uri
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
imagePath = null;
Uri uri = data.getData();
Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
if (DocumentsContract.isDocumentUri(this, uri)) {
// 如果是document类型的Uri,则通过document id处理
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/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();
}
cropPhoto(uri);
}
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 handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
imagePath = getImagePath(uri, null);
cropPhoto(uri);
}
}
上端代码中的“当intent.putExtra(“aspectX”, 1);intent.putExtra(“aspectY”, 1);”时有些机型裁剪框会是圆形的(非方形),解决方案:把裁剪比例设置成其它非1:1比例。
配置文件(AndroidManiFest.xml)源码:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dyb.testcamerademo">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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:name="android.support.v4.content.FileProvider"
android:authorities="com.dyb.testcamerademo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
provider>
application>
manifest>
注:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.dyb.testcamerademo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
provider>
上段代码块是适配7.0的,因为Android 7.0系统开始 使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri。其中android:name、exported、 android:grantUriPermissions、取值固定,android:authorities取值为:“自己项目包名”.fileprovider。
data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
android:resource=“@xml/file_paths”中@xml/的文件名字可以随便起,但一般规范化都用此名。
xml包下file_paths.xml源码
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<external-path
name="camera_photos"
path=""/>
paths>
paths>