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

时间:2016-05-31 15:28:22

标签: java android image crash size

我为我的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);
            }
    }

然而,它不会在模拟器中崩溃,但它会在每部手机上崩溃。所以我找不到错误代码,因为它没有打印在log cat中。

3 个答案:

答案 0 :(得分:1)

位图大小太大会导致崩溃错误。我的解决方案是:

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

希望它可以帮到你。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试将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()方法;