在安卓设备上将大型位图文件调整大小以生成缩放输出文件

223

我有一个大的位图文件(比如3888x2592),现在我想将该位图调整为800x533并保存到另一个文件中。

通常情况下,我会通过调用Bitmap.createBitmap方法对位图进行缩放,但它需要一个源位图作为第一个参数,由于加载原始图像到位图对象中当然会超过内存限制(例如见这里),因此我无法提供这个参数。

我也无法使用BitmapFactory.decodeFile(file, options)读取位图文件,并提供BitmapFactory.Options.inSampleSize参数,因为我想要将其调整为精确的宽度和高度。使用inSampleSize将会将位图缩放到972x648(如果我使用inSampleSize=4)或778x518(如果我使用inSampleSize=5,这甚至不是2的幂次方)。

我也想避免在第一步中使用inSampleSize读取图像,例如以972x648的大小读取图像,然后在第二步将其调整为精确的800x533,因为与直接调整原始图像相比,质量会很差。

总结一下我的问题: 有没有一种方法可以读取一个10MP或更大的大型图像文件,并将其调整为指定的新宽度和高度,而不会出现OutOfMemory异常?

我还尝试过使用BitmapFactory.decodeFile(file, options)并手动设置Options.outHeight和Options.outWidth值为800和533,但这种方式行不通。


不,outHeight和outWidth是解码方法的out参数。话虽如此,我遇到了和你一样的问题,而且对这个两步方法也不太满意。 - rds
经常,谢天谢地,你可以使用一行代码.. https://dev59.com/Cmw05IYBdhLWcg3w_Guw#17733530 - Fattie
读者们,请注意这个非常重要的 QA!!!https://dev59.com/VWAf5IYBdhLWcg3w7mU_#24135522 - Fattie
1
请注意,这个问题现在已经五年了,完整的解决方案是.. https://dev59.com/VWAf5IYBdhLWcg3w7mU_#24135522 干杯! - Fattie
2
现在有关于这个主题的官方文档:https://developer.android.com/training/displaying-bitmaps/load-bitmap.html - Vince
21个回答

-2
使用以下代码调整位图大小。
    public static Bitmap decodeFile(File file, int reqWidth, int reqHeight){

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;        
    BitmapFactory.decodeFile(file.getPath(), options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(file.getPath(), options);
   }

    private static int calculateInSampleSize(
    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
     }

     return inSampleSize;
   }    

同样的内容也在下面的技巧/提示中有解释

http://www.codeproject.com/Tips/625810/Android-Image-Operations-Using-BitmapFactory


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接