Hannington Mambo
Hannington Mambo

Reputation: 1090

Read an image source from an image control

I am able to set the image source of a control as follows:

Dim photo As BitmapImage = New BitmapImage()
photo.SetSource(Application.GetResourceStream(New Uri("Assets/Photos/image.jpg", UriKind.Relative)).Stream)
Me.myImage.Source = photo

Now, how can I read the source url of the image that is displayed in the control? I am trying something like this:

Dim source as String = Me.myImage.Source.GetValue(???)

but I am getting errors of 'cannot be converted to system.windows.DependencyProperty'

Also, can the GetValue method give me the size of the image as well?

Thanks.

Upvotes: 0

Views: 1542

Answers (2)

Clemens
Clemens

Reputation: 128061

If you create your BitmapImages like

Dim photo As BitmapImage =
    New BitmapImage(New Uri("ms-appx:///Assets/Photos/image.jpg"))
myImage.Source = photo

you will later be able to get the URI back from the BitmapImage's UriSource property:

Dim bitmap As BitmapImage = myImage.Source
Dim uri As Uri = bitmap.UriSource

EDIT: Creating a BitmapImage as shown above is equivalent to

Dim photo As BitmapImage = New BitmapImage()
photo.UriSource = New Uri("ms-appx:///Assets/Photos/image.jpg")

The effect is that the UriSource property is set, and can later be read back. Calling BitmapImage.SetSource, as you did in your question, will not set UriSource. That's why it always returned null.

Upvotes: 1

Rob Caplan - MSFT
Rob Caplan - MSFT

Reputation: 21899

The Image.Source here is the BitmapImage (if you didn't know you just set it to one it could be other ImageSource types as well). You can retrieve that and then check its UriSource property to get the Uri and from that the OriginalString:

Dim bmp As BitmapImage = myImage.Source
Dim uriSource As Uri = bmp.UriSource
Dim source As String = uriSource.OriginalString

System.Diagnostics.Debug.WriteLine("Source is {0}", source)

In a non-contrived example you'll probably want to put this in a try/catch block or add other checks to handle the cases where the myImage.Source isn't a BitmapImage or where the BitmapImage isn't loaded from a URI.

Upvotes: 0

Related Questions