Asp.Net上传图片并生成略缩图

分享下

前端

<body>
    <form id="sheet" runat="server">
    <div>
        <asp:FileUpload ID="UpFile" runat="server" />
        &nbsp;<asp:Button ID="btnUpLoad" runat="server"
            Text="UpLoad And Create Small Picture" οnclick="btnUpLoad_Click" />
        <br />
        Your Small Picture Is:<br />
        <asp:Image ID="imgShow" runat="server" />
    </div>
    </form>
</body>

程序代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        imgShow.Visible = false;
    }
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        string filePath = UpFile.PostedFile.FileName;
        string fileName = filePath.Substring(filePath.LastIndexOf("//") + 1);
        string flag = filePath.Substring(filePath.LastIndexOf(".") + 1);
        flag = flag.ToLower();
        if (flag != "jpg" && flag != "bmp" && flag != "gif")
        {
            Response.Write("<script>alert('你选择的不是图片文件!');</script>");
        }
        else
        {
            string savepath = Server.MapPath("UpLoadFiles/") + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + "." + flag;
            UpFile.PostedFile.SaveAs(savepath);

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(savepath);
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height; 

            int width = 640;
            int height = 512;

            System.Drawing.Image bitmap = new System.Drawing.Bitmap(width,height);
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(Color.Transparent);
            g.DrawImage(originalImage, new Rectangle(0, 0, width, height), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
            try
            {
                string NewSaveName = Server.MapPath("UpLoadFiles/") + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".jpg";
                bitmap.Save(NewSaveName, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgShow.Visible = true;
                imgShow.ImageUrl = NewSaveName;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}
上班没时间整,没有等比例缩放图片。需要的自己优化一下。

猜你喜欢

转载自blog.csdn.net/susieweijs/article/details/6342302