android - 从 InputStream 调整位图大小

标签 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 怎么可能?

最佳答案

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

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

关于android - 从 InputStream 调整位图大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841482/

相关文章:

android - 动态调整android中实际图像的大小如何实现

java - 当第二次打开 AlertDialog 时应用程序崩溃

android - 自动调整 TextView 大小以在 Canvas 上绘制

android - 如何从我的应用程序中找出最近 10 天的通话和短信详细信息

android - 在单独的线程中处理位图

java - 如何从 AsyncTask 获取位图并将其设置为我的图像

javascript - 在 Firefox 中创建自定义按钮(使用自定义按钮插件)不允许我调整按钮图像的大小

android - 使用 DownloadManager 从 S3 下载 apk 文件

delphi - Canvas.TransparentColor 和 Canvas.Draw 与不透明度的组合

javascript - html5 canvas在firefox下性能不佳