From url to file
底下的程式碼, 可以將網路上的圖片直接轉成Thumb並儲存在硬碟檔案中.
請注意, 不要使用 BitmapImage bmp=new BitmapImage(new Uri(n, UriKind.RelativeOrAbsolute))); 因這種方法還需等待下載時間完成後才能存檔. 需加入 bmp.DownloadCompleted += new EventHandler(Image_DownloadCompleted);
但因為下一張圖片立即執行, 致使上一張的DownloadCompleted通常不會發生, 非常難控制
private void btn_Click(object sender, RoutedEventArgs e) { new Thread(() => { int length; byte[] data=new byte[1024]; WebRequest request; WebResonse response; Stream webStream; for (int i = 0; i < s.Length; i++) { try { string url = s[i]; request = WebRequest.Create(url); response = request.GetResponse(); webStream = response.GetResponseStream(); memoryStream = new MemoryStream(); while ((length = webStream.Read(data, 0, data.Length)) > 0) { memoryStream.Write(data, 0, length); } memoryStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = memoryStream; bitmap.DecodePixelWidth = 200; bitmap.EndInit(); bitmap.Freeze(); encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (fileStream = new System.IO.FileStream(string.Format("d:/tmp/t{0}_near.jpg", pcount++), FileMode.Create)) { encoder.Save(fileStream); } } catch (Exception ex) { Console.WriteLine("無此網址 or 照片"); } } }).Start(); }