无法从图库中导入正常大小的图像

Can't import normal sized images from gallery

我为我的 android 应用创建了一个功能,允许用户浏览和导入图库中的图像。但是当导入正常或更大尺寸的图像时,应用程序总是崩溃,但当我导入非常小的图像时它不会崩溃。我希望用户能够轻松快速地导入正常大小的图像。这是我的代码:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_in_card);
    openGallery();
}

private void openGallery () {
        Intent intent = new Intent();
        // Show only images, no videos or anything else
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        // Always show the chooser (if there are multiple options available)
        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.str_select_pic_gallery)), PICK_IMAGE_REQUEST);
    }


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                setPicture(bitmap);
                // Log.d(TAG, String.valueOf(bitmap));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

@TargetApi(android.os.Build.VERSION_CODES.JELLY_BEAN)
private void setPicture (Bitmap b) {
            BitmapDrawable drawable;
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                drawable = new BitmapDrawable(getResources(), b);
                wholeImage.setBackgroundDrawable(drawable);
            } else {
                drawable = new BitmapDrawable(getResources(), b);
                wholeImage.setBackground(drawable);
            }
    }

但是它不会在模拟器中崩溃,但它会在每个 phone 上崩溃。所以我找不到错误代码,因为它没有打印在日志中 cat.

您可以使用 BitmapFactory。它的选项可用于位图大小

尝试将 openGallery() 方法与 :

交换
public void openGallery(View view) {
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}

...删除onCreate()中的openGallery()方法;

位图太大会导致崩溃error.My解决方案是:

ContentResolver resolver = getContentResolver();
BitmapFactory.Options options = new  BitmapFactory.options();
options.inJustDecodeBounds = false;
options.inSampleSize = 4; // now you resize bitmap as 0.25 as before
Bitmap mBitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(mPhotoUri),null,options);

希望对您有所帮助