【WPF】wpf image控件加载网络图片不显示问题,
1、加载网络图片到内存system.drawing.image对象中
2、内存中的image 转Bitmap 再转适合system.windows.controls.image 的BitmapImage类型
为什么:网络延迟,得不到实时的图片信息
string userHeadPic = "http://123.56.178.100/headpic/7.jpg"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userHeadPic); WebResponse response = request.GetResponse(); System.Drawing.Image img = System.Drawing.Image.FromStream(response.GetResponseStream()); Bitmap bitMap = new Bitmap(img); BitmapImage bitUserLogo = BitmapToBitmapImage(bitMap); SchoolPubData.UserInfo.imgHead.Source = bitUserLogo; SchoolPubData.MainForm.ToSchoolSwitchPage();
public BitmapImage BitmapToBitmapImage(Bitmap bitmap) { Bitmap bitmapSource = new Bitmap(bitmap.Width, bitmap.Height); int i, j; for (i = 0; i < bitmap.Width; i++) for (j = 0; j < bitmap.Height; j++) { System.Drawing.Color pixelColor = bitmap.GetPixel(i, j); System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B); bitmapSource.SetPixel(i, j, newColor); } MemoryStream ms = new MemoryStream(); bitmapSource.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream(ms.ToArray()); bitmapImage.EndInit(); return bitmapImage; }