天天看點

ASP.NET 多張圖檔上傳,并可以預覽。

一、首先先上效果圖:

1、上傳前

ASP.NET 多張圖檔上傳,并可以預覽。

2、上傳後

ASP.NET 多張圖檔上傳,并可以預覽。

二、主要使用控件:FileUpload,DataList展示多張圖檔

三、代碼

1、前台aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductZiZhiUpload.aspx.cs" Inherits="ProductZiZhiUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

        <meta charset="UTF-8">

        <style type="text/css">

            *{

                margin: 0;

                padding: 0;

            }

            #upBox{

                text-align: center;

                padding: 2px;

                border: 1px solid #666;

                margin: auto;

                margin-top: 15px;

                margin-bottom: 20px;

                position: relative;

                border-radius: 10px;

            }

                #upBox2{

                text-align: center;

                padding: 2px;

                border: 1px solid #666;

                margin: auto;

                margin-top: 15px;

                margin-bottom: 20px;

                position: relative;

                border-radius: 10px;

            }

                      #upBox3{

                text-align: center;

                padding: 2px;

                border: 1px solid #666;

                margin: auto;

                margin-top: 15px;

                margin-bottom: 20px;

                position: relative;

                border-radius: 10px;

            }

                   #upBox4{

                text-align: center;

                padding: 2px;

                border: 1px solid #666;

                margin: auto;

                margin-top: 15px;

                margin-bottom: 20px;

                position: relative;

                border-radius: 10px;

            }

            #inputBox{

                width: 100%;

                height: 40px;

                border: 1px solid cornflowerblue;

                color:red;

                border-radius: 20px;

                position: relative;

                text-align: center;

                line-height: 40px;

                overflow: hidden;

                font-size: 16px;

                background-color:deepskyblue;

            }

            #inputBox2{

                width: 100%;

                height: 40px;

                border: 1px solid cornflowerblue;

                color:red;

                border-radius: 20px;

                position: relative;

                text-align: center;

                line-height: 40px;

                overflow: hidden;

                font-size: 16px;

                background-color:deepskyblue;

            }

               #inputBox3{

                width: 100%;

                height: 40px;

                border: 1px solid cornflowerblue;

                color:red;

                border-radius: 20px;

                position: relative;

                text-align: center;

                line-height: 40px;

                overflow: hidden;

                font-size: 16px;

                background-color:deepskyblue;

            }

                  #inputBox4{

                width: 100%;

                height: 40px;

                border: 1px solid cornflowerblue;

                color:red;

                border-radius: 20px;

                position: relative;

                text-align: center;

                line-height: 40px;

                overflow: hidden;

                font-size: 16px;

                background-color:deepskyblue;

            }

            #inputBox input{

                width: 114%;

                height: 40px;

                opacity: 0;

                cursor: pointer;

                position: absolute;

                top: 0;

                left: -14%;

            }

                #inputBox2 input{

                width: 114%;

                height: 40px;

                opacity: 0;

                cursor: pointer;

                position: absolute;

                top: 0;

                left: -14%;

            }

                    #inputBox3 input{

                width: 114%;

                height: 40px;

                opacity: 0;

                cursor: pointer;

                position: absolute;

                top: 0;

                left: -14%;

            }

                    #inputBox4 input{

                width: 114%;

                height: 40px;

                opacity: 0;

                cursor: pointer;

                position: absolute;

                top: 0;

                left: -14%;

            }

            #imgBox{

                text-align: left;

            }

            #imgBox2{

                text-align: left;

            }

            #imgBox3{

                text-align: left;

            }

            #imgBox4{

                text-align: left;

            }

        .yincang{

            display:none;

        }

        #Button1{

                display: inline-block;

                text-align: center;

                line-height: 30px;

                outline: none;

                width: 100px;

                height: 30px;

                background: cornflowerblue;

                border: 1px solid cornflowerblue;

                color: white;

                cursor: pointer;

                margin-top: 30px;

                border-radius: 5px;

            }

         .card-layerBg {

    display: none;

    width: 100%;

    z-index: 999;

    position: fixed;

    background-color: #000;

    opacity: 0.5;

    top: 0;

    height: 100%;

    filter: alpha(opacity=50);

}

.card-layerCon {

    display: none;

    width: 600px;

    padding: 10px 30px 20px 0;

    background-color: #fff;

    z-index: 9999;

    position: fixed;

    left: 50%;

    top: 50%;

    margin-left: -300px;

    opacity: 1;

    filter: alpha(opacity=100);

    text-align:center;

}

.close {

    font-size: 33px;

    text-align: center;

    color: #ab2223;

    position: absolute;

    right: 10px;

    top: -8px;

    cursor: pointer;

}

.card-layerM {

    width: 100%;

    margin: 0 auto;

    padding: 10px;

    padding-top: 25px;

    overflow-y: auto;

    max-height:100%;

    text-align: center;

}

.card-layerM img{

    width:auto;

    max-width:100%;

    max-height:100%;

}

        </style>

    <script src="js/jquery1.10.2.min.js"></script>

    <script src="My97DatePicker/WdatePicker.js"></script>

    <script type="text/javascript">

//有效期字段是否為空檢驗方法

        function btnsave_onclick() {

            var ctime = $("*[id$=tendtime]").val();

            $("*[id$=Label2]").text("*");

            if (ctime == "") {

                alert("有效期為空!");

                return false;

            } else {

                return true;

            }

        }

//點選上傳圖檔查詢大圖的js

        function layer(small) {

            $(".layer_con img").on("load", function () {

                var $con = $(".layer_con").height() + 30;

                $(".layer_bg").css({ "display": "block" });

                var $winH = $(window).height();

                if ($con > $winH) {

                    $(".layer_con").css({ "height": $winH, "display": "block", "top": "0", "margin-top": "0" });

                } else {

                    $(".layer_con").css({ "display": "block", "top": "50%", "margin-top": -$con / 2 });

                }

            })

        }

