Android中打开手机系统相机和相册,并进行图片裁剪经常被用到,这里写了一个工具类,希望对大家有帮助。主要功能有,获取打开系统相机、相册、裁剪功能的intent,更新手机媒体库方法,以及保存文件功能。详细代码如下:
public class CameraUtil {
/**
* 检测SD卡是否可用
*
* @return true 可用,false不可用。
*/
public static boolean isSDExit() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 新建文件夹到手机本地
*
* @param fileFolder ,文件夹的路径名称
* @return
*/
public static boolean createDir(String fileFolder) {
File dir = new File(fileFolder);
if (!dir.exists()) {
return dir.mkdirs();
}
return false;
}
/**
* 新建文件到手机本地
*
* @param fileNameWithPath ,文件名包含路径
* @return , true新建成功, false新建失败
*/
public static boolean createFile(String fileNameWithPath) {
File file = new File(fileNameWithPath);
try {
if (isSDExit() && file.exists()) {
if (file.delete()) {
return file.createNewFile();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 新建文件到手机指定路径
*
* @param dirPath ,文件的文件夹目录路径
* @param fileName ,文件名
* @return , true新建成功, false新建失败
*/
public static boolean createFile(String dirPath, String fileName) {
File file = new File(dirPath, fileName);
try {
if (isSDExit() && file.exists()) {
if (file.delete()) {
return file.createNewFile();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 创建相机拍照图片名称
*
* @param fileType ,文件的类型,即扩展名,例如.jpg 、.mp4 、.mp3等
* @return , 图片文件名,格式形式20161011_111523.jpg
*/
public static String createFileName(String fileType) {
String fileName = "";
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
fileName = sdf.format(date) + fileType;
return fileName;
}
/**
* 保存图片的Bitmap数据到sd卡指定路径
*
* @param fileNameWithPath ,图片的路径
* @param bitmap ,图片的bitmap数据
*/
public static void savePhotoToPath(String fileNameWithPath, Bitmap bitmap) {
if (isSDExit()) {
File file = new File(fileNameWithPath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (bitmap != null) {
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)) {
fos.flush();
fos.close();
}
}
} catch (FileNotFoundException e) {
file.delete();
e.printStackTrace();
} catch (IOException e) {
file.delete();
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 删除文件
*
* @param dirPath ,文件的文件夹目录路径
* @param fileName ,文件名
* @return , true删除成功, false删除失败
*/
public static boolean deleteFile(String dirPath, String fileName) {
File file = new File(dirPath, fileName);
if (!file.exists()) {
return true;
}
return file.delete();
}
/**
* 更新系统的Media库
*
* @param context
*/
public static void updateSystemMedia(Context context) {
MediaScannerConnection.scanFile(context, new String[]{
android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
}, null, null);
}
/**
* 打开手机系统相册, method one
*
* @return intent, Activity调用的intent
*/
public static Intent openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
return intent;
}
/**
* 打开手机系统相册, method two
*
* @return intent, Activity调用的intent
*/
public static Intent openGallery() {
return new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
/**
* 打开手机系统相机拍照
*
* @param uri , 用于保存手机拍照后所获图片的uri
* @return intent, Activity调用的intent
*/
public static Intent openCamera(Uri uri) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra("autofocus", true);//进行自动对焦操作
return intent;
}
/**
* 打开手机系统的图片裁剪Activity
*
* @param inUri , 待裁剪图片的uri
* @param outUri , 裁剪后图片保存的uri
* @return intent , Activity调用的intent
*/
public static Intent cropPicture(Uri inUri, Uri outUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(inUri, "image/*"); //设置图片资源路径
intent.putExtra("scale", true);
intent.putExtra("crop", true);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
return intent;
}
}
public class CameraActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
private final int ACT_GALLERY = 0;
private final int ACT_CAMERA = 1;
private final int ACT_CROP = 2;
private final int ACT_PERMISSION = 3;
private Context context = null;
private Uri pictureUri = null;
private String filePath = android.os.Environment.getExternalStorageDirectory() + File.separator + "DICM" + File.separator;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_camera);
CameraUtil.createDir(filePath);
initView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case ACT_GALLERY:
galleryBack(data.getData());
break;
case ACT_CAMERA:
startCrop(pictureUri);
break;
case ACT_CROP:
cropBack(pictureUri);
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permission, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permission, grantResults);
switch (requestCode) {
case ACT_PERMISSION:
if (grantResults.length > 0 && PackageManager.PERMISSION_GRANTED == grantResults[0]) {
Log.d(TAG, "permission allowed");
Intent intent = CameraUtil.openCamera(pictureUri);
startActivityForResult(intent, ACT_CAMERA);
} else {
Log.d(TAG, "permission denied");
}
break;
}
}
private void initView() {
Button openGallery = (Button) findViewById(R.id.btn_gallery);
Button openCamera = (Button) findViewById(R.id.btn_camera);
if (openGallery != null) {
openGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startGallery();
}
});
}
if (openCamera != null) {
openCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startCamera();
}
});
}
}
private void startGallery() {
Intent intent = CameraUtil.openGallery();
startActivityForResult(intent, ACT_GALLERY);
}
private void startCamera() {
String fileName = CameraUtil.createFileName(".jpg");
CameraUtil.createFile(filePath, fileName);
File file = new File(filePath, fileName);
pictureUri = Uri.fromFile(file);
//request the camera permission dynamic above android 6.0
boolean permission = PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
if (permission) {
Intent intent = CameraUtil.openCamera(pictureUri);
startActivityForResult(intent, ACT_CAMERA);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, ACT_PERMISSION);
}
}
private void startCrop(Uri inUri) {
Intent intent = CameraUtil.cropPicture(inUri, pictureUri);
startActivityForResult(intent, ACT_CROP);
}
private void galleryBack(Uri inUri) {
//get picture uri from gallery
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(inUri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
startCrop(Uri.fromFile(new File(filePath)));
}
if (!cursor.isClosed()) {
cursor.close();
}
}
}
private void cropBack(Uri inUri) {
if (inUri == null) {
return;
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(inUri));
//to display or save the picture
} catch (Exception e) {
e.printStackTrace();
}
}
}
String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(inUri, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); startCrop(Uri.fromFile(new File(filePath))); } if (!cursor.isClosed()) { cursor.close(); } }
这点是需要注意的,不然有些手机上是会报获取图片失败。