Android从图库获取图片
创始人
2024-10-06 21:01:35
0

以下是一个简单的示例代码,用于从图库获取图片并显示在Android应用程序中:

首先,在你的AndroidManifest.xml文件中,添加以下权限:


然后,在你的Activity或Fragment中,添加以下代码:

// 在Activity或Fragment中定义一个常量,用于请求图库
private static final int REQUEST_PICK_IMAGE = 1;

// 在合适的地方调用以下代码,启动图库:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_IMAGE);

// 在Activity或Fragment中重写onActivityResult方法,获取从图库返回的结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String imagePath = cursor.getString(columnIndex);
            cursor.close();

            // 在这里做你想要的操作,比如显示图片
            ImageView imageView = findViewById(R.id.imageView);
            imageView.setImageURI(selectedImage);
        }
    }
}

以上代码将启动图库,用户选择一张图片后,返回图片的URI,并将其显示在ImageView中。你可以根据自己的需求进行修改和扩展。

相关内容

热门资讯

玩家必备科技!pokemmo脚... 1、玩家必备科技!pokemmo脚本辅助器下载,aapoker脚本怎么用,攻略方法(有挂攻略);详细...
分享实测!wepoker正确养... 分享实测!wepoker正确养号方法,wepoker有用吗,我来教教你(有挂辅助);1分钟了解详细教...
揭秘攻略!哈糖大菠萝能开挂吗,... 揭秘攻略!哈糖大菠萝能开挂吗,wepoker好友房开挂,透明挂教程(有挂教程);科技安装教程;136...
程序员教你!德州局HHpoke... 程序员教你!德州局HHpoker透视脚本,wepoker透视脚本网页,必备教程(有挂辅助)是一款可以...
玩家攻略推荐!poker wo... 玩家攻略推荐!poker world辅助,hhpkoer辅助挂是真的吗,必赢方法(有挂教程);原来确...
交流学习经验!aapoker透... 1、交流学习经验!aapoker透视脚本入口,fishpoker透视底牌,科技教程(有挂软件)。2、...
技术分享!pokemmo手机辅... 技术分享!pokemmo手机辅助软件,hhpoker有没有外挂,攻略教程(有挂技巧);建议优先通过p...
玩家必看教程!wepoker免... 玩家必看教程!wepoker免费脚本,德州hhpoker是真的吗,技巧教程(有挂软件);德州hhpo...
记者揭秘!wpk官网下载链接,... 记者揭秘!wpk官网下载链接,wepoker怎么拿到好牌,解密教程(有挂辅助)是由北京得wepoke...
热门推荐!wepoker透视脚... 热门推荐!wepoker透视脚本网页,wpk插件辅助,教你攻略(有挂教程);建议优先通过wepoke...