//關閉放大圖檔

        $(function () {

            $(".close").on("click", function () {

                $(".layer_con").css("display", "none");

                $(".layer_bg").css("display", "none");

            });

        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

       <div style=" margin-top:20px;">

         <table align="center" bordercolor="#b7dcef" cellpadding="1" cellspacing="1"

                    width="99%">

                    <tr>

                        <td align="right" width="25%" height="30px" class="auto-style1">

                            藥品生産批件有效期:</td>

                        <td align="left" width="30%" class="auto-style1">

                        <asp:TextBox ID="tendtime" runat="server" onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd'})" Width="123px"></asp:TextBox>

                        <asp:Label ID="Label2" runat="server" Text="*" ForeColor="#CC0000"></asp:Label>

                        </td>

                   <td>

                       點選圖檔檢視大圖

                   </td>

                    </tr>

                </table>

       </div>

        <div style="width: 100%;">

            <div id="upBox">

                <asp:HiddenField ID="HiddenField1" runat="server" />

                 <asp:HiddenField ID="HiddenField2" runat="server" />

                 <div id="inputBox">

//點選FileUpload1上傳浏覽按鈕,通過javascript:__doPostBack('lbUploadPhoto',''),直接執行lbUploadPhoto按鈕的方法

                     <asp:FileUpload ID="FileUpload1" runat="server"  οnchange="javascript:__doPostBack('lbUploadPhoto','')"  />

                      <asp:LinkButton ID="lbUploadPhoto" runat="server" OnClick="lbUploadPhoto_Click" CssClass="yincang"></asp:LinkButton> 

                     點選選擇藥品生産批件

                 </div>

                 <div id="imgBox">

                        <asp:DataList ID="CFlist" runat="server" BackColor="White" 

                BorderColor="#E7E7FF" CellPadding="3" 

                GridLines="Horizontal"  Width="99%" onitemcommand="DataList1_ItemCommand" RepeatDirection="Horizontal" RepeatColumns="5">

                <AlternatingItemStyle BackColor="#F7F7F7" />

                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

                <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" BorderColor="black" />

                <ItemTemplate >

   <table style="border-color:Black">

                        <tr>

                            <td  style="border-style:none">

                            <img alt="<%#Eval("imagename") %>" src='<%#Eval("imageurl") %>' style="height:270px ;cursor:hand" οnclick=" $('.layer_con img').prop('src', this.src);layer($(this));"/>

//onclick方法裡是點選圖檔看大圖的js

                            </td>

                            </tr>

                           <tr>

                            <td style="height:40px;width:100px;border-style:none" >

                                <center> <asp:LinkButton ID="lbDe" CommandArgument=<%#Eval("id") %> CommandName="De" runat="server">删除</asp:LinkButton></center></td>

                        </tr>

                     </table>   

                </ItemTemplate>

                <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

            </asp:DataList>

                 </div>

            </div>

                <div id="upBox2">

                     <div id="inputBox2">

                       <asp:FileUpload ID="FileUpload2" runat="server"  οnchange="javascript:__doPostBack('lbUploadPhoto2','')"  />

                      <asp:LinkButton ID="lbUploadPhoto2" runat="server"  CssClass="yincang" OnClick="lbUploadPhoto2_Click"></asp:LinkButton> 

                         點選選擇藥品包裝及說明書</div>

                 <div id="imgBox2">

                     <asp:DataList ID="DataList2" runat="server" BackColor="White" 

                BorderColor="#E7E7FF" CellPadding="3" 

                GridLines="Horizontal"  Width="99%" onitemcommand="DataList2_ItemCommand" RepeatDirection="Horizontal" RepeatColumns="5">

                <AlternatingItemStyle BackColor="#F7F7F7" />

                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

                <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" BorderColor="black" />

                <ItemTemplate >

   <table style="border-color:Black">

                        <tr>

                            <td  style="border-style:none">

                            <img alt="<%#Eval("imagename") %>" src='<%#Eval("imageurl") %>' style="height:270px ;cursor:hand" οnclick=" $('.layer_con img').prop('src', this.src);layer($(this));"/>

                            </td>

                            </tr>

                           <tr>

                            <td style="height:40px;width:100px;border-style:none" >

                                <center> <asp:LinkButton ID="lbDe" CommandArgument=<%#Eval("id") %> CommandName="De" runat="server">删除</asp:LinkButton></center></td>

                        </tr>

                     </table>   

                </ItemTemplate>

                <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

            </asp:DataList>

                 </div>

            </div>

            <div id="upBox3">

                     <div id="inputBox3">

                          <asp:FileUpload ID="FileUpload3" runat="server"  οnchange="javascript:__doPostBack('lbUploadPhoto3','')"  />

                      <asp:LinkButton ID="lbUploadPhoto3" runat="server"  CssClass="yincang" OnClick="lbUploadPhoto3_Click" ></asp:LinkButton> 

                         藥品品質标準</div>

                 <div id="imgBox3">

                        <asp:DataList ID="DataList3" runat="server" BackColor="White" 

                BorderColor="#E7E7FF" CellPadding="3" 

                GridLines="Horizontal"  Width="99%" onitemcommand="DataList3_ItemCommand" RepeatDirection="Horizontal" RepeatColumns="5">

                <AlternatingItemStyle BackColor="#F7F7F7" />

                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

                <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" BorderColor="black" />

                <ItemTemplate >

   <table style="border-color:Black">

                        <tr>

                            <td  style="border-style:none">

                            <img alt="<%#Eval("imagename") %>" src='<%#Eval("imageurl") %>' style="height:270px ;cursor:hand" οnclick=" $('.layer_con img').prop('src', this.src);layer($(this));"/>

                            </td>

                            </tr>

                           <tr>

                            <td style="height:40px;width:100px;border-style:none" >

                                <center> <asp:LinkButton ID="lbDe" CommandArgument=<%#Eval("id") %> CommandName="De" runat="server">删除</asp:LinkButton></center></td>

                        </tr>

                     </table>   

                </ItemTemplate>

                <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

            </asp:DataList>

                 </div>

            </div>

            <div id="upBox4">

                     <div id="inputBox4">

                         <asp:FileUpload ID="FileUpload4" runat="server"  οnchange="javascript:__doPostBack('lbUploadPhoto4','')"  />

                      <asp:LinkButton ID="lbUploadPhoto4" runat="server"  CssClass="yincang" OnClick="lbUploadPhoto4_Click"  ></asp:LinkButton> 

                         藥品檢驗報告書</div>

                 <div id="imgBox4">

                      <asp:DataList ID="DataList4" runat="server" BackColor="White" 

                BorderColor="#E7E7FF" CellPadding="3" 

                GridLines="Horizontal"  Width="99%" onitemcommand="DataList4_ItemCommand" RepeatDirection="Horizontal" RepeatColumns="5">

                <AlternatingItemStyle BackColor="#F7F7F7" />

                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />

                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />

                <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" BorderColor="black" />

                <ItemTemplate >

   <table style="border-color:Black">

                        <tr>

                            <td  style="border-style:none">

                            <img alt="<%#Eval("imagename") %>" src='<%#Eval("imageurl") %>' style="height:270px ;cursor:hand" οnclick=" $('.layer_con img').prop('src', this.src);layer($(this));"/>

                            </td>

                            </tr>

                           <tr>

                            <td style="height:40px;width:100px;border-style:none" >

                                <center> <asp:LinkButton ID="lbDe" CommandArgument=<%#Eval("id") %> CommandName="De" runat="server">删除</asp:LinkButton></center></td>

                        </tr>

                     </table>   

                </ItemTemplate>

                <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

            </asp:DataList>

                 </div>

            </div>

        </div>

        <div style=" margin-top:10px;   text-align:center; margin-bottom:20px;">

            <asp:Button ID="Button1" runat="server" Text="儲存" OnClick="Button1_Click" onclientclick="return btnsave_onclick() ; "/><br />

            <asp:Label ID="Label1" runat="server" Text="注意:資質不全不要儲存" ForeColor="Red"></asp:Label>

        </div>

    </div>

//大圖的idv

                    <div class="layer_bg card-layerBg">

</div>

        <div class="layer_con card-layerCon">

    <div class="layer_main card-layerM">

        <img  src="" />

    </div>

    <div class="close">x</div>

</div>

//大圖的div

    </form>

</body>

</html>

2、背景cs代碼

using System;

using System.Collections.Generic;

using System.Data;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Drawing.Imaging;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class ProductZiZhiUpload : System.Web.UI.Page

{

    ExecuteSql executeSql = new ExecuteSql();

    public static System.IO.Stream fileDataStream = null;

    protected void Page_Load(object sender, EventArgs e)

    {

        if(!IsPostBack)

        { 

        string ccomid= Request.QueryString["comid"];

            HiddenField1.Value = ccomid;

            HiddenField2.Value = executeSql.ExecuteSelectFirst("SELECT  COMNAME FROM dbo.V_Product where comid='"+ ccomid + "'");

            string sql1 = "select CONVERT(VARCHAR(100),endtime,23) AS endtime from prd_product_zizhi where comid='" + ccomid + "'";

            DataTable dt1 = executeSql.ExecuteSelectQuery(sql1);

            if (dt1 != null && dt1.Rows.Count > 0)

            {

                tendtime.Text = dt1.Rows[0]["endtime"].ToString();

            }

            band1();

            band2();

            band3();

            band4();

        }

    }

    protected void lbUploadPhoto_Click(object sender, EventArgs e)

    {

        fileUpload();

    }

    protected void lbUploadPhoto2_Click(object sender, EventArgs e)

    {

        fileUpload2();

    }

    protected void lbUploadPhoto3_Click(object sender, EventArgs e)

    {

        fileUpload3();

    }

    protected void lbUploadPhoto4_Click(object sender, EventArgs e)

    {

        fileUpload4();

    }

    //從控件上傳檔案1 

    public void fileUpload()

    {

        fileDataStream = FileUpload1.PostedFile.InputStream;

        System.Drawing.Image image = System.Drawing.Image.FromStream(fileDataStream);//從上傳檔案流中執行個體化Image類 

        float w = image.HorizontalResolution;//擷取上傳檔案的水準分辨率(以“像素/英寸”為機關)。

        float w1 = image.Width;

        float h1 = image.Height;

        //float h = image.VerticalResolution;//擷取上傳檔案的垂直分辨率(以“像素/英寸”為機關)。 

        if (w>71.9)//這裡限制了分辨率必須大于72的,這裡可以不限制

        {

            if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.ContentLength > 0 && FileUpload1.PostedFile.ContentLength < 1024 * 1024 * 5)//最大不超過5M

            {

                string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();

                if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif" && ext != ".png")

                {

                    return;

                }

                string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;

                string path = "~/upload/tupian1/" + filename;

                FileUpload1.PostedFile.SaveAs(Server.MapPath(path));

                string imageurl = "upload/tupian1/" + filename;

                string newimageurl = imageurl;

                newimageurl = newimageurl.Replace("Image_", "yasuoImage_");

                string insql = "insert into prd_file(typeid,comid,imagename,imageurl,newimageurl,isok,imagetitle) "

                    + " values(1,'" + HiddenField1.Value + "','" + filename + "','" + imageurl + "','"+ newimageurl+ "',0,'"+HiddenField2.Value+ "_藥品生産批件')";

                executeSql.UpdateHrd_qxCount(insql);

                string spath = Server.MapPath(path);

                yasuo(spath, w1, h1);//這裡上傳後同時生成一張 96像素的标準大小圖檔,如果沒有這個業務可以删除這段代碼

                band1();

            }

            else

            {

                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上傳檔案不能大于5M!');</script>");

                // Response.Write("<Script>alert('上傳檔案不能大于5M!');history.go(-2);</Script>");

            }

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('圖檔分辨率不能小于72dpi!');</script>");

        }

    }

    //從控件上傳檔案2

    public void fileUpload2()

    {

        fileDataStream = FileUpload2.PostedFile.InputStream;

        System.Drawing.Image image = System.Drawing.Image.FromStream(fileDataStream);//從上傳檔案流中執行個體化Image類 

        float w = image.HorizontalResolution;//擷取上傳檔案的水準分辨率(以“像素/英寸”為機關)。

        float w1 = image.Width;

        float h1 = image.Height;

        //float h = image.VerticalResolution;//擷取上傳檔案的垂直分辨率(以“像素/英寸”為機關)。 

        if (w > 71.9)

        {

            if (FileUpload2.PostedFile != null && FileUpload2.PostedFile.ContentLength > 0 && FileUpload2.PostedFile.ContentLength < 1024 * 1024 * 5)

        {

            string ext = System.IO.Path.GetExtension(FileUpload2.PostedFile.FileName).ToLower();

            if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif" && ext != ".png")

            {

                return;

            }

            string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;

            string path = "~/upload/tupian2/" + filename;

            FileUpload2.PostedFile.SaveAs(Server.MapPath(path));

            string imageurl = "upload/tupian2/" + filename;

                string newimageurl = imageurl;

                newimageurl = newimageurl.Replace("Image_", "yasuoImage_");

                string insql = "insert into prd_file(typeid,comid,imagename,imageurl,newimageurl,isok,imagetitle) "

                + " values(2,'" + HiddenField1.Value + "','" + filename + "','" + imageurl + "','" + newimageurl + "',0,'"+HiddenField2.Value+ "_包裝及說明書')";

            executeSql.UpdateHrd_qxCount(insql);

                string spath = Server.MapPath(path);

                yasuo(spath, w1, h1);

                band2();

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上傳檔案不能大于5M!');</script>");

           // Response.Write("<Script>alert('上傳檔案不能大于5M!');history.go(-2);</Script>");

        }

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('圖檔分辨率不能小于72dpi!');</script>");

        }

    }

    //從控件上傳檔案3

    public void fileUpload3()

    {

        fileDataStream = FileUpload3.PostedFile.InputStream;

        System.Drawing.Image image = System.Drawing.Image.FromStream(fileDataStream);//從上傳檔案流中執行個體化Image類 

        float w = image.HorizontalResolution;//擷取上傳檔案的水準分辨率(以“像素/英寸”為機關)。 

        float w1 = image.Width;

        float h1 = image.Height;

        //float h = image.VerticalResolution;//擷取上傳檔案的垂直分辨率(以“像素/英寸”為機關)。 

        if (w > 71.9)

        {

         if (FileUpload3.PostedFile != null && FileUpload3.PostedFile.ContentLength > 0 && FileUpload3.PostedFile.ContentLength < 1024 * 1024 * 5)

        {

            string ext = System.IO.Path.GetExtension(FileUpload3.PostedFile.FileName).ToLower();

            if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif" && ext != ".png")

            {

                return;

            }

            string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;

            string path = "~/upload/tupian3/" + filename;

            FileUpload3.PostedFile.SaveAs(Server.MapPath(path));

            string imageurl = "upload/tupian3/" + filename;

                string newimageurl = imageurl;

                newimageurl = newimageurl.Replace("Image_", "yasuoImage_");

                string insql = "insert into prd_file(typeid,comid,imagename,imageurl,newimageurl,isok,imagetitle) "

                + " values(3,'" + HiddenField1.Value + "','" + filename + "','" + imageurl + "','" + newimageurl + "',0,'"+HiddenField2.Value+ "_品質标準')";

                executeSql.UpdateHrd_qxCount(insql);

                string spath = Server.MapPath(path);

                yasuo(spath, w1, h1);

                band3();

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上傳檔案不能大于5M!');</script>");

            //Response.Write("<Script>alert('上傳檔案不能大于5M!');history.go(-2);</Script>");

        }

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('圖檔分辨率不能小于72dpi!');</script>");

        }

    }

    //從控件上傳檔案4 

    public void fileUpload4()

    {

        fileDataStream = FileUpload4.PostedFile.InputStream;

        System.Drawing.Image image = System.Drawing.Image.FromStream(fileDataStream);//從上傳檔案流中執行個體化Image類 

        float w = image.HorizontalResolution;//擷取上傳檔案的水準分辨率(以“像素/英寸”為機關)。 

        float w1 = image.Width;

        float h1 = image.Height;

        //float h = image.VerticalResolution;//擷取上傳檔案的垂直分辨率(以“像素/英寸”為機關)。 

        if (w > 71.9 )

        {

            if (FileUpload4.PostedFile != null && FileUpload4.PostedFile.ContentLength > 0 && FileUpload4.PostedFile.ContentLength < 1024 * 1024 * 5)

        {

            string ext = System.IO.Path.GetExtension(FileUpload4.PostedFile.FileName).ToLower();

            if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif" && ext != ".png")

            {

                return;

            }

            string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;

            string path = "~/upload/tupian4/" + filename;

            FileUpload4.PostedFile.SaveAs(Server.MapPath(path));

            string imageurl = "upload/tupian4/" + filename;

                string newimageurl = imageurl;

                newimageurl = newimageurl.Replace("Image_", "yasuoImage_");

                string insql = "insert into prd_file(typeid,comid,imagename,imageurl,newimageurl,isok,imagetitle) "

                + " values(4,'" + HiddenField1.Value + "','" + filename + "','" + imageurl + "','" + newimageurl + "',0,'"+HiddenField2.Value+ "_檢驗報告')";

                executeSql.UpdateHrd_qxCount(insql);

                string spath = Server.MapPath(path);

                yasuo(spath, w1, h1);

                band4();

        }

        else

        {

            // Response.Write("<Script>alert('上傳檔案不能大于5M!');history.go(-2);</Script>");

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上傳檔案不能大于5M!');</script>");

        }

        }

        else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('圖檔分辨率不能小于72dpi!');</script>");

        }

    }

    protected void band1()

    {

        string sql1 = "select id,imagename,imageurl from prd_file where typeid=1 and comid='" + HiddenField1.Value + "'";

        DataTable dt1 = executeSql.ExecuteSelectQuery(sql1);

        this.CFlist.DataSource = dt1;

        this.CFlist.DataBind();

    }

    protected void band2()

    {

        string sql1 = "select id,imagename,imageurl from prd_file where typeid=2 and comid='" + HiddenField1.Value + "'";

        DataTable dt1 = executeSql.ExecuteSelectQuery(sql1);

        this.DataList2.DataSource = dt1;

        this.DataList2.DataBind();

    }

    protected void band3()

    {

        string sql1 = "select id,imagename,imageurl from prd_file where typeid=3 and comid='" + HiddenField1.Value + "'";

        DataTable dt1 = executeSql.ExecuteSelectQuery(sql1);

        this.DataList3.DataSource = dt1;

        this.DataList3.DataBind();

    }

    protected void band4()

    {

        string sql1 = "select id,imagename,imageurl from prd_file where typeid=4 and comid='" + HiddenField1.Value + "'";

        DataTable dt1 = executeSql.ExecuteSelectQuery(sql1);

        this.DataList4.DataSource = dt1;

        this.DataList4.DataBind();

    }

    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)

    {

        string type = e.CommandName.ToString();

        string Id = e.CommandArgument.ToString();

        if (type == "De")

        {

            string sql1 = "delete from prd_file where id="+ Id;

            int num = executeSql.UpdateHrd_qxCount(sql1);

            if (num > 0)

            {

                band1();

            }

            else

            {

            }

        }

        else if (type == "Ed")

        {

        }

    }

    protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)

    {

        string type = e.CommandName.ToString();

        string Id = e.CommandArgument.ToString();

        if (type == "De")

        {

            string sql1 = "delete from prd_file where id=" + Id;

            int num = executeSql.UpdateHrd_qxCount(sql1);

            if (num > 0)

            {

                band2();

            }

            else

            {

            }

        }

        else if (type == "Ed")

        {

        }

    }

    protected void DataList3_ItemCommand(object source, DataListCommandEventArgs e)

    {

        string type = e.CommandName.ToString();

        string Id = e.CommandArgument.ToString();

        if (type == "De")

        {

            string sql1 = "delete from prd_file where id=" + Id;

            int num = executeSql.UpdateHrd_qxCount(sql1);

            if (num > 0)

            {

                band3();

            }

            else

            {

            }

        }

        else if (type == "Ed")

        {

        }

    }

    protected void DataList4_ItemCommand(object source, DataListCommandEventArgs e)

    {

        string type = e.CommandName.ToString();

        string Id = e.CommandArgument.ToString();

        if (type == "De")

        {

            string sql1 = "delete from prd_file where id=" + Id;

            int num = executeSql.UpdateHrd_qxCount(sql1);

            if (num > 0)

            {

                band4();

            }

            else

            {

            }

        }

        else if (type == "Ed")

        {

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        string sql1 = "IF NOT EXISTS(select * from prd_product_zizhi WHERE comid = '"+HiddenField1.Value+"') "

 + " BEGIN  "

  + " INSERT INTO prd_product_zizhi(comid, state, endtime) VALUES('" + HiddenField1.Value + "', 1, '"+ tendtime.Text+ "') "

 + "  END "

 + "  ELSE "

 + "  BEGIN "

 + "  UPDATE prd_product_zizhi SET endtime = '" + tendtime.Text + "', state =1 WHERE comid = '" + HiddenField1.Value + "' "

 + "  END ";

       int i= executeSql.UpdateHrd_qxCount(sql1);

        if(i>0)

        {

            string zhang = "~/upload/zhang/ceshizhang.png";

            string zhangpath = Server.MapPath(zhang);

            string selsql = "select id,newimageurl from prd_file where comid='"+HiddenField1.Value+"' and isok=0";

            DataTable dt1 = executeSql.ExecuteSelectQuery(selsql);

            if (dt1 != null && dt1.Rows.Count > 0)

            {

                for(int j=0;j< dt1.Rows.Count; j++)

                {

                    string id = dt1.Rows[j]["id"].ToString();

                    string newimageurl = dt1.Rows[j]["newimageurl"].ToString();

                    string yuan = "~/"+ newimageurl;

                    string yuanpath = Server.MapPath(yuan);

                    ImgWater iw = new ImgWater();

                    iw.gaizhang(yuanpath, zhangpath);

                    string newimageurl1 = newimageurl;

                    string daizhang= newimageurl1.Replace("yasuoImage_", "zhangImage_");

                    executeSql.UpdateHrd_qxCount("update prd_file set newimageurl='"+ daizhang + "',isok=1 where id="+id);

                }

            }

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('成功!');</script>");

            //Response.Write("<Script>alert('成功!');history.go(-2);</Script>");

        }else

        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('失敗!');</script>");

            //Response.Write("<Script>alert('失敗!');history.go(-2);</Script>");

        }

    }

