参考:
一. 步骤简介
要说拍照,如果只是调用系统相机的话,步骤比较简单,就是利用隐式Intent打开相机,然后会相机会传回来排好的图片,传回来的图片分为比较小的缩略图和比较大的原图,缩略图的话可以直接进行展示,而原图的话就要输出到文件中,因此简单的拍照分以下步骤:
- 使用隐式Intent打开相机
- 在onActivityResult回调中对图片进行处理
二. 详解
-
拍照并获取缩略图
拍照并获取缩略图不需要任何权限,只需要调用相机然后获取结果即可- 调用相机
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//用来打开相机的Intent
if(takePhotoIntent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退,要是不加这句则当系统没有相机应用的时候该应用会闪退
startActivityForResult(takePhotoIntent,REQ_CODE);//启动相机
}
- 获取结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQ_CODE&&resultCode==RESULT_OK){
/*缩略图信息是储存在返回的intent中的Bundle中的,
* 对应Bundle中的键为data,因此从Intent中取出
* Bundle再根据data取出来Bitmap即可*/
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
mPicture.setImageBitmap(bitmap);
}
}
-
拍照并获取完整图片
因为完整图片较大,所以需要将其存储到文件中,因此需要创建用来存储图片的文件,其次又因为存储图片需要访问外存,因此可能需要申请读写权限。- 调用相机
private void takePhoto(){
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
if(takePhotoIntent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退,要是不加这句则当系统没有相机应用的时候该应用会闪退
File imageFile = createImageFile();//创建用来保存照片的文件
if(imageFile!=null){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
/*7.0以上要通过FileProvider将File转化为Uri*/
mImageUri = FileProvider.getUriForFile(this,FILE_PROVIDER_AUTHORITY,imageFile);
}else {
/*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
mImageUri = Uri.fromFile(imageFile);
}
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);//将用于输出的文件Uri传递给相机
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO_CODE);//打开相机
}
}
}
/**
* 创建用来存储图片的文件,以时间来命名就不会产生命名冲突
* @return 创建的图片文件
*/
private File createImageFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_"+timeStamp+"_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
return imageFile;
}
- 获取结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode== REQUEST_TAKE_PHOTO_CODE &&resultCode==RESULT_OK){
try {
/*如果拍照成功,将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
mPicture.setImageBitmap(bitmap);//显示到ImageView上
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
- 将拍的照片添加到媒体库以便相册可以扫描到(当照片存储在应用目录下的时候会扫描不到)
- 其实就是发送一条扫描文件的广播
/**
* 将拍的照片添加到相册
* @param uri 拍的照片的Uri
*/
private void galleryAddPic(Uri uri){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
sendBroadcast(mediaScanIntent);
}
三. 有关7.0以上FileProvider的使用
- 注册FileProvider
<provider
android:authorities="cn.fonxnickel.officialcamerademo.fileprovider"//自己定义的authority
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>
- 新建路径文件(xml/file_paths)
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="my_images"
path="."/>
</paths>
四. 对拍好的照片进行剪裁
五. 从相册选取图片
- 相册选取图片和拍照步骤差不多,都是打开应用程序,然后返回Uri,然后进行处理
- 步骤如下:
- 打开相册
/**
* 打开相册
*/
private void openAlbum() {
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setType("image/*");
startActivityForResult(openAlbumIntent, CHOOSE_PHOTO);//打开相册
}
- 处理返回的Uri
/*相机或者相册返回来的数据*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
/*如果拍照成功,将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
Log.i(TAG, "onActivityResult: imageUri " + mImageUri);
galleryAddPic(mImageUriFromFile);
mPicture.setImageBitmap(bitmap);//显示到ImageView上
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
Log.i(TAG, "onActivityResult: ImageUriFromAlbum: "+data.getData());
if (resultCode == RESULT_OK) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
handleImageOnKitKat(data);//4.4之后图片解析
}else {
handleImageBeforeKitKat(data);//4.4之前图片解析
}
}
break;
default:
break;
}
}
/**
* 4.4版本以下对返回的图片Uri的处理:
* 就是从返回的Intent中取出图片Uri,直接显示就好
* @param data 调用系统相册之后返回的Uri
*/
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri,null);
displayImage(imagePath);
}
/**
* 4.4版本以上对返回的图片Uri的处理:
* 返回的Uri是经过封装的,要进行处理才能得到真实路径
* @param data 调用系统相册之后返回的Uri
*/
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
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();
}
displayImage(imagePath);
}
/**
* 将imagePath指定的图片显示到ImageView上
*/
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
mPicture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
/**
* 将Uri转化为路径
* @param uri 要转化的Uri
* @param selection 4.4之后需要解析Uri,因此需要该参数
* @return 转化之后的路径
*/
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;
}
六. 源码
- 布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.foxnickel.officialcamerademo.MainActivity">
<Button
android:id="@+id/bt_take_photo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/take_photo"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp"/>
<ImageView
android:id="@+id/iv_picture"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@mipmap/ic_launcher"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/bt_choose_from_album"/>
<Button
android:id="@+id/bt_choose_from_album"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/choose_from_album"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/bt_take_photo"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"/>
</android.support.constraint.ConstraintLayout>
- 主要逻辑
public class MainActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
private Button mTakePhoto, mChooseFromAlbum;
private ImageView mPicture;
private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
private static final int REQUEST_PERMISSION_CODE = 267;
private static final int TAKE_PHOTO = 189;
private static final int CHOOSE_PHOTO = 385;
private static final String FILE_PROVIDER_AUTHORITY = "cn.fonxnickel.officialcamerademo.fileprovider";
private Uri mImageUri, mImageUriFromFile;
private File imageFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*申请读取存储的权限*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
}
}
mPicture = (ImageView) findViewById(R.id.iv_picture);
mTakePhoto = (Button) findViewById(R.id.bt_take_photo);
mChooseFromAlbum = (Button) findViewById(R.id.bt_choose_from_album);
mTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePhoto();
}
});
mChooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openAlbum();
}
});
}
/**
* 打开相册
*/
private void openAlbum() {
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setType("image/*");
startActivityForResult(openAlbumIntent, CHOOSE_PHOTO);//打开相册
}
/**
* 拍照
*/
private void takePhoto() {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退,要是不加这句则当系统没有相机应用的时候该应用会闪退
imageFile = createImageFile();//创建用来保存照片的文件
mImageUriFromFile = Uri.fromFile(imageFile);
Log.i(TAG, "takePhoto: uriFromFile " + mImageUriFromFile);
if (imageFile != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
/*7.0以上要通过FileProvider将File转化为Uri*/
mImageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
} else {
/*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
mImageUri = Uri.fromFile(imageFile);
}
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
startActivityForResult(takePhotoIntent, TAKE_PHOTO);//打开相机
}
}
}
/**
* 创建用来存储图片的文件,以时间来命名就不会产生命名冲突
*
* @return 创建的图片文件
*/
private File createImageFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
} catch (IOException e) {
e.printStackTrace();
}
return imageFile;
}
/*申请权限的回调*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult: permission granted");
} else {
Log.i(TAG, "onRequestPermissionsResult: permission denied");
Toast.makeText(this, "You Denied Permission", Toast.LENGTH_SHORT).show();
}
}
/*相机或者相册返回来的数据*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
/*如果拍照成功,将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
Log.i(TAG, "onActivityResult: imageUri " + mImageUri);
galleryAddPic(mImageUriFromFile);
mPicture.setImageBitmap(bitmap);//显示到ImageView上
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if (data == null) {//如果没有选取照片,则直接返回
return;
}
Log.i(TAG, "onActivityResult: ImageUriFromAlbum: " + data.getData());
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
handleImageOnKitKat(data);//4.4之后图片解析
} else {
handleImageBeforeKitKat(data);//4.4之前图片解析
}
}
break;
default:
break;
}
}
/**
* 4.4版本以下对返回的图片Uri的处理:
* 就是从返回的Intent中取出图片Uri,直接显示就好
* @param data 调用系统相册之后返回的Uri
*/
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
/**
* 4.4版本以上对返回的图片Uri的处理:
* 返回的Uri是经过封装的,要进行处理才能得到真实路径
* @param data 调用系统相册之后返回的Uri
*/
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
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();
}
displayImage(imagePath);
}
/**
* 将imagePath指定的图片显示到ImageView上
*/
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
mPicture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
/**
* 将Uri转化为路径
* @param uri 要转化的Uri
* @param selection 4.4之后需要解析Uri,因此需要该参数
* @return 转化之后的路径
*/
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;
}
/**
* 将拍的照片添加到相册
*
* @param uri 拍的照片的Uri
*/
private void galleryAddPic(Uri uri) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
sendBroadcast(mediaScanIntent);
}
}
网友评论