iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >android跳到系统相册选择图片并根据uri获取真实图片路径
  • 361
分享到

android跳到系统相册选择图片并根据uri获取真实图片路径

选择图片系统uriAndroid 2022-06-06 13:06:48 361人浏览 薄情痞子
摘要

1.首先跳转到系统相册选择图片 public void ChoosePicture(View view) { // 激活

1.首先跳转到系统相册选择图片
public void ChoosePicture(View view)
    {
        // 激活系统图库,选择一张图片
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 0);
    }
2.重载startActivityForResult函数,处理所选择的图片
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if( requestCode == 0)
        {
            if( data != null )
            {
                Bitmap bitmapLocal = null;
                Uri uri = data.getData(); //获取图片uri
                String imagePath = getRealPathFromURI(uri); // 根据URI找到图片真正的路径
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                bitmapLocal = BitmapFactory.decodeFile(imagePath, options); 
                this.image.setImageBitmap(bitmapLocal);
                this.bitmap = bitmapLocal;
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

其中,getRealPathFromURI函数将文件的uri转化为文件路径,具体代码如下:

private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        //不能直接调用contentprovider的接口函数,需要使用contentresolver对象,通过URI间接调用contentprovider
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

到这里我们就成功将获取到图片的文件路径啦。


作者:zhengxq27


--结束END--

本文标题: android跳到系统相册选择图片并根据uri获取真实图片路径

本文链接: https://www.lsjlt.com/news/29046.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作