//圖檔統一處理代碼,寬度大于1500像素改成1500,小于1500的不處理,處理後圖檔分辨率是96

    protected void yasuo(string sFile, float w, float h)

    {

        string sFile2 = sFile;

        string dFile = sFile2.Replace("Image_", "yasuoImage_");

        int flag = 100;

        float w2 = w;

        float h2 = h;

        if (w > 1500.0)

        {

            w2 = w * 1500.0f / w;

            h2 = h * 1500.0f / w;

        }

        GetPicThumbnail(sFile, dFile, (int)(w2), (int)(h2), 100);

    }

    /// 壓縮圖檔公用方法    

    /// <param name="sFile">原圖檔</param>    

    /// <param name="dFile">壓縮後儲存位置</param>    

    /// <param name="dHeight">高度</param>    

    /// <param name="dWidth"></param>    

    /// <param name="flag">壓縮品質(數字越小壓縮率越高) 1-100</param>    

    /// <returns></returns>    

    protected static bool GetPicThumbnail(string sFile, string dFile, int dWidth, int dHeight, int flag)

    {

        System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);

        ImageFormat tFormat = iSource.RawFormat;

        int sW = 0, sH = 0;

        //按比例縮放  

        Size tem_size = new Size(iSource.Width, iSource.Height);

        if (tem_size.Width > dHeight || tem_size.Width > dWidth)

        {

            if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))

            {

                sW = dWidth;

                sH = (dWidth * tem_size.Height) / tem_size.Width;

            }

            else

            {

                sH = dHeight;

                sW = (tem_size.Width * dHeight) / tem_size.Height;

            }

        }

        else

        {

            sW = tem_size.Width;

            sH = tem_size.Height;

        }

        Bitmap ob = new Bitmap(dWidth, dHeight);

        Graphics g = Graphics.FromImage(ob);

        g.Clear(Color.WhiteSmoke);

        g.CompositingQuality = CompositingQuality.HighQuality;

        g.SmoothingMode = SmoothingMode.HighQuality;

        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

        g.Dispose();

        //以下代碼為儲存圖檔時,設定壓縮品質    

        EncoderParameters ep = new EncoderParameters();

        long[] qy = new long[1];

        qy[0] = flag;//設定壓縮的比例1-100    

        EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

        ep.Param[0] = eParam;

        try

        {

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

            ImageCodecInfo jpegICIinfo = null;

            for (int x = 0; x < arrayICI.Length; x++)

            {

                if (arrayICI[x].FormatDescription.Equals("JPEG"))

                {

                    jpegICIinfo = arrayICI[x];

                    break;

                }

            }

            if (jpegICIinfo != null)

            {

                ob.Save(dFile, jpegICIinfo, ep);//dFile是壓縮後的新路徑    

            }

            else

            {

                ob.Save(dFile, tFormat);

            }

            return true;

        }

        catch

        {

            return false;

        }

        finally

        {

            iSource.Dispose();

            ob.Dispose();

        }

    }

}

