private int PHOTO_REQUEST_CAREMA = 0; private int PHOTO_REQUEST_GALLERY = 1; private File tempFile; private String PHOTO_FILE_NAME = "output_image.jpg"; private int PHOTO_REQUEST_CUT = 3; private String PHOTO_NAME = "image.jpg"; private File file;
/* * 从相机获取 */ public void camera() { // 激活相机 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // 判断存储卡是否可以用,可用进行存储 if (hasSdcard()) { tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME); // 从文件中创建uri Uri uri = Uri.fromFile(tempFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA startActivityForResult(intent, PHOTO_REQUEST_CAREMA); } /* * 从相册获取 */ public void gallery() { // 激活系统图库,选择一张图片 Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY startActivityForResult(intent, PHOTO_REQUEST_GALLERY); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PHOTO_REQUEST_GALLERY) { // 从相册返回的数据 if (data != null) { // 得到图片的全路径 uri = data.getData(); crop(uri);//裁剪图片 } } else if (requestCode == PHOTO_REQUEST_CAREMA) { // 从相机返回的数据 if (hasSdcard()) { crop(Uri.fromFile(tempFile)); } else { Toast.makeText(MenuEditingActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show(); } } else if (requestCode == PHOTO_REQUEST_CUT) { // 从剪切图片返回的数据 if (data != null) { Bitmap bitmap = data.getParcelableExtra("data"); ivDisplayImage.setImageBitmap(bitmap); try { file = new File(Environment.getExternalStorageDirectory(), PHOTO_NAME); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); //压缩 bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); outputStream.flush(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } try { // 将临时文件删除 tempFile.delete(); } catch (Exception e) { e.printStackTrace(); } } } private boolean hasSdcard() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } /* * 剪切图片 */ private void crop(Uri uri) { // 裁剪图片意图 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); // 裁剪框的比例,1:1 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // 裁剪后输出图片的尺寸大小 intent.putExtra("outputX", 250); intent.putExtra("outputY", 250); intent.putExtra("outputFormat", "PNG");// 图片格式 intent.putExtra("noFaceDetection", true);// 取消人脸识别 intent.putExtra("return-data", true); // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT startActivityForResult(intent, PHOTO_REQUEST_CUT); }