【问题标题】:How to get path from image on drawable folder and set as image view, Bitmap?如何从可绘制文件夹中的图像获取路径并设置为图像视图、位图?
【发布时间】:2025-12-17 11:10:01
【问题描述】:

我的可绘制文件夹中已经有一些来自 android 项目的图片。

我创建了一些对象(代理),然后我需要使用我保存在数据库中的这张图片来设置imageView

所以,我将图片保存为String photoPath

Uri path1 = Uri.parse("android.resource://"+BuildConfig.APPLICATION_ID+"/" + R.drawable.agent1);
        String photoAg1 = path1.getPath();
ag1.setPhotoPath(photoAg1);

(我已经尝试过 path1.toString。)

好的,在此之前没有问题。 此对象显示在 listViewImageView

为了展示它,我正在做:

    ImageView photo = (ImageView) view.findViewById(R.id.list_cell_photo);
System.out.println(agent.getPhotoPath());                    
Bitmap bitmap = BitmapFactory.decodeFile(agent.getPhotoPath());
                    Bitmap lowdefbitmap = Bitmap.createScaledBitmap(bitmap,300,300,true);

                    photo.setImageBitmap(lowdefbitmap);

问题出在createScaledBitmap。 上面的错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                   at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:714)

System.out.println返回:/2131099732 如果我输入path1.toString,则返回:android.resource://com.aa.xlambton/2131099732

我已经看过了: Create a Bitmap/Drawable from file path

Android get image path from drawable as string

Get absolute path of android drawable image

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException even when file IS actually there

我认为我保存此路径错误,因为Bitmap 无法解码文件,因此createdScaledBitmap 将变为空。

有人可以帮帮我吗?

【问题讨论】:

  • 你想将drawable转换为位图吗?你为什么需要它?只需简单地将可绘制对象设置为图像资源
  • 这个link的可能重复

标签: android image bitmap path android-drawable


【解决方案1】:

在我的项目中,我想从项目文件夹中获取一些图像。所以有一种方法可以在 java 类中获取图像,但是在 .xml 文件中很简单。这显然是由 android 中的 assets Manger 完成的。 Follow this link
注意: AssetManager assetManager = getAssets(); 必须在 youractvity.java 文件中。

【讨论】:

  • 需要位格式
【解决方案2】:

这样试试

public int getImage(String imageName) {

    int drawableResourceId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());

    return drawableResourceId;
}

【讨论】:

    【解决方案3】:

    您可以将 Reference Id R.drawable.img_name 保存为整数而不是保存路径。

    当您需要操作此可绘制对象时,您可以使用该 id 而不是 R.drawable.img_name

    如果您需要此可绘制的位图,请关注this

    Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                           saved_id);
    

    【讨论】:

    • 我还有新的代理,我需要保存用户拍摄的照片,我可以从拍摄的照片中获得参考吗?
    • 没有。在这种情况下,您需要有图像路径。
    【解决方案4】:

    你可以试试这个方法:

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.youResourceId);
    

    【讨论】:

      最近更新 更多