3、相關公共類,加水印公共類

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

using System.IO;

using System.Drawing.Imaging;

/// <summary>

///ImgWater 的摘要說明

/// </summary>

public class ImgWater

{

    public ImgWater()

    {

        //

        //TODO: 在此處添加構造函數邏輯

        //

    }

    public void gaizhang(string yuanpath,string zhangpath)

    {

        string yuanpath1 = yuanpath;

        string daizhangpath = yuanpath1.Replace("yasuoImage_", "zhangImage_");

        zzsImgWater(yuanpath, zhangpath, daizhangpath, 0, 1, 500);

    }

    /// <summary>

     /// 圖檔水印

     /// </summary>

     /// <param name="ImgFile">原圖檔案位址</param>

     /// <param name="WaterImg">水印圖檔位址</param>

     /// <param name="sImgPath">水印圖檔儲存位址</param>

     /// <param name="Alpha">水印透明度設定</param>

     /// <param name="iScale">水印圖檔在原圖上的顯示比例</param>

     /// <param name="intDistance">水印圖檔在原圖上的邊距确定,以圖檔的右邊和下邊為準,當設定的邊距超過一定大小後參數會自動失效</param>

    public bool zzsImgWater(

   string ImgFile

   , string WaterImg

   , string sImgPath

   , float Alpha

   , float iScale

   , int intDistance

   )

