android - 解码位图返回 null

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

toast 表明 bm 为空。我将 f.getAbsolutePath() 更改为 f.getPath() 但结果是一样的。 Uri imgselect 和 String imgpath 有值。我不使用 SD 卡,我从图库中获取位图。

如何调整位图的大小?

谢谢。

最佳答案

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

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;
        }

关于android - 解码位图返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510831/

相关文章:

android - 选择将在哪个 android 设备(模拟器或手机)上运行 react-native run-android

android - 你会如何做智能手机BLE室内检测和定位?

在 C 中创建 BMP 文件(位图)

Android 内存不足错误与图像

image - AS3/AIR/Mobile - 将位图保存到文件

android - Android中的人脸检测?

android - 如何在android中的imageview中添加gif图像?

java - Android 2.1 和 HTC Desire : Is there a bluetooth problem?(CorruptedStreamException)

java - 将字节数组写入文件(大文件大小)

android - 位图处理时内存泄漏