java.lang.OutOfMemoryError in android while getting image from gallery in android

后端 未结 4 1130
走了就别回头了
走了就别回头了 2020-12-30 11:32

I am picking a picture from gallery using code

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCont         


        
4条回答
  •  春和景丽
    2020-12-30 12:22

    Try this :

    @Override
        protected void onActivityResult(int requestCode, int resultCode,
                Intent imageReturnedIntent) {
            super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
            switch (requestCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();
                    try {
                        picImageView.setImageBitmap(decodeUri(selectedImage));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    

    And then declare the following function :

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(selectedImage), null, o);
    
            final int REQUIRED_SIZE = 100;
    
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
    
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(selectedImage), null, o2);
        }
    

    Thanks.

提交回复
热议问题