用戶登錄  |  用戶注冊
首 頁源碼下載網絡學院最新源碼源碼排行屏蔽廣告
當前位置:新興網絡 > 網絡學院 > .Net技術 > Asp.Net

Asp.net圖片上傳并生成縮略圖(C#)

減小字體 增大字體 作者:佚名  來源:本站整理  發布時間:2010-06-28 19:51:17

.CS代碼:

C# code復制代碼
/// <summary>
/// asp.net上傳圖片并生成縮略圖
/// </summary>
/// <param name="upImage">HtmlInputFile控件</param>
/// <param name="sSavePath">保存的路徑,些為相對服務器路徑的下的文件夾</param>
/// <param name="sThumbExtension">縮略圖的thumb</param>
/// <param name="intThumbWidth">生成縮略圖的寬度</param>
/// <param name="intThumbHeight">生成縮略圖的高度</param>
/// <returns>縮略圖名稱</returns>
public string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)
{
    #region
    #region
    string sThumbFile = "";
    string sFilename = "";
    if (txtTitle.Text.Trim().Length > 0)
    {
    }
    else
    {
        Jscript.Alert("標題不能為空");
        return "標題不能為空";
    }
    School.Model.BlogUserPic bumodel = new School.Model.BlogUserPic();
    School.BLL.BlogUserPic buBll = new School.BLL.BlogUserPic();

    //獲取用戶ID
    EncryptStr Encry = new EncryptStr();
    userID = Encry.Decrypt(HttpContext.Current.Request.Cookies["SchoolStudent"]["UserID"].ToString());

    //設置添加信息
    bumodel.PicTitle = Utils.ChkSQL(this.txtTitle.Text.Trim().ToString());
    bumodel.PicDesc = Utils.ChkSQL(this.txtPicDesc.Text.Trim().ToString());
    bumodel.addTime = DateTime.Now;
    bumodel.UserId = Utils.StrToInt(userID, 0);
    bumodel.uploadIP = DNTRequest.GetIP();
    bumodel.IsDel = 0;
    bumodel.IsCheck = 1;
    #endregion
    #region
    if (upImage.PostedFile != null)
    {
        HttpPostedFile myFile = upImage.PostedFile;
        int nFileLen = myFile.ContentLength;
        if (nFileLen == 0)
        {
            Jscript.Alert("沒有選擇上傳圖片");
            return "沒有選擇上傳圖片";
        }
        if (nFileLen > 2097152)
        {
            Jscript.Alert("上傳圖片不能大于2MB");
            return "上傳圖片不能大于2MB";
        }
        //獲取upImage選擇文件的擴展名
        string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
        //判斷是否為圖片格式
        if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
        {
            Jscript.Alert("圖片格式不正確");
            return "圖片格式不正確";
        }
        byte[] myData = new Byte[nFileLen];
        myFile.InputStream.Read(myData, 0, nFileLen);
        sFilename = System.IO.Path.GetFileName(myFile.FileName);
        int file_append = 0;
        //檢查當前文件夾下是否有同名圖片,有則在文件名+1
        while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
        {
            file_append++;
            sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
         + file_append.ToString() + extendName;
        }
        System.IO.FileStream newFile = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename),
            System.IO.FileMode.Create, System.IO.FileAccess.Write);
        newFile.Write(myData, 0, myData.Length);
        newFile.Close();
        //以上為上傳原圖
        #region
        try
        {
            //原圖加載
            using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
            {
                //原圖寬度和高度
                int width = sourceImage.Width;
                int height = sourceImage.Height;
                int smallWidth;
                int smallHeight;
                //獲取第一張繪制圖片的大小,(比較 原圖的寬/縮略圖的寬 和 原圖的高/縮略圖的高)
                if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                {
                    smallWidth = intThumbWidth;
                    smallHeight = intThumbWidth * height / width;
                }
                else
                {
                    smallWidth = intThumbHeight * width / height;
                    smallHeight = intThumbHeight;
                }

                //判斷縮略圖在當前文件夾下是否同名稱文件存在
                file_append = 0;
                sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;
                while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                {
                    file_append++;
                    sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + extendName;
                }

                //縮略圖保存的絕對路徑
                string smallImagePath = Server.MapPath(sSavePath) + sThumbFile;
                //System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
                //bumodel.PicUrl = Server.MapPath(smallImagePath);
                bumodel.PicUrl = "/UploadBlogPhoto/" + userID + "/" + sThumbFile;//壓縮過的圖片
                //smallImagePath;
                //業務層 增加方法 bumodel是model
                buBll.Add(bumodel);//添加相片
                Response.Write("<script language='JavaScript'>alert('添加相片成功');window.location='BlogUserPic.aspx?userID=" + userID + "';</script>");
                //Response.End();
                //新建一個圖板,以最小等比例壓縮大小繪制原圖
                using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                {
                    //繪制中間圖
                    using (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(System.Drawing.Color.White);
                        g.DrawImage(
                            sourceImage, new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                            new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.GraphicsUnit.Pixel);
                    }
                    //新建一個圖板,以縮略圖大小繪制中間圖
                    using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                    {
                        //繪制縮略圖
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                        {
                            //高清,平滑
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(System.Drawing.Color.White);
                            int lwidth = (smallWidth - intThumbHeight) / 2;
                            int bheight = (smallHeight - intThumbHeight) / 2;
                            g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                            g.Dispose();
                            bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                }

            }
        }

        catch
        {
            //出錯則刪除
            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));
            Jscript.Alert("圖片格式不正確");
            return "圖片格式不正確";
        }
        #endregion
        //返回縮略圖名稱
        return sThumbFile;
    }
    #endregion
    Jscript.Alert("沒有選擇圖片");
    return "沒有選擇圖片";
    #endregion

button控件事件:

C# code復制代碼
/// <summary>
/// 上傳圖片事件
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">e</param>
protected void btnSmbit_Click(object sender, EventArgs e)
{
    //獲取用戶ID
    EncryptStr Encry = new EncryptStr();
    userID = Encry.Decrypt(HttpContext.Current.Request.Cookies["SchoolStudent"]["UserID"].ToString());
    //我們是根據用戶ID生成一個文件夾,保存到單獨的文件夾
    this.UpLoadImage(this.File1, "../UploadBlogPhoto/" + userID + "/", "thumb_", 600, 600);
}
前臺代碼:
<td>添加相片:<input id="File1" runat="server" type="file" />
<asp:Button ID="btnSmbit" runat="server" Text="提交" OnClick="btnSmbit_Click" />
</td>

Tags:Asp.net 圖片上傳 縮略圖

作者:佚名
  • 好的評價 如果您覺得此文章好,就請您
      75%(3)
  • 差的評價 如果您覺得此文章差,就請您
      25%(1)

網絡學院評論評論內容只代表網友觀點,與本站立場無關!

   評論摘要(共 0 條,得分 0 分,平均 0 分) 查看完整評論
pk10计划软件冠军五码