asp.net FileUpload1上传前 调整图片大小 再进行上传

asp.net FileUpload1上传前 调整图片大小 再进行上传,因为有些人上传的图片太大了,影响宽带


前台代码:



    <div>
        <asp:FileUpload ID="FileUpload" runat="server" />
        <br /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上传图片" />
        <br /><br />

        <br /><br />
        <asp:Image ID="Image1" ImageUrl="" runat="server" Visible="false" 
            Height="167px" Width="226px" />
</div>


后台代码:(按钮中添加)




    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload.HasFile)
        {

            string filename = FileUpload.FileName;


            if (!Directory.Exists(Server.MapPath(@"./图片")))
            {

                Directory.CreateDirectory(Server.MapPath(@"./图片"));
            }


            string directory = Server.MapPath(@"./图片\");


            Bitmap originalBMP = new Bitmap(FileUpload.FileContent);

            int thumbnailSize = 250;
            int newWidth, newHeight;
            if (originalBMP.Width > originalBMP.Height)
            {
                newWidth = thumbnailSize;
                newHeight = originalBMP.Height * thumbnailSize / originalBMP.Width;
            }
            else
            {
                newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height;
                newHeight = thumbnailSize;
            }

            Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

            Graphics oGraphics = Graphics.FromImage(newBMP);


            oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);


            newBMP.Save(directory + filename);


            originalBMP.Dispose();
            newBMP.Dispose();
            oGraphics.Dispose();


            Image1.Visible = true;
            Image1.ImageUrl = @"./图片/" + filename;  ///  这里设置文件名
        }


        else
        {
            Response.Write("<script>alert('没有选择图片" + "')';</script>");
        }


    }
}



效果图如下:


asp.net_FileUpload1上传前_调整图片大小_再进行上传


webform