将位图裁剪为特定宽度和高度而不会丢失分辨率

时间:2014-06-18 10:30:16

标签: android bitmap crop

我需要从图库裁剪图像并保存到服务器。这是我裁剪图像的代码

   private void startCropImage() {

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(mImageCaptureUri, "image/*");

    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
        //indicate output X and Y
    intent.putExtra("outputX", 400);
    intent.putExtra("outputY", 487);

    intent.putExtra("return-data", true);
    intent.putExtra("scale", true);
    startActivityForResult(intent, CROP_FROM_GALLERY);
}

我需要输出400 * 487,但在检查宽度后裁剪图像时,设备上只有160,但在AVD上显示正确的宽度。为什么会这样?以下是我的onActivityResult代码

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {

Bitmap bm2 = extras2.getParcelable("data");

imgview.setImageBitmap(bm2);

int width = bm2.getWidth();}

2 个答案:

答案 0 :(得分:0)

检查此行:

Bitmap bm2 = extras2.getParcelable("data");

意图只能传输有限的数据量。根据版本或设备的不同,它的范围可能从200kb到1mb。所以这一行返回了裁剪图像的缩略图。要获得完整图像,请执行以下操作。请记住,您无法获得所需的确切宽度。

Uri selectedImage = data.getData();
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(
                           selectedImage, filePath, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        Bitmap bmp= BitmapFactory.decodeFile(filePath);

您需要裁剪图像的文件系统中的实际路径。 的更新 com.android.camera.action.CROP不是官方的android意图。画廊和相机等应用程序支持它,但有许多设备不支持此意图。查看@commonsware的this博客文章。我已使用此SO post中的库回答裁剪图像。

答案 1 :(得分:0)

我不知道你可能知道这个图书馆我的建议只是我没有给出答案的代码,我给予选择

为什么要重新发明轮子 :)(当然我们可以改进)

  

https://github.com/edmodo/cropper