如何从图片路径获取资源ID?

3

我在 Android 中有一个图片路径。这个图片存在于设备的 SD 卡上。我该如何找到它的资源 ID?我需要将其发送给 decodeResource 函数。我正在尝试检测用户从画廊中选择的图像上的面部。我编写的代码如下:

    Intent intent = new Intent(this, DetectFaces.class);
    intent.putExtra(PICTURE_PATH,picturePath);//the path of the image
    startActivity(intent);

在detectFaces类中
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detect_faces);
       // getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        picturePath = intent.getStringExtra(GetFaceActivity.PICTURE_PATH);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        //imageView.setOnTouchListener(this);

    } 

有一个按钮,其onClick事件与

public void DetectFacesInImage(View view)
{
    BitmapFactory.Options bitmapFactoryOptions=new BitmapFactory.Options();
    bitmapFactoryOptions.inPreferredConfig= Bitmap.Config.RGB_565;
myBitmap=BitmapFactory.decodeResource(getResources(),R.drawable.faceswapping,bitmapFactoryOptions);
    int width=myBitmap.getWidth();
    int height=myBitmap.getHeight();
    detectedFaces=new FaceDetector.Face[number_of_faces];
    FaceDetector faceDetector=new FaceDetector(width,height,number_of_faces);
    number_of_faces_detected = faceDetector.findFaces(myBitmap, detectedFaces);

 }

我需要在decodeResource函数中使用ID。有什么提示吗?
2个回答

2

试试这个,可能会对你有帮助

File fileObj = new  File(“/sdcard/Images/test_image.jpg”);
if(fileObj .exists()){
    Bitmap bitMapObj= BitmapFactory.decodeFile(fileObj .getAbsolutePath());
    ImageView imgView= (ImageView) findViewById(R.id.imageviewTest);
    imgView.setImageBitmap(bitMapObj);
}

但是你在哪里找到图像的resourceID呢? - Ankuj
2
你不需要资源ID来解码文件。只有当这个特定的图像在你的资源文件夹中时,你才需要资源ID。但是你提到这个图像可用于SD卡上。你不会为任何不在你的apk中的东西获得资源ID。 - Durairaj Packirisamy
Durairaj P,你应该将你的评论编辑为答案,因为我认为这就是他想要做的。 - Raz

-1
如果您想解码图像,需要通过使用媒体存储的查询来获取文件路径。您可以使用类似以下的代码:
public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);


    }

我已经有了imagePath,但现在我需要使用decodeResource()函数,它需要resID作为参数,因此我想从imagePath中找到它。 - Ankuj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接