解码位图会返回null

时间:2013-08-29 12:19:03

标签: android bitmap

我正在尝试解码位图,但该函数返回null,我不知道为什么。

代码:

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if(requestCode == SELECT_FOTO) 
{
  Uri imgselect = data.getData();
  String imgpath = imgselect.getPath();
  File f = new File (imgpath);
  Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
  Toast.makeText(Insertarlugar.this, "Bitmap es" + bm, Toast.LENGTH_LONG).show();
}

吐司指示我bm为空。我为f.getPath()更改了f.getAbsolutePath(),但结果是一样的。 Uri imgselect和String imgpath都有值。我不使用SD卡,而是从图库中获取位图。

如何调整位图大小?

感谢。

2 个答案:

答案 0 :(得分:3)

尝试这个并在imagepath不为空之前检查

Uri imgselect = data.getData();
String imgpath = imgselect.getPath();
if(imgpath !=null)
{
  Bitmap bm = BitmapFactory.decodeFile(imgpath);
}

如果图像有大而无法解码图像路径,那么你试试这个并给出宽度和高度为60和60

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
            int reqHeight) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        return bmp;
        }

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
             }
         }
         return inSampleSize;
        }

答案 1 :(得分:0)

无需使用实际文件,因为您指的是内容提供商(将为您执行此操作)

Uri imgselect = data.getData();
Bitmap bm = BitmapFactory.decodeFile(imgselect.getPath());

无法检查它是否有效,您可能需要先解码Uri。