【Android】从相册读取一个图片设置到ImageView中

昨晚遇到一个问题,从相册里选择一个图片展示到ImageView上,一直没反应。

1.点击按钮发起跳转

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_PICK_IMAGE);

2.选择后处理

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_PICK_IMAGE && resultCode == RESULT_OK && null != data) {
            //获取返回的数据
            Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
            //bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inSampleSize = 2;
//
//            bitmap = BitmapFactory.decodeFile(picturePath, options);



//            Matrix matrix = new Matrix();
//            matrix.setScale(0.1f, 0.1f);
//            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
//                    bitmap.getHeight(), matrix, true);


//            bitmap = Bitmap.createScaledBitmap(bitmap, DpUtils.dip2px(UploadActivity.this,250), DpUtils.dip2px(UploadActivity.this,250), true);

            upload.setImageBitmap(bitmap);

            tag.setVisibility(View.GONE);
            upload.setVisibility(View.VISIBLE);
        }
    }

3.一切都看似顺利,但是就是没有任何反应。

去搜了setImageBitmap无效,

①很多博客说小米等手机做了内存防溢出处理。于是我又试了各种方法缩小图片,会闪一下选择的照片后类似死机。
②有的说可能是我没加权限,在ManiFest文件中加入

 

③最后解决的也是很奇怪,居然是因为我原来ImageView在布局文件中先设置了background,这句去掉之后一切都正常了。因为setImageBitmap设置的是src,可能是发生了冲突?不太清楚。

4.scaleType设置无效,因为设置的图片必须放在drawable-hdpi中


如果有小伙伴遇到类似情况,可以参考一下~

你可能感兴趣的:(Android开发)