最近需要做一個方法,將比較大的圖片轉換爲較小的圖片。
/// <summary> /// 獲得原始圖片地址,並且壓縮 /// </summary> /// <param name="url"></param> /// <param name="newWidth"></param> /// <returns></returns> private byte[] getResizedImage(String url, int newWidth) { Bitmap bmpOut = null; System.IO.MemoryStream outStream = new System.IO.MemoryStream(); using (Image inputImage = LoadImageFromURL(url)) { if (inputImage != null) { ImageFormat format = inputImage.RawFormat; decimal ratio; //ratio old width:new width int newHeight = 0; //*** If the image is smaller than a thumbnail just return it if (inputImage.Width < newWidth) return null; ratio = (decimal)newWidth / inputImage.Width; decimal h = inputImage.Height * ratio; newHeight = (int)h; bmpOut = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight); g.DrawImage(inputImage, 0, 0, newWidth, newHeight); bmpOut.Save(outStream, format); } else return null; } return outStream.ToArray(); } private Image LoadImageFromURL(string url) { HttpWebRequest request = (HttpWebRequest)System.Net.HttpWebRequest.Create(url); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Image img = Bitmap.FromStream(response.GetResponseStream()); response.Close(); return img; } catch (Exception e) { return null; } }
然後是調用
/// <summary> /// 返回壓縮圖片的虛擬路徑 /// </summary> /// <param name="url">要壓縮的圖片路徑</param> /// <returns></returns> public string GetThumbImg(string url) { int newWidth = 200; //定義新寬度 string savedImage = "~/images/1.jpg"; //文件虛擬路徑 //獲取壓縮後圖片二進制數據 byte[] bytes = getResizedImage(url, newWidth); if (bytes != null) { File.WriteAllBytes(Server.MapPath(savedImage), bytes);//創建縮略圖 } return savedImage; }