用ASP.NET实现简单的文字水印
发布时间:2006-10-14 8:44:39   收集提供:gaoqian

代码如下:

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>

<%@ Page language="vb" %>

<script runat="server">
    Dim FilePath As String = Server.MapPath("FengEr.jpg")
   
    Sub Page_Load(Sender As Object, E As EventArgs)
        Dim image As System.Drawing.Image = System.Drawing.Image.FromFile( FilePath )
        Dim g As Graphics = Graphics.FromImage(image)
        g.DrawImage(image, 0, 0, image.Width, image.Height)
        Dim f As Font = new Font("华文行楷", 30)
        Dim b As Brush = new SolidBrush(Color.Green)
        Dim s As String = Request.QueryString("Str")
        g.DrawString(s, f, b, 20, 290)
        image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
        g.Dispose()
        image.Dispose()
    End Sub   
</script>


只要把这个代码存成一个aspx文件,比如Test.aspx。然后放到wwwroot里面(假设你的虚拟目录是默认的)。再做一个Test.jpg的图片,就可以在(20, 290)这个位置打印出“华文行楷”这种字体的文字了。调用方法很简单:

http://localhost/Test.aspx?Str=Dicky's Blog!

对于打印的位置和字体还有图片文件都是可以自己设定的。另外,如果出现了以英文作为参数就可以正常显示,而对于中文就无法显示的情况,是因为Asp.net的web.config设置不正确造成了,需要进行如下设置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
    <globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312"/>
    </system.web>
</configuration>

这样,就可以正常显示了。

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50