ASP.NET圖片處理問題總結


     我們在做web程序的時候經常會遇到一些圖片處理的問題,今天就把遇到的需要圖片處理的地方給總結一下。也算是對自己學習過程的一個總結,希望也能給大家一些啟發。

一、驗證碼。

我們在某些網站注冊或者登錄的時候,都可能遇到要填寫驗證碼的地方,當時沒搞懂這樣的圖片是怎樣一回事,事實上這是一張隨機生成的圖片,需要在后台專門新建一個aspx頁或者ashx一般程序處理頁來專門負責生成這樣的圖片。下面就通過示例向大家演示這樣的一個過程!

首先我們新建一個登錄頁,模擬用戶登錄。代碼如下:

 

<div>
    <table>
    <tr><td>賬號:</td><td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td></tr>
    <tr><td>密碼:</td><td>
        <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox></td></tr>
    <tr><td>驗證碼:</td><td>
        <asp:Image ID="Image1" runat="server" ImageUrl="ValidateNo.aspx" /></td></tr>
    <tr><td>請輸入:</td><td>
        <asp:TextBox ID="txtyzm" runat="server"></asp:TextBox></td></tr>
        <tr><td>
            <asp:Button ID="btndl" runat="server" Text="登錄" onclick="btndl_Click" /></td><td>
                <asp:Button ID="Button2" runat="server" Text="取消" CausesValidation=false /></td></tr>
    </table>
    </div>

布局如圖:

然后再新建一個ValidateNo.aspx頁,用來生成驗證碼圖片,在這個aspx頁中只需要在構造函數中寫如下代碼即可:

 

protected void Page_Load(object sender, EventArgs e)
        {
            Random r = new Random();
            int i = r.Next(1000, 9999);//生成一個四位的隨機數
            Bitmap bit = new Bitmap(100, 40);//生成一個尺寸為100,40的位圖
            Graphics g = Graphics.FromImage(bit);//創建一個繪圖實例,並以上邊創建的的位圖為畫板,當然這里邊也以選擇一張已有的圖片作為畫板。只需要將FromImage()里的參數換位已存在的Image對象即可
            g.DrawLine(new Pen(Brushes.Blue), new Point(0, 10), new Point(100, 10));
            g.DrawLine(new Pen(Brushes.GreenYellow), new Point(0, 25), new Point(100, 25));//畫兩條直線,起到一定的模糊驗證的碼的效果
            g.DrawString(i.ToString(), new Font("宋體", 30), Brushes.Green, new PointF(0, 0));//將生成的四位數的驗證碼繪到該畫板上
            bit.Save(Response.OutputStream, ImageFormat.Jpeg);//將該位圖保存為JPEG的格式
            Session["ValidateNo"] = i.ToString();//Seession值保存生成的驗證碼的值,以便在登錄的時候和用戶輸入的驗證碼的值做比較
            Response.ContentType = "image/jpeg";//將輸入類型改為“Image/jpeg"
            Response.End();
        }

剛剛我們在代碼里有說到將生成的隨機驗證碼保存在seesion中,那么我們在登錄的時候就可以根據session中值的和用戶輸入的值做比較,以此來判斷用戶輸入驗證碼是否正確,所以我們在登錄頁的aspx.cs頁做出這樣的處理:(這里只是模擬測試,在實際的開發中,如果驗證碼、密碼、賬號都正確的話,就會導向新的頁面)

protected void btndl_Click(object sender, EventArgs e)
        {
            if (Session["ValidateNo"] != null)
            {
                string s = Session["ValidateNo"].ToString();
                if (txtyzm.Text != s)
                {
                    Response.Write("<script>alert('"+s+"')</script>");
                }
                else
                {
                    Response.Write("<script>alert('OK')</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('驗證碼暫不存在!')</script>");
            }
        }

二、給圖片加文字

有時候我們會看到有些個人空間或主頁的圖片都加有相應的文字,就像騰訊微博那種發一張圖片會顯示騰訊微博字樣。下面我就給大家展示下如何在圖片上添加文字。

首先我們新建一個aspx頁,頁面布局如下:

 

<table style="background:lightblue"><tr><td>選擇上傳文件:</td><td><asp:FileUpload ID="FileUpload1" runat="server" /></td><td>
           <asp:Button ID="btnupload" runat="server" Text="上傳圖片" 
               onclick="btnupload_Click" /></td></tr>
       <tr><td colspan="3">
           <asp:Image ID="TouXiang" runat="server" /></tr>
 </table> 

然后我們在btnuplod按鈕的Click事件的處理函數中做如下操作:

 

protected void btnupload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.FileName.Trim() != "")
            {
                string extension = Path.GetExtension(FileUpload1.FileName);//先獲取文件的后綴
                string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Minute.ToString();//以當前的日期,以年月分的格式為上傳的圖片重命名
                string path = Server.MapPath(".")+"\\images\\"+fileName + extension;
                FileUpload1.PostedFile.SaveAs(path);//將圖片保存在指定路徑下
               Bitmap img = new Bitmap(path);//新建一個Bitmap對象並以此為畫板
                Graphics g = Graphics.FromImage(img);
                g.DrawString("Hello Olive!", new Font("宋體", 30), Brushes.GreenYellow, new PointF(20,20) );//將"Hello Olive"書寫在圖片的(20,20)處
                g.Dispose();
                newPath = Server.MapPath(".") + "\\images\\" + fileName + "_New" + extension;
                img.Save(newPath);//將加有文字的圖片重新命名並保存,並刪除原來的圖片
                img.Dispose();
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                touxiangpath="~/images/" + fileName + "_New" + extension;
            }
            else
            {
                Response.Write("<script>alert('請先選擇要上傳的文件!')</script>");
            }
        }

