標籤:
我就不多說了注釋裡都有
if (Request.Files["file1"] == null) { Response.Write("<script>alert(\"請選擇上傳檔案!\")</script>"); } else { //擷取圖片格式 string fileExtension = Path.GetExtension(Request.Files["file1"].FileName); if (fileExtension == ".jpg") { //圖片儲存路徑 string savePath = Server.MapPath(@"~/uploadpic/"); //取到圖片流 Stream sam = Request.Files["file1"].InputStream; //取到圖片流存入Image System.Drawing.Image im = System.Drawing.Image.FromStream(sam); //原圖寬度 int oWidth = im.Width; //原圖高度 int oHeight = im.Height; //設定縮圖初始寬度 int tWidth = 210; //設定縮圖初始高度 int tHeight = 180; //建立空的bmp圖片 Bitmap bt = new Bitmap(210, 180); //按比例計算出縮圖的寬度和高度 if (oWidth >= oHeight) tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth))); else tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight))); //圖片置中 int pWidth = (210 - tWidth) / 2; int pHeight = (180 - tHeight) / 2; //建立繪製圖片執行個體 Graphics g = Graphics.FromImage(bt); //控製圖片品質 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; //控制消除鋸齒 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //設定透明背景 g.Clear(Color.Transparent); //產生縮圖 g.DrawImage(im, new Rectangle(pWidth, pHeight, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel); //儲存圖片 bt.Save(string.Format("{0}{1}.png", savePath, DateTime.Now.ToString("yyyyMMddHHmmss_yyyy")), ImageFormat.Png); } else { Response.Write("<script>alert(\"圖片格式不正確!\")</script>"); } }
轉載請註明!
C# ASP.NET 按比例縮小代碼(基礎版)