代码如下:

Code Behind
 1 void MainWindow_Loaded(object sender, RoutedEventArgs e)
2 {
3 string imgURL = "http://www.***.com/***.jpg";
4 if (!String.IsNullOrEmpty(imgURL))
5 {
6 Application.Current.Dispatcher.BeginInvoke(new Action(() =>
7 {
8 //return byte[].
9 byte[] content = this.GetImageContent(imgURL);
10
11 //return bitmap source.
12 BitmapSource bitmapSource = ConvertToImage(content);
13
14 this.MyImg.Source = bitmapSource;
15 }), DispatcherPriority.Background);
16 }
17 }
18
19 #region GetImage
20
21 private byte[] GetImageContent(string imgURL)
22 {
23 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgURL);
24 request.AllowAutoRedirect = true;
25
26 WebProxy proxy = new WebProxy();
27 proxy.BypassProxyOnLocal = true;
28 proxy.UseDefaultCredentials = true;
29 request.Proxy = proxy;
30
31 WebResponse response = request.GetResponse();
32
33 using (Stream stream = response.GetResponseStream())
34 {
35 using (MemoryStream memoryStream = new MemoryStream())
36 {
37 Byte[] buffer = new Byte[1024];
38 int current = 0;
39 while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
40 {
41 memoryStream.Write(buffer, 0, current);
42 }
43 return memoryStream.ToArray();
44 }
45 }
46 }
47
48 private BitmapSource ConvertToImage(byte[] content)
49 {
50 using (MemoryStream memoryStream = new MemoryStream(content))
51 {
52 Bitmap bitmap = new Bitmap(memoryStream);
53 IntPtr bmpPt = bitmap.GetHbitmap();
54 BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
55 bmpPt,
56 IntPtr.Zero,
57 Int32Rect.Empty,
58 BitmapSizeOptions.FromEmptyOptions());
59 return bitmapSource;
60 }
61 }
62
63 #endregion



posted on 2011-12-07 17:57  Damon-Cui  阅读(849)  评论(0编辑  收藏  举报