1. 程式人生 > 實用技巧 >C# 生成縮圖方法

C# 生成縮圖方法

  private static string CreateThumbnail(string filepath, int tWidth, int tHeight)
        {
            if (string.IsNullOrEmpty(filepath))
            {
                return "";
            }
            string paramOriginalDirectory = "thumbnail";
            string oldfilepath = filepath;
            
//string originalImagePath = HttpContext.Current.Server.MapPath(filepath);//全路徑(即絕對路徑) string originalImagePath = filepath;//全路徑(即絕對路徑) //originalImagePath = ApiToWeb(originalImagePath); string filename = System.IO.Path.GetFileName(originalImagePath); string oldthumbnailImagePath = oldfilepath.Replace(filename, ""
) + paramOriginalDirectory + "/" + filename; string thumbnailPath = originalImagePath.Replace(filename, "") + paramOriginalDirectory; string thumbnailImagePath = originalImagePath.Replace(filename, "") + paramOriginalDirectory + "/" + filename; if (!Directory.Exists(thumbnailPath)) { Directory.CreateDirectory(thumbnailPath); }
if (!File.Exists(originalImagePath)) { return oldthumbnailImagePath; } if (File.Exists(thumbnailImagePath)) { return oldthumbnailImagePath; } try { FileStream fileStream = File.OpenRead(originalImagePath); Int32 filelength = 0; filelength = (int)fileStream.Length; Byte[] image = new Byte[filelength]; fileStream.Read(image, 0, filelength); System.Drawing.Image oImage = System.Drawing.Image.FromStream(fileStream); fileStream.Close(); int oWidth = oImage.Width;//原圖寬度 int oHeight = oImage.Height;//原圖高度 if (tWidth == 0) { tWidth = 100; } if (tHeight == 0) { tHeight = 100; } //按比例計算出縮圖的寬度和高度 if (oWidth >= oHeight) { tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oHeight))); } else { tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight))); } //生成縮圖 Bitmap tImage = new Bitmap(tWidth, tHeight); Graphics g = Graphics.FromImage(tImage); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//設定高質量插值法 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//設定高質量,低速度呈現平滑程度 g.Clear(Color.Transparent);//清空畫布並以透明背景色填充 g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel); //string oPath = originalImagePath + "\\" + filename + ".jpg"; //string thumbnailImagePath = thumbnailPath + "\\" + filename + ".jpg"; tImage.Save(thumbnailImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); //釋放資源 oImage.Dispose(); g.Dispose(); tImage.Dispose(); return oldthumbnailImagePath; } catch (Exception ex) { return ex.Message + ex.StackTrace; } }