android - 防止位图被写入磁盘被缩放

标签 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();
    }
}

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

最佳答案

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

opts.inSampleSize = 16;

去掉这条线,输出图像的尺寸应该是一样的。

关于inSampleSize的使用,根据official doc :

For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1.

关于android - 防止位图被写入磁盘被缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21922897/

相关文章:

android - 自签名 ssl 证书在部署到 Android 时不会被阻止

java - FileProvider.getUriForFile 返回空对象引用

c++ - 如何将这个新的 char** 写入 .bmp 文件?

使用 FileOutputStream 使用进度条下载 Android ION

android - 旋转屏幕时丢失数据

java - Picasso/Glide 仅从 youtube 搜索结果中加载 6 个缩略图

c++ - CreateDibSection 在磁盘上而不是物理内存上

Python ctype 帮助 : working with C unsigned char pointers

java - 使用 OkHTTP 客户端下载二进制文件已损坏

android - 将数据库从 Assets 复制到设备数据文件夹时出现 FileNotFoundException