How to resize an image i picked from the gallery in android?

后端 未结 2 919
盖世英雄少女心
盖世英雄少女心 2020-12-09 12:00

I am building an android where. Inside of one activity I have an image button. When I click on it the gallery opens up and I can choose an image. Then I set that image as th

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 12:22

    You can use this method to get a resized image. This way you can avoid OutOfMemoryError

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

提交回复
热议问题