C# ASP.NET 图片按比例缩小

我就不多说了注释里都有

     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>");
            }
        }

转载请注明!

转载于:https://www.cnblogs.com/xuduo-123/p/4540337.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值