标签:
在做项目的时候,总是避免不了头像的剪裁和选取,然而4.4以后 以前能够使用的代码 ,也用不了了。 做下记录吧。因为下面代码我用了几次了。
以后直接复制粘贴。
<span style="white-space:pre"> </span>intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, GALLERY_REQUEST_CODE);
<span style="white-space:pre"> </span>intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, CAMERA_REQUEST_CODE);
private static int CAMERA_REQUEST_CODE = 1; private static int GALLERY_REQUEST_CODE = 2; private static int CROP_REQUEST_CODE = 3;
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST_CODE) { if (data == null) { return; } else { //拍照 Bundle extras = data.getExtras(); if (extras != null) { Bitmap bm = extras.getParcelable("data"); Uri uri = saveBitmap(bm); startImageZoom(uri); } } } else if (requestCode == GALLERY_REQUEST_CODE) { if (data == null) {//相册 return; } Uri uri; uri = data.getData(); Uri fileUri = convertUri(uri); startImageZoom(fileUri); } else if (requestCode == CROP_REQUEST_CODE) { if (data == null) { return; }//剪裁后的图片 Bundle extras = data.getExtras(); if (extras == null) { return; } Bitmap bm = extras.getParcelable("data"); ShowImageView(bm); } }
private Uri convertUri(Uri uri) { InputStream is = null; try { is = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(is); is.close(); return saveBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
private Uri saveBitmap(Bitmap bm) { File tmpDir = new File(Environment.getExternalStorageDirectory() + "/xiaoxin"); if (!tmpDir.exists()) { tmpDir.mkdir(); } File img = new File(tmpDir.getAbsolutePath() + "love.png"); try { FileOutputStream fos = new FileOutputStream(img); bm.compress(Bitmap.CompressFormat.PNG, 85, fos); fos.flush(); fos.close(); Toast.makeText(MainActivity.this, "成功了", Toast.LENGTH_SHORT).show(); return Uri.fromFile(img); } catch (FileNotFoundException e) { Toast.makeText(MainActivity.this, "失敗了", Toast.LENGTH_SHORT).show(); e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "失敗了", Toast.LENGTH_SHORT).show(); return null; } }
/** * 剪裁图片 * * @param uri */ private void startImageZoom(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); intent.putExtra("return-data", true); startActivityForResult(intent, CROP_REQUEST_CODE); }
标签:
原文地址:http://blog.csdn.net/jack_king007/article/details/46403207