一、从网络中获取图片信息:
1 /// <summary> 2 /// 获取图片 3 /// </summary> 4 /// <param name="url">Url</param> 5 /// <returns>BitmapImage</returns> 6 public BitmapImage GetImage(string url) 7 { 8 BitmapImage image=null; 9 try 10 { 11 image = new BitmapImage(); 12 long fileLength = 0; 13 //从url指定的网络地址获取图片信息 14 WebRequest webReq = WebRequest.Create(url); 15 WebResponse webRes = webReq.GetResponse(); 16 fileLength = webRes.ContentLength; 17 Stream srm = webRes.GetResponseStream(); 18 byte[] bufferbyte = new byte[fileLength]; 19 int allByte = (int) bufferbyte.Length; 20 int startByte = 0; 21 while (fileLength > 0) 22 { 23 int downByte = srm.Read(bufferbyte, startByte, allByte); 24 if (downByte == 0) 25 { 26 break; 27 } 28 startByte += downByte; 29 allByte -= downByte; 30 } 31 //以流的形式初始化图片 32 image.BeginInit(); 33 image.StreamSource = new MemoryStream(bufferbyte); 34 image.EndInit(); 35 srm.Close(); 36 webRes.Close(); 37 } 38 catch (Exception) 39 { 40 Console.WriteLine("获取图片信息失败"); 41 } 42 return image; 43 }
二、在Image控件中显示获取到的图片
1 public void ShowImage(BitmapImage img) 2 { 3 image.Source = img; 4 image.Width = img.PixelWidth; 5 image.Height = img.PixelHeight; 6 }
image是Image控件
三、保存Image到磁盘
1 /// <summary> 2 /// 保存图片到磁盘 3 /// </summary> 4 /// <param name="img"></param> 5 public void SaveImage(Image img) 6 { 7 //img为Image控件 8 BitmapSource bsrc = (BitmapSource)img.Source; 9 //保存文件对话框 10 SaveFileDialog sf = new SaveFileDialog(); 11 //设定默认保存类型为Png 12 sf.DefaultExt = ".png"; 13 //指定用户只能下载jpg和png格式的图片 14 sf.Filter = "JPG 图片 (*.jpg)|*.jpg|PNG 图片 (*.png)|*.png"; 15 if (sf.ShowDialog() == true) 16 { 17 PngBitmapEncoder pngE = new PngBitmapEncoder(); 18 pngE.Frames.Add(BitmapFrame.Create(bsrc)); 19 using (Stream stream = File.Create(sf.FileName)) 20 { 21 pngE.Save(stream); 22 } 23 } 24 }
时间: 2024-10-05 02:48:10