views:

212

answers:

1

If I've got a Silverlight Image control that downloads from a full URL, how can I get the size (in bytes) of the downloaded image without making another web call?

I can't find anything on the Image or the BitmapImage source behind it that would tell me. And even the DownloadProgress event on the BitmapImage only gives a percentage.

A: 

I never noticed it before, but that is kind of a strange gap in the framework...

You'll probably have to download the image by itself using a WebClient object. That'll give you a stream of bytes. You can check the length of the stream, and then create a bitmap from the stream.

Code to set up the web client and begin the download (note, it's an async call, so we assign an event handler to fire when it completes the download.)

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
Uri someImageUri = new Uri("http://www.somesite.com/someimage.jpg");
wc.OpenReadAsync(someImageUri);

Here's an example of what the event handler method might look like:

   void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        System.IO.Stream imageStream = e.Result;
        long imageSize = imageStream.Length;
        BitmapImage bi = new BitmapImage();
        bi.SetSource(imageStream);
        Image image = new Image();
        image.Source = bi;
    }

Obviously, if you already have an image control on your form, you wouldn't need to create a new one, or if you did want to create it, you'll have to add it to a parent panel of some kind...

~Chris

Chris Jaynes
You must be right. I was hoping it was just tucked away somewhere but I guess it's just not exposed.
RandomEngy
Trying to do this, but I'm getting a security exception when I try to grab an image from another domain. I think the Image control has special privileges to make that kind of web call.
RandomEngy
Gosh, now that I think about it, I've never used the WebClient to do cross-site calls in the Silverlight container before...<a href="http://blogs.interakting.co.uk/dominicz/archive/2008/11/17/securityexception-when-making-requests-to-websites-in-silverlight-2.0.aspx">Here's some info about that Exception</a>. There is an XML config file that you can set up on the client, but that probably wouldn't help.As he suggests, you should be able to write a simple service or ASP page that you could call that would just grab the image bits and write them to the response. Then call your own page.
Chris Jaynes