转载请注明出处:手机照相/录像、裁剪、从相册选择图片_Mr_Leixiansheng的博客-CSDN博客
package com.example.administrator.takephoto;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
private static final int CHOOSE_PHTOT = 3;
private Button takePhoto; //拍照
private Button choosePhoto; //选择相册图片
private ImageView photo;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.take_photo);
choosePhoto = (Button) findViewById(R.id.choose);
photo = (ImageView) findViewById(R.id.photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//将文件存于手机SD卡根目录下
File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");
try {
//如果存在则删除,无则新建
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
//将Filed对象转换为Uri对象
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");//拍照
//Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");//录像
//intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//录像质量
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//启动相机(带返回结果)
startActivityForResult(intent, TAKE_PHOTO);
}
});
choosePhoto
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
//打开相册
startActivityForResult(intent, CHOOSE_PHTOT);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//启动裁剪
startActivityForResult(intent, CROP_PHOTO);
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream
(getContentResolver().openInputStream(imageUri));
//显示裁剪后的图片
photo.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHTOT:
if (resultCode == RESULT_OK) {
//处理图片
handleImageOnKit(data);
}
break;
default:
break;
}
}
private void handleImageOnKit(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(
uri.getAuthority())) {
//解析出数字格式的ID
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.provider.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())) {
imagePath = getImagePath(uri, null);
}
displayImage(imagePath);
}
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
photo.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
}
}
private String getImagePath(Uri externalContentUri, String selection) {
String path =null;
Cursor cursor = getContentResolver().query(externalContentUri, 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"?>
<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:text="Take Photo"
android:textAllCaps="false"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/choose"
android:text="Choose Photo"
android:textAllCaps="false"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
简洁版:(注意SD卡权限声明)
package com.leixiansheng.test;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btnTakePhoto;
private ImageView ivPhoto;
private File file;
private Uri fileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initCamera();
setOnclickListener();
}
private void setOnclickListener() {
btnTakePhoto.setOnClickListener(this);
}
private void initView() {
btnTakePhoto = (Button) findViewById(R.id.take_photo);
ivPhoto = (ImageView) findViewById(R.id.image_view);
}
@Override
public void onClick(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileName);
startActivityForResult(intent, 1);
}
private void initCamera() {
try {
file = new File(Environment.getExternalStorageDirectory(), "image.jpg"); //存储位置及文件名称
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
fileName = Uri.fromFile(file);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
ivPhoto.setImageURI(fileName);
}
}
}
}