    {

        try

        {

            //裝載圖檔

            FileStream fs = new FileStream(ImgFile, FileMode.Open);

            BinaryReader br = new BinaryReader(fs);

            byte[] bytes = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            MemoryStream ms = new MemoryStream(bytes);

            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

            //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

            int imgPhotoWidth = imgPhoto.Width;

            int imgPhotoHeight = imgPhoto.Height;

            System.Drawing.Image imgWatermark = new Bitmap(WaterImg);

            int imgWatermarkWidth = imgWatermark.Width;

            int imgWatermarkHeight = imgWatermark.Height;

            //計算水印圖檔尺寸

            decimal aScale = Convert.ToDecimal(iScale);

            decimal pScale = 0.05M;

            decimal MinScale = aScale - pScale;

            decimal MaxScale = aScale + pScale;

            int imgWatermarkWidthNew = imgWatermarkWidth;

            int imgWatermarkHeightNew = imgWatermarkHeight;

            if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth >= imgPhotoHeight)

                if (imgWatermarkWidth > imgWatermarkHeight)

                    if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale))

                    {

                    }

                    else

                    {

                        imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                        imgWatermarkHeightNew = Convert.ToInt32((imgPhotoWidth * aScale / imgWatermarkWidth) * imgWatermarkHeight);

                    }

                else

                if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale))

                {

                }

                else

                {

                    imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                    imgWatermarkWidthNew = Convert.ToInt32((imgPhotoHeight * aScale / imgWatermarkHeight) * imgWatermarkWidth);

                }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth >= imgWatermarkHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            //if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth <= imgPhotoHeight)

               //if (imgWatermarkWidth*2 >= imgWatermarkHeight) {

                //    if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale))

                //    {

                //    }

                //    else

                //    {

                //        imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                //        imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

                //    }

                //}

                //else

                //{ 

                //if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale))

                //{

                //}

                //else

                //{

                //    imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                //    imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

                //}

                //}

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth <= imgWatermarkHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            //将原圖畫出來

            Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(96, 96);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);

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

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

            gbmPhoto.Clear(Color.White);

            gbmPhoto.DrawImage(

            imgPhoto

            , new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight)

            , 0

            , 0

            , imgPhotoWidth

            , imgPhotoHeight

            , GraphicsUnit.Pixel

            );

            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics gWatermark = Graphics.FromImage(bmWatermark);

            //指定高品質顯示水印圖檔品質

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

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

            ImageAttributes imageAttributes = new ImageAttributes();

            //設定兩種顔色,達到合成效果

            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);

            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            //用矩陣設定水印圖檔透明度

            float[][] colorMatrixElements = {

new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},

