Android:来自sdCard的setImageBitmap不起作用

时间:2016-05-19 13:06:47

标签: android mediastore

我希望用户从SD卡中选择照片并在ImageView中显示

我的代码:

try {
    bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
    e.printStackTrace();
}
imgOne.setImageBitmap(bm);

但是这段代码不起作用

用户选择照片后的onActivityResult代码

  

我的课程:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Log.i("error", "" + requestCode);
            final ImageView imgOne = (ImageView) G.currentActivity.findViewById(R.id.imgOne);
            if (requestCode == 1) {
                Bitmap bm = null;
                if (data != null) {
                    try {
                        bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
                        //ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        //bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

                        //bm = Bitmap.createScaledBitmap(bm, 600, 600, true);
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }

                    imgOne.setImageBitmap(bm);
                    Log.i("error", "" + bm);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

      final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

                imageView.setImageBitmap(selectedImage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }