【问题标题】:How to save a selected Uri pic to drawable?如何将选定的 Uri 图片保存到可绘制对象?
【发布时间】:2015-04-13 09:40:56
【问题描述】:

我正在尝试通过使用 Uri 将用户从他们的图库中选择的图片设置为应用程序的背景,但我无法完全弄清楚。我尝试做的一件事是直接将背景设置为 uri,但它无法解决兼容性不匹配问题。我该如何做到这一点,无论是通过编程设置可绘制对象还是其他方式?

这是我尝试过的

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

    super.onActivityResult(requestCode, resultCode, intent);
    if (requestCode == 1) {

        if (intent != null && resultCode == RESULT_OK) {

            Uri selectedImage = intent.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 filePath = cursor.getString(columnIndex);
            cursor.close();

            if (bmp != null && !bmp.isRecycled()) {
                bmp = null;
            }

            bmp = BitmapFactory.decodeFile(filePath);
            imageView.setBackground(selectedImage);//error here

            //imageView.setBackgroundResource(0);//originally this, but this crashes also
            imageView.setImageBitmap(bmp);

        }
    }
}

【问题讨论】:

    标签: android uri background-image drawable image-gallery


    【解决方案1】:

    查看此链接Retrieve drawable resource from Uri

         try {
                InputStream inputStream = getContentResolver().openInputStream(yourUri);
                yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
                imageView.setImageDrawable(yourDrawable);
            } catch (FileNotFoundException e) {
                yourDrawable = getResources().getDrawable(R.drawable.default_image);
            }
    

    【讨论】:

    • 编辑:谢谢,但它仍然崩溃;这就是我现在在尝试声明中的内容: InputStream inputStream = getContentResolver().openInputStream(selectedImage); Drawable UploadPic = Drawable.createFromStream(inputStream, selectedImage.toString()); imageView.setImageDrawable(uploadedPic);
    • 不要忘记这一行: finally { try { if (inputStream != null) { inputStream.close(); } } 捕捉(忽略异常){} }
    猜你喜欢
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    相关资源
    最近更新 更多