权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CAMERA"/>
private static final int PHOTO_GRAPH = 2;// 拍照 private static final int PHOTO_ZOOM = 3; // 缩放 private static final int PHOTO_RESULT = 4;// 结果 private static final String IMAGE_UNSPECIFIED = "image/*"; AlertDialog.Builder builder=new AlertDialog.Builder(InfoActivity.this); builder.setTitle("头像"); builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { } }); String[] items=new String[]{"相册上传","拍摄上传"}; builder.setItems(items, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { if(which == 0){ //从相册获取图片 Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED); startActivityForResult(intent, PHOTO_ZOOM); } else if(which == 1){ //从拍照获取图片
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDirectory(),"temp.jpg"))); startActivityForResult(intent, PHOTO_GRAPH); } } }); builder.create().show(); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //获取图片路径 if (resultCode == 0) return; // 拍照 if (requestCode == PHOTO_GRAPH) { // 设置文件保存路径 File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); startPhotoZoom(Uri.fromFile(picture)); } if (data == null) return; // 读取相册缩放图片 if (requestCode == PHOTO_ZOOM) { startPhotoZoom(data.getData()); } // 处理结果 if (requestCode == PHOTO_RESULT) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0-100)压缩文件 //此处可以把Bitmap保存到sd卡中,具体请看:http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html imageView_head.setImageBitmap(photo); //把图片显示在ImageView控件上 myApp = (MyGlobal)getApplication(); myApp.saveUserHead(user_id, photo); EventMessage eventMessage = new EventMessage(); eventMessage.setWhich(3); EventBus.getDefault().post(eventMessage); } } } public void startPhotoZoom(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, IMAGE_UNSPECIFIED); intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例,输入需要是整数,不然无效,其中1比1是圆形
intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪图片宽高 intent.putExtra("outputX", 500); intent.putExtra("outputY", 500); intent.putExtra("return-data", true); startActivityForResult(intent, PHOTO_RESULT); }
考虑版本适配与机型适配的问题后private CircleImageView iv_avatar;
private String TAG = "Main2Activity"; private final int GALLERY_REQUSET_CODE = 0; private final int CROP_REQUEST_CODE = 1; private final int GALLERY_REQUSET_CODE_KITKAT = 2; private Uri uritempFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); FindView(); iv_avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
//相册上传 routeToGallery();
//拍照上传
/*
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
//创建文件夹
File appDir = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_name));
if (!appDir.exists()) {
appDir.mkdirs();
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri pictureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),getString(R.string.app_name)+"/temp.png"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, PHOTO_GRAPH);
*/
} }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case GALLERY_REQUSET_CODE: handleGalleryResult(resultCode, data); break; case GALLERY_REQUSET_CODE_KITKAT: handleGalleryKitKatResult(resultCode, data); break; case CROP_REQUEST_CODE: // 此处crop正常返回resultCode也不为RESULT_OK if(data == null) return; Bundle bundle = data.getExtras(); if (Build.MODEL.contains("MI")) { try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile)); BitmapDrawable bd = new BitmapDrawable(bitmap); iv_avatar.setImageDrawable(bd); } catch (FileNotFoundException e) { Log.e("Exception PHOTO_RESULT", e.getMessage(), e); } } else { Bitmap face = bundle.getParcelable("data"); BitmapDrawable bd = new BitmapDrawable(face); //my_index_background.setImageBitmap(face); iv_avatar.setImageDrawable(bd); } break; // case PHOTO_GRAPH: // // 设置文件保存路径 // File picture = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_name) + "/temp.png"); // Uri uri = Uri.fromFile(picture); // routeToCrop(uri); // break; default: break; } } //打开相册 private void routeToGallery() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { startActivityForResult(intent, GALLERY_REQUSET_CODE_KITKAT); } else { startActivityForResult(intent, GALLERY_REQUSET_CODE); } } // 裁剪 private void routeToCrop(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra("crop", true); // intent.putExtra("circleCrop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); if (Build.MODEL.contains("MI")) { uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); } else { intent.putExtra("return-data", true); } startActivityForResult(intent, CROP_REQUEST_CODE); } private File saveBitmap(Bitmap bitmap) throws IOException { File file = new File(getExternalCacheDir(), "face-cache"); if (!file.exists()) file.createNewFile(); try (OutputStream out = new FileOutputStream(file)) { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); } return file; } private void handleGalleryResult(int resultCode, Intent data) { if(resultCode != RESULT_OK) return; String path = data.getData().getPath(); Bitmap image = BitmapFactory.decodeFile(path); File faceFile; try { faceFile = saveBitmap(image); } catch (IOException e) { e.printStackTrace(); return; } Uri fileUri = Uri.fromFile(faceFile); routeToCrop(fileUri); } // Result uri is "content://" after Android 4.4 private void handleGalleryKitKatResult(int resultCode, Intent data) { if(resultCode != RESULT_OK) return; Uri contentUri = data.getData(); if (contentUri == null) return; File faceFile; try { ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(contentUri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); faceFile = saveBitmap(image); } catch (IOException e) { e.printStackTrace(); return; } Uri fileUri; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Android 7.0 "file://" uri权限适配 fileUri = FileProvider.getUriForFile(this, "com.example.m_evolution.fileprovider", faceFile); } else { fileUri = Uri.fromFile(faceFile); } routeToCrop(fileUri); } private void FindView(){ iv_avatar = findViewById(R.id.iv_user_avatar); }
在manifests.xml中加入:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.m_evolution"> <application> <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.example.m_evolution.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /> </provider> </application> </manifest>
provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <paths> <external-cache-path name="mycache" path="./" /> </paths> </resources>