Getting the size of a downloaded image in Silverlight
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.开发者_如何学编程
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
精彩评论