如何从android中的画廊获取地址

时间:2016-07-14 15:17:20

标签: android inputstream image-gallery

我编写了这段代码,我的代码从图库中选择一张图片并从中获取数据,但我不知道如何从Inputstrem或数据中获取图像地址并存储它?

public void loadPic()
{
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, 1);
}

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

    if(requestCode==1)
    {
        try {
            Uri selectedImage=data.getData();
            InputStream inputStream = getContentResolver().openInputStream(selectedImage);
            listItems.add(inputStream.toString());
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }
    }
}

3 个答案:

答案 0 :(得分:2)

如下所示读取文件名,请相应地使用它。

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            File f = new File(picturePath);
            String imageName = f.getName();

答案 1 :(得分:1)

有时,您无法从您选择的图片中获取文件。 这是因为选择的人来自Google+,云端硬盘,Dropbox或任何其他提供商。

最佳解决方案是让系统通过Intent.ACTION_GET_CONTENT选择内容,并通过内容提供商获取结果。

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...
    }
}

答案 2 :(得分:0)

我不确定这是不是你想要的,但你可以得到这样的图像:

Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);

获得位图后,您可以看到here如何存储它。

编辑:试试这个

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

取自here