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

后端 未结 4 1129
走了就别回头了
走了就别回头了 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:09

    Add below function into your java file and call this function in onActivityResult() after getting image path or image uri, it will solve your problem.

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o);
    
        // The new size we want to scale to
        final int REQUIRED_SIZE = 100;
    
        // Find the correct scale value. It should be the power of 2.
        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;
        }
    
        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o2);
    }
    

提交回复
热议问题