创建缩放位图会导致图像无效

时间:2011-05-12 05:20:10

标签: android image bitmap

我创建了一个将位图直接缩放到特定表面区域的函数。该函数首先获取位图的宽度和高度,然后找到最接近所需大小的样本大小。最后,图像缩放到确切的大小。这是我找到解码缩放位图的唯一方法。问题是从BitmapFactory.createScaledBitmap(src,width,height,filter)返回的位图总是以宽度和高度-1返回。我已经实现了使用createScaledBitmap()方法的其他函数,但没有找到任何理由为什么创建缩放位图会产生无效输出。我还发现,如果我创建一个可变的图像位图副本会导致相同的错误。感谢

public static Bitmap load_scaled_image( String file_name, int area) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file_name, options);
    double ratio = (float)options.outWidth / (float)options.outHeight;
    int width, height;
    if( options.outWidth > options.outHeight ) {
        width = (int)Math.sqrt(area/ratio);
        height = (int)(width*ratio);
    }
    else {
        height = (int)Math.sqrt(area/ratio);
        width = (int)(height*ratio);
    }
    BitmapFactory.Options new_options = new BitmapFactory.Options();
    new_options.inSampleSize = Math.max( (options.outWidth/width), (options.outHeight/height) );
    Bitmap image = BitmapFactory.decodeFile(file_name, new_options);
    return Bitmap.createScaledBitmap(image, width, height, true);
}

我添加了此功能,可将大型相机图像缩放到特定数量的百万像素。因此传入的典型区域为1000000,用于100万像素。解码后的相机图像产生1952的outWidth和3264的outHieght。然后我通过这种方式计算比率,我可以保持与缩放图像相同的高宽比,在这种情况下比率是0.598 ...使用比率和新的表面积我可以找到新的宽度773和高度1293.773x1293 = 999489,这只是约100万像素。接下来,我计算解码新图像的样本大小,在这种情况下,样本大小为4,图像解码为976x1632。所以我的宽度为773,高度为1293.

1 个答案:

答案 0 :(得分:1)

我遇到了类似的问题(缩放位图的高度和宽度为-1)。 在这个stackOverflow线程之后: Android how to create runtime thumbnail 我在调用函数时尝试使用相同的位图两次:

imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, 
                                        THUMBNAIL_SIZE, false);

出于某种原因,这解决了我的问题,也许它也会解决你的问题。

相关问题