效果如圖:

三、生成略縮圖

現在的很多博客、個人主頁、空間之類的都有編輯個人信息的設置,在編輯個人信息的時候都可能會需要上傳頭像,下面我們來講一下如何生成略縮頭像。

頁面布局的話我們還是引用上邊的布局:

但是要在<table></table>再加一行,用來顯示生成的略縮圖。

首先我們需要新建一個CutImageCutImage.cs,專門用來對圖片進行縮放,如下:

       /// <summary>(該圖片縮放的代碼參考自博客園博主king-兩色天)

        /// 截取圖片

        /// </summary>

        /// <param name="oPath">原圖片路徑</param>

        /// <param name="nPaht">新圖片路徑</param>

        /// <param name="w">略縮圖的寬度</param>

        /// <param name="h">略縮圖的高度</param>

        /// <param name="mode">截取模式</param>

     

 public static void CutImg(string oPath, string nPaht, int w, int h,string mode)
        {
            Image oimg = Image.FromFile(oPath);
            int nToWidth = w;
            int nToHeight = h;
            int x = 0;
            int y = 0;
            int oWidth = oimg.Width;
            int oHeight = oimg.Height;
            switch (mode)
            {
                case "HW"://按照指定的寬高進行縮放,可能變形
                    break;
                case "W"://指定寬度,高按比例縮放
                    nToHeight = oWidth * oHeight / nToWidth;
                    break;
                case "H"://指定高度,寬按比例縮放
                    nToWidth=oWidth*oHeight/nToHeight;
                    break;
                case "CUT"://按照指定的寬、高縮放
                    if ((oimg.Width / oimg.Height) > (nToWidth / nToHeight))
                    {
                        oHeight = oimg.Height;
                        oWidth = oimg.Height * nToWidth / nToHeight;
                        y = 0;
                        x = (oimg.Width - oWidth) / 2;
                    }
                    else
                    {
                        oWidth = oimg.Width;
                        oHeight = oimg.Width * nToHeight / nToWidth;
                        x = 0;
                        y = (oimg.Height - oHeight) / 2;
                    }
                    break;
                default: break;
            }
            //新建一個BMP圖片
            Image bitmap = new Bitmap(nToWidth, nToHeight);
            //新建一個畫板
            Graphics gp = Graphics.FromImage(bitmap);
            gp.InterpolationMode = InterpolationMode.High;
            gp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空畫布,並以背景色為透明色填充
            gp.Clear(Color.Transparent);
            gp.DrawImage(oimg, new Rectangle(0, 0, nToWidth, nToHeight), new Rectangle(x, y, oWidth, oHeight), GraphicsUnit.Pixel);//繪制出新的略縮圖
            try
            {
                bitmap.Save(nPaht, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch(Exception e)
            {
                throw e;
            }
            finally
            {
                oimg.Dispose();
                bitmap.Dispose();
            }
        }

然后我們的aspx頁的btnupload按鈕的Click事件的處理函數代碼如下:

 

protected void btnupload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.FileName.Trim() != "")
            {
                    //.......
                    //.......前邊都省略了代碼是一樣的
                      if (File.Exists(path))
                {
                    File.Delete(path);
                }
                string p = Server.MapPath(".") + "\\images\\";
                touxiangpath="~/images/" + fileName + "_New" + extension;
                TouXiang.ImageUrl = touxiangpath;
                CutImage.CutImg(newPath, p+"olive.jpg", 100, 200, "CUT");//調用縮放圖片的類CutImage的CutImg函數,這里直接保存為了“olive.jpg"是為了方便下面的引用顯示,也可保存為其他的名稱和格式。
                 luesuotu.ImageUrl = "~/images/olive.jpg";
            } 
            else
            {
                Response.Write("<script>alert('請先選擇要上傳的文件!')</script>");
            }
        }

生成效果如圖:

為了方便大家的使用我已經把圖片縮放功能封裝成了一個類,里邊還有其他的一些縮放的功能,已經導出了類模板,有興趣的朋友可以點擊下載ImageCut.zip,希望可以給大家一些幫助。

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM