繁体   English   中英

如何打开图库选择图像?

[英]How to open Gallery to pick an image?

我正在寻找一种打开onClick画廊以选择图片的方法。 我想在图片的列表视图中使用该本地“已上传”图片。 有人可以帮我解释一下该怎么做。 我是Android开发的初学者。

public void pickImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
        if (data == null) {
            //Display an error
            return;
        }
        InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
        //Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
    }
}

这是我在应用程序中使用的代码

Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, PICKIMAGE_REQUESTCODE);

而在onActivity结果方法

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

            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == PICKIMAGE_REQUESTCODE) {
                if (resultCode == RESULT_OK) {
                    Uri imageUri = data.getData();
                    InputStream inputStream = null;


                    try {
                        inputStream = getContentResolver().openInputStream(imageUri);
                       bitmap = BitmapFactory.decodeStream(inputStream);
                    } 
                   catch (FileNotFoundException e) 
                     {
                        e.printStackTrace();
                    } finally {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onActivityResult: error closing InputStream during reading image from the phone external storage");
                        }

                    }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM