getting an image path from a imageview?

2019-07-27 06:45发布

I have an ImageView and I want get the path of image and add in a String. I want do this because I need send this to my webservice like a default image

How can I do it ?

ImageView

<ImageView
    android:id="@+id/ivPerfil"
    android:padding="5dp"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:src="@drawable/icon_usuario"
    android:scaleType="fitXY"
    />

Getting the path

ivPerfil = (ImageView)findViewById(R.id.ivPerfil);
Drawable img = getResources().getDrawable(R.drawable.icon_usuario);
String pathImage = img.toString();

2条回答
男人必须洒脱
2楼-- · 2019-07-27 07:23

You can't directly get the path to the image referenced by the ImageView, but there is a bit of a way around it.

Since you clearly know the path to the image when setting it (since you wouldn't be able to set it without knowing it), you have the option to set the View's tag (which can technically be any Object).

In this case, it's just a String you're going to want to store.

So let's say you have:

Uri imageFilePath = Uri.parse("some/path/to/file.png");

Now, when setting the image Uri on the ImageView, add this after to set its tag:

imageView.setTag(imageFilePath.toString());

Then, when you're actually going to send it to the server, just call the getTag() method on your ImageView and you'll get the correct file location.

e.g.

String path = imageView.getTag().toString();

If the image is from your assets, though, you're going to have to construct the appropriate path from the resources (see miselking's answer on this page for how to do that).

查看更多
我命由我不由天
3楼-- · 2019-07-27 07:28

You can try this:

    Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.icon_usuario);
    String imgPath = path.toString();

"your.package.name" is the name of your package (i.e: com.example.mypackage)

You can use this path in android like this:

ivPerfil = (ImageView)findViewById(R.id.ivPerfil);
ivPerfil.setImageURI(path);
查看更多
登录 后发表回答