意图从图库中获取图像

意图从图库中获取图像

本文介绍了意图从图库中获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用share命令从图库中获取图像.

I want to get a image from Gallery with the share command.

我当前的代码是:

Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        Log.d("Test","Simple SEND");
        Uri imageUri = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if (imageUri != null) {
            InputStream iStream = getContentResolver().openInputStream(imageUri);
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        Log.d("Test", "Multiple SEND");
    }

imageUri的值为:content://media/external/images/media/37

The value of the imageUri is: content://media/external/images/media/37

但是函数"openInputStream"会引发错误"java.io.FileNotFoundException".

But the function "openInputStream" throws the error "java.io.FileNotFoundException".

使用以下功能,我可以获得图像的真实路径.

With the following function i get the real path of the image.

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

但是我不知道如何将其转换为位图.

But i don't know how to convert it to a bitmap.

推荐答案

Uri不是File. new File(imageUri.toString())总是错误的. imageUri.getPath()仅在Uri的方案为file时有效,并且在您的情况下,方案可能为content.

A Uri is not a File. new File(imageUri.toString()) is always wrong. imageUri.getPath() only works if the scheme of the Uri is file, and in your case, the scheme is probably content.

使用ContentResolveropenInputStream()Uri标识的文件或内容上获取InputStream.然后,将该流传递到BitmapFactory.decodeStream().

Use ContentResolver and openInputStream() to get an InputStream on the file or content identified by the Uri. Then, pass that stream to BitmapFactory.decodeStream().

另外,请在后台线程上解码位图,以免在进行此工作时不冻结UI.

Also, please decode bitmaps on a background thread, so that you do not freeze your UI while this work is going on.

这篇关于意图从图库中获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:36