控制上传图片的大小

来源:互联网 发布:sublime text windows 编辑:程序博客网 时间:2024/05/17 01:34

public static void MakeSmallImg(System.Web.HttpPostedFile postFile, string saveImg, System.Double Width)
    {

        //原始图片名称
        string originalFilename = postFile.FileName;
        //生成的高质量图片名称
        string strGoodFile = saveImg;


        //从文件取得图片对象
        System.Drawing.Image image = System.Drawing.Image.FromStream(postFile.InputStream, true);

        if (image.Width > Width)
        {
            System.Double NewWidth, NewHeight;
            NewWidth = Width;
            NewHeight = image.Height * (NewWidth / image.Width);

            if (NewWidth > Width)
            {
                NewWidth = Width;
                NewHeight = image.Height * (NewWidth / image.Width);
            }

            System.Drawing.Size size = new System.Drawing.Size((int)NewWidth, (int)NewHeight);

            System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            g.Clear(Color.White);

            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),new System.Drawing.Rectangle(0, 0, image.Width, image.Height),System.Drawing.GraphicsUnit.Pixel);

            bitmap.Save(strGoodFile, System.Drawing.Imaging.ImageFormat.Jpeg);

            g.Dispose();
            image.Dispose();
            bitmap.Dispose();
        }
        else
        {
            postFile.SaveAs(saveImg);
        }
    }