防止将位图写入正在缩放的​​磁盘

时间:2014-02-21 00:44:48

标签: android bitmap fileoutputstream

我遇到了一个问题,当我将一个位图写入磁盘时,它会被写入磁盘,但它会被写成一个微小的图像(文件大小为3kb或更少)。

我已经检查过源图像确实是正确的尺寸,但是输出图像似乎缩小了,尽管将位图选项配置为不缩放。

@Override
protected Void doInBackground(PPImage... params) {
    String filename = "pp_" + position + ".jpg";
    File externalStorageDirectory = Environment.getExternalStorageDirectory();
    final File destination = new File(externalStorageDirectory, filename);

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 16;
    opts.inPurgeable = true;
    opts.inScaled = false;

    decode(opts, Uri.parse(params[0].getUri()), getActivity(), new OnBitmapDecodedListener() {
        @Override
        public void onDecoded(Bitmap bitmap) {
            try {
                FileOutputStream out = new FileOutputStream(destination, false);
                writeImageToFileTask.this.holder.pathToImage = destination.getAbsolutePath();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();

                MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), destination.getAbsolutePath(), destination.getName(), destination.getName());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    return null;
}

private void decode(BitmapFactory.Options options, Uri mUri, Context mContext, OnBitmapDecodedListener listener) {
    try {
        InputStream inputStream;
        if (mUri.getScheme().startsWith("http") || mUri.getScheme().startsWith("https")) {
            inputStream = new URL(mUri.toString()).openStream();
        } else {
            inputStream = mContext.getContentResolver().openInputStream(mUri);
        }

        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);

        listener.onDecoded(bitmap);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

如何确保写入文件的图像与原始源图像的尺寸相同?

1 个答案:

答案 0 :(得分:2)

您已在代码中指定了样本大小,这将导致调整大小:

opts.inSampleSize = 16;

只需删除此行,输出图像的尺寸应相同。

关于inSampleSize的使用情况,根据official doc

  

例如,inSampleSize == 4返回的图像是1/4   原始的宽度/高度,以及像素数的1/16。任何价值   < = 1与1相同。