最近在做一个图片上传,在上传之前需要对照片进行裁剪,遇到一个坑,在别的手机上运行都正常,在小米手机上却遇见一个问题,选中图片无法裁剪,直接闪退,目前已解决!之前出过问题的地方会标红
//选择图片
private void choosePhotos(){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, CHOOSE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOOSE_PICTURE:
// 对图片进行裁剪处理
cutImage(data.getData());
break;
case CROP_SMALL_PICTURE:
if (data != null) {
try {
Bitmap head=BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
// 让刚才选择裁剪得到的图片显示在界面上
setImageView (head);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
}
// 对图片进行裁剪处理
protected void cutImage(Uri uri) {
//com.android.camera.action.CROP这个action是用来裁剪图片用的
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
//这里不用return-data返回(稍后解释)
//intent.putExtra("return-data", true);
uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "temp_image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, CROP_SMALL_PICTURE);
}
//图片回显
private void setImageView (Bitmap bitmap){
Bitmap bitmap_bg=Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas=new Canvas(bitmap_bg);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
//这里使用了绘图的模式的功能,PorterDuff.Mode.SRC_IN表示两个图层显示重合部分上面图层的内容
canvas.drawOval(new RectF(0,0,bitmap.getWidth(),bitmap.getHeight()),paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap,0,0,paint);
Drawable drawable =new BitmapDrawable(bitmap_bg);
//personImage是需要赋值的id
image.setImageDrawable(drawable);
}
OK!从照片库选择裁剪并且上传就成功了!
若是截取小图可以直接 intent.putExtra("return-data", true);
若是大图可将图片直接转成uri进行传递