new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},

new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},

new float[] {0.0f, 0.0f, 0.0f, Alpha, 0.0f},

new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}

};

            System.Drawing.Imaging.ColorMatrix wmColorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            //确定水印邊距

            int xPos = imgPhotoWidth - imgWatermarkWidthNew;

            int yPos = imgPhotoHeight - imgWatermarkHeightNew;

            int xPosOfWm = 0;

            int yPosOfWm = 0;

            if (xPos > intDistance)

                xPosOfWm = xPos - intDistance;

            else

                xPosOfWm = xPos;

            if (yPos > intDistance)

                yPosOfWm = yPos - intDistance;

            else

                yPosOfWm = yPos;

            gWatermark.DrawImage(

            imgWatermark

            , new Rectangle(xPosOfWm, yPosOfWm, imgWatermarkWidthNew, imgWatermarkHeightNew)

            , 0

            , 0

            , imgWatermarkWidth

            , imgWatermarkHeight

            , GraphicsUnit.Pixel

            //, imageAttributes

            );

            imgPhoto = bmWatermark;

            //以jpg格式儲存圖檔

            imgPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //銷毀對象

            gbmPhoto.Dispose();

            gWatermark.Dispose();

            imgPhoto.Dispose();

            imgWatermark.Dispose();

            return true;

        }

        catch

        {

            return false;

        }

    }

    /** <summary>

         /// 文字水印

         /// </summary>

         /// <param name="ImgFile">原圖檔案位址</param>

         /// <param name="TextFont">水印文字</param>

         /// <param name="sImgPath">文字水印圖檔儲存位址</param>

         /// <param name="hScale">高度位置</param>

         /// <param name="widthFont">文字塊在圖檔中所占寬度比例</param>

         /// <param name="Alpha">文字透明度 其數值的範圍在0到255</param>

    public bool zzsTextWater(

   string ImgFile

   , string TextFont

   , string sImgPath

   , float hScale

   , float widthFont

   , int Alpha

   )

    {

        try

        {

            FileStream fs = new FileStream(ImgFile, FileMode.Open);

            BinaryReader br = new BinaryReader(fs);

            byte[] bytes = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            MemoryStream ms = new MemoryStream(bytes);

            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

            //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

            int imgPhotoWidth = imgPhoto.Width;

            int imgPhotoHeight = imgPhoto.Height;

            Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);

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

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

            gbmPhoto.DrawImage(

            imgPhoto

            , new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight)

            , 0

            , 0

            , imgPhotoWidth

            , imgPhotoHeight

            , GraphicsUnit.Pixel

            );

            //建立字型大小的數組,循環找出适合圖檔的水印字型

            //int[] sizes = new int[] { 1000, 800, 700, 650, 600, 560, 540, 500, 450, 400, 380, 360, 340, 320, 300, 280, 260, 240, 220, 200, 180, 160, 140, 120, 100, 80, 72, 64, 48, 32, 28, 26, 24, 20, 28, 16, 14, 12, 10, 8, 6, 4, 2 };

            int[] sizes = new int[] { 28, 26, 24, 20, 16, 14, 12 };

            System.Drawing.Font crFont = null;

            System.Drawing.SizeF crSize = new SizeF();

            for (int i = 0; i < 7; i++)

            {

                crFont = new Font("微軟雅黑", sizes[i], FontStyle.Bold);

                crSize = gbmPhoto.MeasureString(TextFont, crFont);

                if ((ushort)crSize.Width < (ushort)imgPhotoWidth * widthFont)

                    break;

            }

            //設定水印字型的位置

            //int yPixlesFromBottom = (int)(imgPhotoHeight * hScale);

            //float yPosFromBottom = ((imgPhotoHeight - yPixlesFromBottom) - (crSize.Height / 2));

            //float xCenterOfImg = (imgPhotoWidth * 1 / 2);

            float yPosFromBottom = imgPhotoHeight * 0.85f;

            float xCenterOfImg = imgPhotoWidth * 0.8f;

            //if (xCenterOfImg<crSize.Height)

            // xCenterOfImg = (imgPhotoWidth * (1 - (crSize.Height)/ imgPhotoWidth));

            System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();

            StrFormat.Alignment = System.Drawing.StringAlignment.Center;

            //

            System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 0, 0, 0));

            gbmPhoto.DrawString(

            TextFont

            , crFont

            , semiTransBrush2

            , new System.Drawing.PointF(xCenterOfImg + 1, yPosFromBottom + 1)

            , StrFormat

            );

            System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 255, 255, 255));

            //gbmPhoto.FillRectangle(semiTransBrush2, new RectangleF(new PointF(xCenterOfImg - crSize.Width / 2, yPosFromBottom - 4), crSize));

            gbmPhoto.DrawString(

         TextFont

         , crFont

         , semiTransBrush

         , new System.Drawing.PointF(xCenterOfImg, yPosFromBottom)

         , StrFormat

         );

            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            gbmPhoto.Dispose();

            imgPhoto.Dispose();

            bmPhoto.Dispose();

            return true;

        }

        catch

        {

            return false;

        }

    }

    /** <summary>

         /// 文字和Logo圖檔水印

         /// </summary>

         /// <param name="ImgFile">原圖檔案位址</param>

         /// <param name="WaterImg">水印圖檔位址</param>

         /// <param name="TextFont">水印文字資訊</param>

         /// <param name="sImgPath">生存水印圖檔後的儲存位址</param>

         /// <param name="ImgAlpha">水印圖檔的透明度</param>

         /// <param name="imgiScale">水印圖檔在原圖上的顯示比例</param>

         /// <param name="intimgDistance">水印圖檔在原圖上的邊距确定,以圖檔的右邊和下邊為準,當設定的邊距超過一定大小後參數會自動失效</param>

         /// <param name="texthScale">水印文字高度位置,從圖檔底部開始計算,0-1</param>

         /// <param name="textwidthFont">文字塊在圖檔中所占寬度比例 0-1</param>

         /// <param name="textAlpha">文字透明度 其數值的範圍在0到255</param>

    public void zzsImgTextWater(

   string ImgFile

   , string WaterImg

   , string TextFont

   , string sImgPath

   , float ImgAlpha

   , float imgiScale

   , int intimgDistance

   , float texthScale

   , float textwidthFont

   , int textAlpha

   )

    {

        try

        {

            FileStream fs = new FileStream(ImgFile, FileMode.Open);

            BinaryReader br = new BinaryReader(fs);

            byte[] bytes = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            MemoryStream ms = new MemoryStream(bytes);

            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

            //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

            int imgPhotoWidth = imgPhoto.Width;

            int imgPhotoHeight = imgPhoto.Height;

            Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);

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

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

            gbmPhoto.DrawImage(

            imgPhoto

            , new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight)

            , 0

            , 0

            , imgPhotoWidth

            , imgPhotoHeight

            , GraphicsUnit.Pixel

            );

            //建立字型大小的數組,循環找出适合圖檔的水印字型

            int[] sizes = new int[] { 1000, 800, 700, 650, 600, 560, 540, 500, 450, 400, 380, 360, 340, 320, 300, 280, 260, 240, 220, 200, 180, 160, 140, 120, 100, 80, 72, 64, 48, 32, 28, 26, 24, 20, 28, 16, 14, 12, 10, 8, 6, 4, 2 };

            System.Drawing.Font crFont = null;

            System.Drawing.SizeF crSize = new SizeF();

            for (int i = 0; i < 43; i++)

            {

                crFont = new Font("arial", sizes[i], FontStyle.Bold);

                crSize = gbmPhoto.MeasureString(TextFont, crFont);

                if ((ushort)crSize.Width < (ushort)imgPhotoWidth * textwidthFont)

                    break;

            }

            //設定水印字型的位置

            int yPixlesFromBottom = (int)(imgPhotoHeight * texthScale);

            float yPosFromBottom = ((imgPhotoHeight - yPixlesFromBottom) - (crSize.Height / 2));

            float xCenterOfImg = (imgPhotoWidth * 1 / 2);

            System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();

            StrFormat.Alignment = System.Drawing.StringAlignment.Center;

            //

            System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(Color.FromArgb(textAlpha, 0, 0, 0));

            gbmPhoto.DrawString(

            TextFont

            , crFont

            , semiTransBrush2

            , new System.Drawing.PointF(xCenterOfImg + 1, yPosFromBottom + 1)

            , StrFormat

            );

            System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(Color.FromArgb(textAlpha, 255, 255, 255));

            gbmPhoto.DrawString(

            TextFont

            , crFont

            , semiTransBrush

            , new System.Drawing.PointF(xCenterOfImg, yPosFromBottom)

            , StrFormat

            );

            System.Drawing.Image imgWatermark = new Bitmap(WaterImg);

            int imgWatermarkWidth = imgWatermark.Width;

            int imgWatermarkHeight = imgWatermark.Height;

            //計算水印圖檔尺寸

            decimal aScale = Convert.ToDecimal(imgiScale);

            decimal pScale = 0.05M;

            decimal MinScale = aScale - pScale;

            decimal MaxScale = aScale + pScale;

            int imgWatermarkWidthNew = imgWatermarkWidth;

            int imgWatermarkHeightNew = imgWatermarkHeight;

            if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth >= imgPhotoHeight)

                if (imgWatermarkWidth > imgWatermarkHeight)

                    if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale))

                    {

                    }

                    else

                    {

                        imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                        imgWatermarkHeightNew = Convert.ToInt32((imgPhotoWidth * aScale / imgWatermarkWidth) * imgWatermarkHeight);

                    }

                else

                if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale))

                {

                }

                else

                {

                    imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                    imgWatermarkWidthNew = Convert.ToInt32((imgPhotoHeight * aScale / imgWatermarkHeight) * imgWatermarkWidth);

                }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth >= imgWatermarkHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth <= imgPhotoHeight)

                if (imgWatermarkWidth > imgWatermarkHeight)

                    if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale))

                    {

                    }

                    else

                    {

                        imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                        imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

                    }

                else

                if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale))

                {

                }

                else

                {

                    imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                    imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

                }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth <= imgWatermarkHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight)

            {

                imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);

                imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight);

            }

            if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight)

            {

                imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale);

                imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth);

            }

            //将原圖畫出來

            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics gWatermark = Graphics.FromImage(bmWatermark);

            //指定高品質顯示水印圖檔品質

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

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

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();

            //設定兩種顔色,達到合成效果

            System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);

            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            //用矩陣設定水印圖檔透明度

            float[][] colorMatrixElements = {

new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},

new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},

new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},

new float[] {0.0f, 0.0f, 0.0f, ImgAlpha, 0.0f},

new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}

};

            System.Drawing.Imaging.ColorMatrix wmColorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            //确定水印邊距

            int xPos = imgPhotoWidth - imgWatermarkWidthNew;

            int yPos = imgPhotoHeight - imgWatermarkHeightNew;

            int xPosOfWm = 0;

            int yPosOfWm = 0;

            if (xPos > intimgDistance)

                xPosOfWm = xPos - intimgDistance;

            else

                xPosOfWm = xPos;

            if (yPos > intimgDistance)

                yPosOfWm = yPos - intimgDistance;

            else

                yPosOfWm = yPos;

            gWatermark.DrawImage(

            imgWatermark

            , new Rectangle(xPosOfWm, yPosOfWm, imgWatermarkWidthNew, imgWatermarkHeightNew)

            , 0

            , 0

            , imgWatermarkWidth

            , imgWatermarkHeight

            , GraphicsUnit.Pixel

            , imageAttributes

            );

            imgPhoto = bmWatermark;

            //以jpg格式儲存圖檔

            imgPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //銷毀對象

            gbmPhoto.Dispose();

            gWatermark.Dispose();

            bmPhoto.Dispose();

            imgPhoto.Dispose();

            imgWatermark.Dispose();

        }

        catch

        {

        }

    }

    /** <summary>

         /// 縮略圖

         /// </summary>

         /// <param name="ImgFile">原圖檔案位址</param>

         /// <param name="sImgPath">縮略圖儲存位址</param>

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

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

         /// <param name="BgColor">縮略圖背景顔色,注意,背景顔色隻能指定KnownColor中的值,如blue,red,green等</param>

    public bool zzsResizeImg(string ImgFile, string sImgPath, int ResizeWidth, int ResizeHeight, string BgColor)

    {

        try

        {

            FileStream fs = new FileStream(ImgFile, FileMode.Open);

            BinaryReader br = new BinaryReader(fs);

            byte[] bytes = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            MemoryStream ms = new MemoryStream(bytes);

            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

            //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

            int imgPhotoWidth = imgPhoto.Width;

            int imgPhotoHeight = imgPhoto.Height;

            int startX = 0;

            int StartY = 0;

            int NewWidth = 0;

            int NewHeight = 0;

            if (imgPhotoWidth >= ResizeWidth && imgPhotoHeight >= ResizeHeight)

            {

                NewWidth = ResizeWidth;

                NewHeight = Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(ResizeWidth) / Convert.ToDecimal(imgPhotoWidth), 10));

                startX = 0;

                StartY = (ResizeHeight - NewHeight) / 2;

            }

            if (ResizeWidth > imgPhotoWidth && ResizeHeight < imgPhotoHeight)

            {

                NewHeight = ResizeHeight;

                NewWidth = Convert.ToInt32(imgPhotoWidth * Math.Round(Convert.ToDecimal(ResizeHeight) / Convert.ToDecimal(imgPhotoHeight), 10));

                startX = (ResizeWidth - NewWidth) / 2;

                StartY = 0;

            }

            if (ResizeWidth < imgPhotoWidth && ResizeHeight > imgPhotoHeight)

            {

                NewWidth = ResizeWidth;

                NewHeight = Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(ResizeWidth) / Convert.ToDecimal(imgPhotoWidth), 10));

                startX = 0;

                StartY = (ResizeHeight - NewHeight) / 2;

            }

            if (imgPhotoWidth < ResizeWidth && imgPhotoHeight < ResizeHeight)

            {

                NewWidth = imgPhotoWidth;

                NewHeight = imgPhotoHeight;

                startX = (ResizeWidth - imgPhotoWidth) / 2;

                StartY = (ResizeHeight - imgPhotoHeight) / 2;

            }

            //計算縮放圖檔尺寸

            Bitmap bmPhoto = new Bitmap(ResizeWidth, ResizeHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);

            gbmPhoto.Clear(Color.FromName(BgColor));

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

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

            gbmPhoto.DrawImage(

            imgPhoto

            , new Rectangle(startX, StartY, NewWidth, NewHeight)

            , new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight)

            , GraphicsUnit.Pixel

            );

            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            imgPhoto.Dispose();

            gbmPhoto.Dispose();

            bmPhoto.Dispose();

            ms.Close();

            return true;

        }

        catch

        {

            return false;

        }

    }

    /** <summary>

         /// 圖檔剪切

         /// </summary>

         /// <param name="ImgFile">原圖檔案位址</param>

         /// <param name="sImgPath">縮略圖儲存位址</param>

         /// <param name="PointX">剪切起始點 X坐标</param>

         /// <param name="PointY">剪切起始點 Y坐标</param>

         /// <param name="CutWidth">剪切寬度</param>

         /// <param name="CutHeight">剪切高度</param>

    public bool zzsCutImg(string ImgFile, string sImgPath, int PointX, int PointY, int CutWidth, int CutHeight)

    {

        FileStream fs = new FileStream(ImgFile, FileMode.Open);

        BinaryReader br = new BinaryReader(fs);

        try

        {

            byte[] bytes = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            MemoryStream ms = new MemoryStream(bytes);

            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

            //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

            //此處隻能用filestream,用 System.Drawing.Image則會報多過程序通路檔案的錯誤,會鎖定檔案

            Bitmap bmPhoto = new Bitmap(CutWidth, CutHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);

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

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

            gbmPhoto.DrawImage(

            imgPhoto

            , new Rectangle(0, 0, CutWidth, CutHeight)

            , new Rectangle(PointX, PointY, CutHeight, CutHeight)

            , GraphicsUnit.Pixel

            );

            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            imgPhoto.Dispose();

            gbmPhoto.Dispose();

            bmPhoto.Dispose();

            ms.Close();

            return true;

        }

        catch

        {

            return false;

        }

        finally

        {

        }

    }

}

繼續閱讀