从Inputstream采样图像而不解码为Bitmap

时间:2015-05-09 12:03:31

标签: java android bitmap inputstream outputstream

我正在尝试找到一种解决方案,可以将Url中的图像下载到文件系统中并调整大小,而无需先将其解码为位图。

我能找到的唯一解决方案是使用特定的SampleSize将其解码为位图的方法。但是,这里的问题是在创建位图时会消耗大量内存,这会根据设备上可用的空闲内存限制图像的最大大小。另一个问题是它需要花费大量时间将其解码为Bitmap,并将其压缩回输出流。

我当前的代码如下所示(options1包含原始尺寸,calculateSampleSizeForImageSize()为较小的所需Imagesize计算sampleSize):

 if (maximumImageSize  < Runtime.getRuntime().maxMemory() / 4f) {
                //enough memory free to reduce size
                //reduce size
                BitmapFactory.Options options2 = new BitmapFactory.Options();
                options2.inSampleSize = calculateSampleSizeForImageSize(options1, maximumImageSize);
                options2.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeStream(is, null, options2);
                try {
                    //write reduced size bitmap to picture file
                    os = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                    os.flush();
                    bitmap.recycle();
                    return 0;
                } catch (IOException e) {
                    Log.d(TAG, "failed to fetch image", e);
                    throw new IOException(e);
                } finally {
                    closeStream(os);
                    closeStream(is);
                }

那么有没有办法绕过位图并直接将缩小的输入流写入输出流?

0 个答案:

没有答案