从InputStream调整位图大小

时间:2012-10-11 14:07:13

标签: android bitmap resize-image

我尝试从InputStream调整一个图像的大小,所以我使用Strange out of memory issue while loading an image to a Bitmap object中的代码,但我不知道为什么这段代码总是返回没有图像的Drawable。

这个很好用:

private Drawable decodeFile(InputStream f){
    try {
        InputStream in2 = new BufferedInputStream(f);
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=2;
        return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
    } catch (Exception e) {
        return null;
    }
}

这个不起作用:

private Drawable decodeFile(InputStream f){
    try {
        InputStream in1 = new BufferedInputStream(f);
        InputStream in2 = new BufferedInputStream(f);
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in1,null,o);

        //The new size we want to scale to
        final int IMAGE_MAX_SIZE=90;

        //Find the correct scale value. It should be the power of 2.
        int scale = 2;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / 
               (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inJustDecodeBounds = false;
        o2.inSampleSize=scale;
        return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
    } catch (Exception e) {
        return null;
    }
}

为什么一个选项影响另一个?如果我使用两个不同的InputStream和Options,它是如何实现的?

2 个答案:

答案 0 :(得分:8)

实际上,您有两个不同的BufferedInputStream,但它们内部只使用一个InputStream对象,因为BufferedInputStream只是InputStream的包装。

因此,您不能只在同一个流上调用两次BitmapFactory.decodeStream方法,它肯定会失败,因为第二次它不会从流的开头开始解码。如果您的流受支持或重新打开,则需要重置该流。

答案 1 :(得分:1)

这是我的代码运行良好,我希望这会有所帮助

//Decode image size
    BitmapFactory.Options optionsIn = new BitmapFactory.Options();
    optionsIn.inJustDecodeBounds = true; // the trick is HERE, avoiding memory leaks
    BitmapFactory.decodeFile(filePath, optionsIn);

    BitmapFactory.Options optionsOut = new BitmapFactory.Options();
    int requiredWidth = ECameraConfig.getEntryById(Preferences.I_CAMERA_IMAGE_RESOLUTION.get()).getyAxe();
    float bitmapWidth = optionsIn.outWidth;
    int scale = Math.round(bitmapWidth / requiredWidth);
    optionsOut.inSampleSize = scale;
    optionsOut.inPurgeable = true;//avoiding memory leaks
    return BitmapFactory.decodeFile(filePath, optionsOut);

我相信你不需要2个InputStream。