setImageBitmap()不起作用

I'l*_*lio 3 android bitmap imageview

我有和ImageView,它应该填充来自Gallery的图像与此代码:

Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
            getIntent.setType("image/*");
            Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            pickIntent.setType("image/*");

            Intent chooserIntent = Intent.createChooser(getIntent, "Pick an image.");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

            startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);
Run Code Online (Sandbox Code Playgroud)

现在,在这部分代码中一切都很好,问题出在onActivityResult(),完全在setImageBitmap()中,因为imageView没有采用Gallery中的图像.这是来自onActivityResult()的代码:

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

    if(requestCode == PICK_IMAGE_REQUEST || resultCode == PromoUpload.RESULT_OK){

        Uri selectedImage = data.getData();
        String[] filepathColumm = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filepathColumm, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filepathColumm[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        imagePromo.setImageBitmap(bitmap);
        pictureFlag = 1;

    }
Run Code Online (Sandbox Code Playgroud)

我敬酒picturePath属性,它显示确定,问题就在这里:

Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
    imagePromo.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)

但我不知道我做错了什么.这是ImageView的XML:

<ImageView
        android:id="@+id/imageView_promo"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:padding="1dp" />
Run Code Online (Sandbox Code Playgroud)

我也试过从多种尺寸中选择图像,但它似乎不起作用......

Com*_*are 7

但我不知道我做错了什么

您假设每个Uri都来自MediaStore并且每个条目MediaStore都有一个有用的路径.两者都不是真的.

您应该做的是传递selectedImage到图像加载库(Glide,Picasso等),因为这些库不仅知道如何Uri正确使用它们,而且它们将在后台线程上进行图像加载,而不是冻结你正在这里做UI.您还可以教图像加载库以缩放图像以适合您的需要ImageView,以节省堆空间.

更直接地替换代码将是:

    Uri selectedImage = data.getData();
    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
    imagePromo.setImageBitmap(bitmap);
    pictureFlag = 1;
Run Code Online (Sandbox Code Playgroud)

但是,如上所述,这将在磁盘I/O和图像解码进行时冻结您的UI.