BitmapFactory.decodeFile() returns 在某些设备中为空

BitmapFactory.decodeFile() returns null in some devices

我正在使用 here 中的以下代码。我想压缩图像。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

int actualHeight = options.outHeight;
int actualWidth = options.outWidth;

从相机、图库和照片中选择图像后,我会根据 OS 类型和设备型号在不同设备中获得不同类型的路径。喜欢:

1) /storage/emulated/0/Android/data/...

2) /raw//storage/emulated/0/mb/1511172993547.jpg

3) /2/1/内容://media/external/images/media/11647/ORIGINAL/NONE/486073582

如果路径类似于第一个 url,则此代码运行良好。但是如果我得到其他类型的图像,那么 BitmapFactory.decodeFile() 会给出 null.

有没有办法在所有类型的设备和 OS 版本中压缩图像。

更新:

打开选择器:

Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent, 1001);

选择图片后:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri imgUri = Uri.fromFile(new File(data.getData().getPath()));
    Bitmap cmpBitmap = ImageUtils.compressUriQuality(OpenWallWeb.this, imgUri);
    dlgImageToPost.setImageBitmap(cmpBitmap);
...
}

用于压缩:

public static Bitmap compressUriQuality(Context mContext, Uri selectedImage) {
    InputStream imageStream = null;
    Bitmap bmp = null;
    try {
        imageStream = mContext.getContentResolver().openInputStream(
                selectedImage);
        bmp = BitmapFactory.decodeStream(imageStream);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 50, stream);

        if (imageStream != null)
            imageStream.close();
        stream.close();
        stream = null;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmp;
}

我遇到了同样的问题,请为您的应用添加存储权限。

查看此 link 了解更多信息

电视 2) /raw//storage/emulated/0/mb/1511172993547.jpg

如果用户从“图库”或“照片”中选择图片,您将不会获得该路径。当然,它不是可用于 .decodeFile() 的文件系统路径。你是怎么得到的?

3) /2/1/content://media/external/images/media/11647/ORIGINAL/NONE/486073582

这不是有效的内容方案路径。你是怎么得到的?当然不能用于 .decodeFile()。

  i'm getting different type of paths 

如果你'act normal',你永远不会得到这样的路径。那么你在做什么呢?基本 uri 处理错误?

using following code from here. 

正如您现在所看到的,对于很大一部分来说,这是非常肮脏的示例代码。

any way to compress image in all types of devices and OS versions.

当然可以。直接使用获取的selected uri即可。为它打开一个 InputStream 并使用 .decodeStream() 代替。

我的天..你没有直接使用uri。

 Bitmap cmpBitmap = ImageUtils.compressUriQuality(OpenWallWeb.this, imgUri);

改为

  Bitmap cmpBitmap = ImageUtils.compressUriQuality(OpenWallWeb.this, data.getData());