用ASP.NET 处理图象:从数据库中读取图象,并在图象上加上版权信息

来源:互联网 发布:如何更换淘宝店铺头像 编辑:程序博客网 时间:2024/04/30 05:40

  我是一个ASP.NET的新手,出于对程序的热爱而自学程序设计,作为一非计算机专业人氏(我是一个小会计)常常感到学习的困难,希望得到各位大侠的帮助,以提高自己的水平,以下是我学习过程中写的一个关于数据库图象字段处理的程序,也可以说是学习笔记吧,希望得到各位的指正。

程序设计思路:

1:用ADO.NET从一个BLOB字段中读取一幅图象,方法:在图象列上执行一个SELECT语句,并使用EXCUTESCALAR方法取得结果,然后将它保存在字节数组中;
2:将图象数组写入memory strean 中,并将流读入一个Image对象中;
3:用GDI+类对图形进行处理,将版权信息写到图象相应的位置
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.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
///<summary>
///实现从SQLSERVER数据库中读取图象数据,并为图象加上版权标记,
///实现IHTTPHANDLER接口
///</summary>
public class imagehandle:IHttpHandler
{
   public imagehandle()
   {
  
   }
    #region IHttpHandler 成员
    public bool IsReusable
    {
        get { return true; }
    }
    public void ProcessRequest(HttpContext context)
    {
        int id = 1;
        bool result = Int32.TryParse(context.Request.QueryString["id"], out id);     
        string cnnstr = "Data Source=CW31;Initial Catalog=Northwind;Integrated Security=True";
        string cmdstr = "select photo from employees where employeeid=" + id;
        SqlConnection cnn = new SqlConnection(cnnstr);
        SqlCommand cmn = new SqlCommand(cmdstr, cnn);
        byte[] image = null;
        try
        {
            cnn.Open();
            image = (byte[])cmn.ExecuteScalar();
 
        }
        catch (Exception E)
        {
            throw new Exception(E.Message);
        }
        finally
        {
            cnn.Close();
        }
        if (image != null)
        {
 
          System.Drawing.Image limage = ReadImage(image);
         Bitmap bmp = new Bitmap(limage);
        Graphics g = Graphics.FromImage(bmp);
        StringFormat strfmt = new StringFormat();
        strfmt.Alignment = StringAlignment.Center;
        SolidBrush btmforcolor = new SolidBrush(Color.White);
        SolidBrush btmbaclcolor = new SolidBrush(Color.Black);
         //固定版权写入图形的位置
      SizeF textf = new SizeF();      
        string mycopright = context.Request.UserHostName;      
        Font f = new Font("黑体", 12, FontStyle.Italic);
         textf = g.MeasureString(mycopright, f);
        int bheight = bmp.Height;
        int bweght = bmp.Width;
        float theight = textf.Height;
        float tweight = textf.Width;
        float x = ((float)bweght - tweight - 3);
        float y = ((float)bheight-theight - 3);
        float w = ((float)x + tweight);
        float h = ((float)y + theight);
        RectangleF textarea = new RectangleF(x, y, w, h);
        g.FillRectangle(btmbaclcolor,textarea);
        g.DrawString(mycopright, f, btmforcolor, textarea);
        btmforcolor.Dispose();
        btmbaclcolor.Dispose();
        f.Dispose();
        g.Dispose();
  //将图象保存到输出流中
        bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }    
 
    }
//将图象字节写并成像的处理程序,将字节数组转为流,并将流形成图象
    public System.Drawing.Image ReadImage(byte[] bytes)
    {
        MemoryStream ms = new MemoryStream(bytes,78,bytes.Length-78); 
        return System.Drawing.Image.FromStream(ms);
        ms.Close();
    }
 
    #endregion
}
 
在cofig文件中注册 imagehandle
<httpHandlers>
      <add path="dbimage.axd"  type="imagehandle"  verb="*" />
    </httpHandlers>
3、使用图象处理程序例子
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span style="color: #66ccff"><span style="font-size: 36pt">Employees photo<br />
        </span>
            <table>
                <tr>
                    <td style="width: 100px">
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1"
            DataTextField="LastName" DataValueField="EmployeeID" Width="150px">
        </asp:DropDownList></td>
                    <td style="width: 100px">
                    </td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [EmployeeID], [LastName] FROM [Employees]"></asp:SqlDataSource>
                    </td>
                    <td style="width: 100px">
                    </td>
                    <td style="width: 100px">
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
        <asp:Image ID="Image1" runat="server" Height="286px" Width="409px"/></td>
                </tr>
            </table>
        <br />
        </span>
        <br />
        &nbsp;
        <br />
    </div>
    </form>
</body>
</html>
//DropDownList控件的selectitemvalue属性与IMAGE的imagurl属性相关,其程序实现如下:
 protected void Page_PreRender(object sender, EventArgs e)
    {
        string url;
        if (!IsPostBack)
        {
            url = "dbimage.axd?id=1";
        }
        else
        {
            url = string.Format("dbimage.axd?id={0}", DropDownList1.SelectedValue);
        }
        Image1.ImageUrl = url;
    }
例程实现效果
Employees photo