/// <summary>/// 制作遠程縮略圖/// </summary>/// <param name="url">圖片URL</param>/// <param name="newFileName">新圖路徑</param>/// <param name="maxWidth">最大寬度</param>/// <param name="maxHeight">最大高度</param>public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight){ Stream stream = GetRemoteImage(url); if(stream == null) return; Image original = Image.FromStream(stream); stream.Close(); MakeThumbnailImage(original, newFileName, maxWidth, maxHeight);}
/// <summary>/// 獲取圖片流/// </summary>/// <param name="url">圖片URL</param>/// <returns></returns>private static Stream GetRemoteImage(string url){ HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; request.ContentLength = 0; request.Timeout = 20000; HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); return response.GetResponseStream(); } catch { return null; }}
/// <summary>/// 制作縮略圖/// </summary>/// <param name="original">圖片物件</param>/// <param name="newFileName">新圖路徑</param>/// <param name="maxWidth">最大寬度</param>/// <param name="maxHeight">最大高度</param>public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight){ Size _newSize = ResizeImage(original.Width,original.Height,maxWidth, maxHeight); using (Image displayImage = new Bitmap(original, _newSize)) { try { displayImage.Save(newFileName, original.RawFormat); } finally { original.Dispose(); } }}
/// <summary>/// 計算新尺寸/// </summary>/// <param name="width">原始寬度</param>/// <param name="height">原始高度</param>/// <param name="maxWidth">最大新寬度</param>/// <param name="maxHeight">最大新高度</param>/// <returns></returns>private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight){ if (maxWidth <= 0) maxWidth = width; if (maxHeight <= 0) maxHeight = height; decimal MAX_WIDTH = (decimal)maxWidth; decimal MAX_HEIGHT = (decimal)maxHeight; decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT; int newWidth, newHeight; decimal originalWidth = (decimal)width; decimal originalHeight = (decimal)height; if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT) { decimal factor; // determine the largest factor if (originalWidth / originalHeight > ASPECT_RATIO) { factor = originalWidth / MAX_WIDTH; newWidth = Convert.ToInt32(originalWidth / factor); newHeight = Convert.ToInt32(originalHeight / factor); } else { factor = originalHeight / MAX_HEIGHT; newWidth = Convert.ToInt32(originalWidth / factor); newHeight = Convert.ToInt32(originalHeight / factor); } } else { newWidth = width; newHeight = height; } return new Size(newWidth,newHeight); }
若對您有用,請贊助個棒棒糖~

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4452.html
標籤:ASP.NET
上一篇:使用ASP.NET Core 3.x 構建 RESTful API - 3.2 路由和HTTP方法
下一篇:ASP.NET圖片上傳和截取
