首页 > 解决方案 > 从图像选择器中裁剪的图像

问题描述

我正在尝试从图像选择器中获取裁剪的图像。我可以选择一个图像并查看裁剪的矩形。但是在裁剪返回到我的活动后,我uri的始终为空......“onActivityResult”将不会被调用。

我的代码:

        iv.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                int imageX = iv.getMeasuredWidth();
                int imageY = iv.getMeasuredHeight();

                pickImageIntent.setType("image/*");
                pickImageIntent.putExtra("crop", "true");
                pickImageIntent.putExtra("outputX", imageX);
                pickImageIntent.putExtra("outputY", imageY);
                pickImageIntent.putExtra("aspectX", imageX);
                pickImageIntent.putExtra("aspectY", imageY);
                pickImageIntent.putExtra("scale", true);
                pickImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(pickImageIntent,REQ_CODE_PICK_GALLERY);
            }
        });

也叫

pickImageIntent.putExtra("return-data", true);

或者

@Override
    protected void onResume(){
        super.onResume();
        iv.setImageURI(uri);
    }

也不起作用...

这些是我的权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

我也试过:

pickImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
pickImageIntent.putExtra("return-data", true);

并在作品中获得位图onActivityResult,但imagesize太小了。感觉像

pickImageIntent.putExtra("outputX", imageX);
pickImageIntent.putExtra("outputY", imageY);

被忽略了,我该怎么办?

标签: android

解决方案


您必须覆盖“onActivityResult”,而不是“onResume”。这是一个可以帮助您的示例

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

推荐阅读