Android 调用相机、相册功能

  清单文件中增加对应权限,动态申请权限(此部分请参考Android 动态申请权限,在此不作为重点描述)


private static final int REQUEST_CODE_ALBUM = 100;//打开相册
private static final int REQUEST_CODE_CAMERA = 101;//打开相机

//调用相册
private void openAlbum(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_ALBUM);
}
//调用相机
private void openCamera1(){
Intent intent;
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK){
if (data != null) {
// 照片的原始资源地址
Uri uri = data.getData();
String path = uri.getPath();
ContentResolver cr = context.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
        }
}else if(requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK){
if(data != null && data.getData() != null){
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bitmap = extras.getParcelable("data");
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
          //可将图片保存下来,用于上传或其他操作(如果不需要可以省略此步)
          String path = savePicToSdcard(image,Environment.getExternalStorageDirectory().getPath(),System.currentTimeMillis() + ".jpg");
            }
}
}
}

public static String savePicToSdcard(Bitmap bitmap, String path, String fileName) {
String filePath = "";
if (bitmap != null) {
filePath = path + File.separator + fileName;
File destFile = new File(filePath);
OutputStream os = null;
try {
os = new FileOutputStream(destFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (IOException e) {
filePath = "";
}
}
return filePath;
}


上述相机方法相片清晰度低,获取的是返回对象中的略缩图;如对照片清晰度有要求,可以在上面方法的基础上进行修改,方法如下:

需要在清单文件中application中增加如下代码:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>

创建file_paths.xml文件

项目目录res下创建xml文件夹,xml文件夹下创建file_paths.xml文件,文件内容:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_storage_root"
path="." />
</paths>

配置完成后,修改增加如下代码:
private static final int REQUEST_RESULT_CODE = 102;//裁剪后保存
//调用相机(指定相机拍摄照片保存地址,相片清晰度高)
private void openCamera2(){
String photoPath = Environment.getExternalStorageDirectory().getPath()+"/"+File.separator+"123.jpg";
File pictureFile = new File(photoPath);
Uri picUri;
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String packageName = context.getApplicationContext().getPackageName();
picUri = FileProvider.getUriForFile(context, new StringBuilder(packageName).append(".fileprovider").toString(), pictureFile);
} else {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
picUri = Uri.fromFile(pictureFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK){
if (data != null) {
// 照片的原始资源地址
Uri uri = data.getData();
String path = uri.getPath();
ContentResolver cr = context.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
}
}else if(requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK){
File tempFile = new File(photoPath);
cropImg(getImageContentUri(tempFile));//对照片进行裁剪保存
}else if(requestCode ==REQUEST_RESULT_CODE && resultCode == RESULT_OK){
try {
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(mUriPath));
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

public Uri getImageContentUri(File imageFile) {
    String filePath = imageFile.getAbsolutePath();
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);

if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}

public void cropImg(Uri uri){
    Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");

//实现对图片的裁剪,必须要设置图片的属性和大小
intent.putExtra("crop", "true"); //滑动选中图片区域
intent.putExtra("aspectX", 1); //裁剪框比例1:1
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 700); //输出图片大小
intent.putExtra("outputY", 700);
intent.putExtra("return-data", true); //有返回值

String mLinshi = System.currentTimeMillis() + ".jpg";
photoFile = new File(Environment.getExternalStorageDirectory().getPath(), mLinshi);

mUriPath = Uri.parse("file://" + photoFile.getAbsolutePath());
//将裁剪好的图输出到所建文件中
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPath);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//注意:此处应设置return-data为false,如果设置为true,是直接返回bitmap格式的数据,耗费内存。设置为false,然后,设置裁剪完之后保存的路径,即:intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPath);
intent.putExtra("return-data", false);
startActivityForResult(intent, REQUEST_RESULT_CODE);
}


原文地址:https://www.cnblogs.com/LEON-D/p/11389346.html