C# ASP.NET 按比例縮小代碼(基礎版)

來源:互聯網
上載者:User

標籤:

我就不多說了注釋裡都有

     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 按比例縮小代碼(基礎版)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.