Resize a large bitmap file to scaled output file on Android

前端 未结 21 1521
执念已碎
执念已碎 2020-11-22 05:51

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling

21条回答
  •  佛祖请我去吃肉
    2020-11-22 06:13

    Justin answer translated to code (works perfect for me):

    private Bitmap getBitmap(String path) {
    
    Uri uri = getImageUri(path);
    InputStream in = null;
    try {
        final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
        in = mContentResolver.openInputStream(uri);
    
        // Decode image size
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
    
    
    
        int scale = 1;
        while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > 
              IMAGE_MAX_SIZE) {
           scale++;
        }
        Log.d(TAG, "scale = " + scale + ", orig-width: " + options.outWidth + ", 
           orig-height: " + options.outHeight);
    
        Bitmap resultBitmap = null;
        in = mContentResolver.openInputStream(uri);
        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            options = new BitmapFactory.Options();
            options.inSampleSize = scale;
            resultBitmap = BitmapFactory.decodeStream(in, null, options);
    
            // resize to desired dimensions
            int height = resultBitmap.getHeight();
            int width = resultBitmap.getWidth();
            Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
               height: " + height);
    
            double y = Math.sqrt(IMAGE_MAX_SIZE
                    / (((double) width) / height));
            double x = (y / height) * width;
    
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(resultBitmap, (int) x, 
               (int) y, true);
            resultBitmap.recycle();
            resultBitmap = scaledBitmap;
    
            System.gc();
        } else {
            resultBitmap = BitmapFactory.decodeStream(in);
        }
        in.close();
    
        Log.d(TAG, "bitmap size - width: " +resultBitmap.getWidth() + ", height: " + 
           resultBitmap.getHeight());
        return resultBitmap;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(),e);
        return null;
    }
    

提交回复
热议问题