从图库中选择图像时,应用程序崩溃

时间:2019-03-29 13:48:58

标签: android kotlin bitmap

我需要从图库中进行选择,以对其实施过滤器。 我使用以下代码在应用中打开图库:

 var intent = Intent(Intent.ACTION_PICK)
                    intent.setType("image/*")
                    startActivityForResult(intent, PERMISSION_CODE)

活动结果:

 if (resultCode == Activity.RESULT_OK && requestCode == PERMISSION_CODE) {
            var bitmap: Bitmap = BitmapUtils.getBitmapFromGallery(this, data?.data, 800, 800)
            original_filter_bitmap.recycle()
            final_bitmap.recycle()
            filtered_bitmap.recycle()
            original_filter_bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
            final_bitmap = original_filter_bitmap.copy(Bitmap.Config.ARGB_8888, true)
            filtered_bitmap = original_filter_bitmap.copy(Bitmap.Config.ARGB_8888, true)
            image_preview.setImageBitmap(original_filter_bitmap)
            bitmap.recycle()
         //   imageFiltersFragment.displayThumbNail(original_filter_bitmap)
        }

这里是从图库方法的位图获取的

(Context context, Uri uri, int width, int height) {
        String[] filepathcolumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, filepathcolumn, null, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filepathcolumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(picturePath, options);
        options.inSampleSize = calculateInSampleSize(options, width, height);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(picturePath, options);
    }

因此,图库会打开,我选择图像,然后按图像应用会崩溃。

Logcat:

Caused by: java.lang.IllegalStateException: BitmapUtils.getBitmapFro…is, data?.data, 800, 800) must not be null
        at com.example.sg772.textonimage.MainActivity.onActivityResult(MainActivity.kt:191)

第191行:var bitmap: Bitmap = BitmapUtils.getBitmapFromGallery(this, data?.data, 800, 800)

1 个答案:

答案 0 :(得分:1)

data?.data可能为空。

data?.data?.let {
    val bitmap = BitmapUtils.getBitmapFromGallery(this, it, 800, 800)
    ...
}