安卓:如何将从图库选择的照片设置为位图(bitmap)

10

在这里,我通过代码作为监听器要求用户访问相册:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);

然而,我不太清楚如何将一个变量设置为所选择的照片。

我应该在哪里放置代码以将变量设置为所选的照片呢?

谢谢 :)


你能获取到图片路径吗? - Heshan Sandeepa
4个回答

20

首先,您需要覆盖onActivityResult方法以获取所选图像文件的URI。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == SELECT_PHOTO) {

        if (resultCode == RESULT_OK) {
            if (intent != null) {
                // Get the URI of the selected file
                final Uri uri = intent.getData();
                useImage(uri);                   
              }
        }
       super.onActivityResult(requestCode, resultCode, intent);

    }
}

然后定义 useImage(Uri) 来使用图片

void useImage(Uri uri)
{
 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
 //use the bitmap as you like
 imageView.setImageBitmap(bitmap);
}

你最好在onActivityResult的if语句中检查requestCode。 - Emad Razavi
我得到的位图为空。当我调试它时,我的位图输出为 - 位图 =“”。采用相同的方法。这是什么原因? - Priyavrat Talyan

13

你可以这样做。

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

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

         // Do something with the bitmap


        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
}

但是我应该把它放在哪里呢?只放在onCreate中还是应该放在选择按钮的监听器中? - Kinoscorpia
如果我想保存所创建的位图,我可以在类的开头创建一个名为bitmap的变量,然后只需说“bitmap = BitmapFactory.decodeFile(imagePath,options);”吗? - Kinoscorpia
另外,感谢您的澄清和帮助 :) - Kinoscorpia
我不确定我理解你的评论问题。但是从图库返回的图像已经保存,这就是为什么你会得到指向该图像的路径。如果需要,您可以直接复制文件。但将其读入位图可能更有用...这取决于您想要做什么。 - Bojan Kseneman
我得到的imagePath为空,因此应用上述方法后我的位图也为空。这是什么原因呢? - Priyavrat Talyan

3

Akash Kurian Jose答案的替代方案

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

我经常使用
fun getBitmap(file: Uri, cr: ContentResolver): Bitmap?{
            var bitmap: Bitmap ?= null
            try {
                val inputStream = cr.openInputStream(file)
                bitmap = BitmapFactory.decodeStream(inputStream)
                // close stream
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }catch (e: FileNotFoundException){}
            return bitmap
        }

它不仅适用于来自图库的照片,也适用于来自相机的照片。

关于它的更大问题:Picasso无法显示来自图库的图片

使用此方法打开图库:

private void openGallery(){
    if (Build.VERSION.SDK_INT <19){
        Intent intent = new Intent(); 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
    } else {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
    }
}

然后您可以使用上述提到的 ContentResolver.openInputStream 方法将 Uri 转换为 Bitmap,或者使用 ImageView.setImageUri(Uri) 方法来设置图像。


2

如果您想将所选图像显示到特定的ImageView上。 假设我们有RC_PHOTO_PICKER = 1,那么这些代码应该可以实现

private void openPhotoPicker() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
    startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), RC_PHOTO_PICKER);
}

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

    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK && data != null) {
        Uri pickedImage = data.getData();
        //set the selected image to ImageView
        mImageView.setImageURI(pickedImage);
    }
}

然后只需调用openPhotoPicker()方法即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接