安卓调用系统相机进行拍照
调用系统相机进行拍照的话,步骤比较简单,分为两步
- 使用隐式Intent打开相机
- 在onActivityResult回调中对图片进行处理 (传回来的图片分为缩略图和原图,缩略图比较小可以直接进行展示,原图比较大,需要传输到文件中显示)
拍照获取缩略图
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:id="@+id/image" />
private static final int REQ_CODE = 1;
private void takePhone(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退,要是不加这句则当系统没有相机应用的时候该应用会闪退
Log.e(TAG, "onClick: 手机有拍照功能" );
startActivityForResult(intent,REQ_CODE);//启动相机
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE && resultCode == RESULT_OK){
Log.e(TAG, "onActivityResult: jinru" );
Bundle extras = data.getExtras();
Bitmap data1 = (Bitmap) extras.get("data");
addressImage.setImageBitmap(data1);
Log.e(TAG, "onActivityResult: data"+data1.toString() );
}
}
拍照获取原图
- 先在清单文件applicaion当中配置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.ceshiapplication.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
</application>
- xml布局 file_paths.xml
<paths>
<external-path
name="my_images"
path="."/>
</paths>
3.Java代码
private static final int REQUEST_TAKE_PHOTO_CODE = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.example.ceshiapplication.fileProvider";
private Uri imageUri;
private void takePhoto() {
//拍照并获取大图 图片存入相册
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File imageFile = createImageFile();//创建用来保存图片的文件
Log.e(TAG, "takePhoto: imageFile" + imageFile);
if (imageFile != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
//7.0以上需要通过FileProvider将file转换成uri
imageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
} else {
imageUri = Uri.fromFile(imageFile);
}
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_TAKE_PHOTO_CODE);
}
}
private File createImageFile() {
String format = new SimpleDateFormat("yyyy-MM-DD").format(new Date());
String fileName = "JDEG_" + format + "_";
File file = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File imageFile = File.createTempFile(fileName, ".jpg", file);
return imageFile;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
addressImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
打开相册获取图片
步骤和打开相机差不多 都是使用隐式Intent
private static final int CHOOSE_PHONE = 3;
private void openAlbum() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHONE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_PHONE && resultCode == RESULT_OK){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
displayPicture(data);//4.4之后图片解析
}else {
lowVersionDisplayPicture(data);//4.4之前图片解析
}
}
}
/**
* 4.4版本以下对返回的图片Uri的处理:
* 就是从返回的Intent中取出图片Uri,直接显示就好
* @param data 调用系统相册之后返回的Uri
*/
private void lowVersionDisplayPicture(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri,null);
displayImage(imagePath);
}
/**
* 4.4版本以上对返回的图片Uri的处理:
* 返回的Uri是经过封装的,要进行处理才能得到真实路径
* @param data 调用系统相册之后返回的Uri
*/
@TargetApi(19)
private void displayPicture(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(getActivity(), 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);
addressImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getActivity(), "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 = getActivity().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;
}
|