asp.net如何在图片上加水印文字具体实现

第一步,添加一个一般处理程序(Handler),本例是ImageHandler

代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mime;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class ImageHandler : IHttpHandler
{
    public ImageHandler()
    {
    }

public string GetContentType(String path)
    {
        switch (Path.GetExtension(path))
        {
            case ".bmp": return "Image/bmp";
            case ".gif": return "Image/gif";
            case ".jpg": return "Image/jpeg";
            case ".png": return "Image/png";
            default: break;
        }
        return String.Empty;
    }

public ImageFormat GetImageFormat(String path)
    {
        switch (Path.GetExtension(path).ToLower())
        {
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
            default: return null;
        }
    }

protected byte[] WatermarkImage(HttpContext context)
    {

byte[] imageBytes = null;
        if (File.Exists(context.Request.PhysicalPath))
        {
            // Normally you'd put this in a config file somewhere.
            string watermark = "世复检测";

Image image = Image.FromFile(context.Request.PhysicalPath);

Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
            {
                // Graphic is not a Indexed (GIF) image
                graphic = Graphics.FromImage(image);
            }
            else
            {
                /* Cannot create a graphics object from an indexed (GIF) image.
                 * So we're going to copy the image into a new bitmap so
                 * we can work with it. */
                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);

// Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;

Font myFont = new Font("Arial", 15);
            SolidBrush brush = new SolidBrush(Color.FromArgb(255, Color.Red));

/* This gets the size of the graphic so we can determine
             * the loop counts and placement of the watermarked text. */
            SizeF textSize = graphic.MeasureString(watermark, myFont);

//// Write the text across the image.
            //for (int y = 0; y < image.Height; y++)
            //{
            //    for (int x = 0; x < image.Width; x++)
            //    {
            //        PointF pointF = new PointF(x, y);
            //        graphic.DrawString(watermark, myFont, brush, pointF);
            //        x += Convert.ToInt32(textSize.Width);
            //    }
            //    y += Convert.ToInt32(textSize.Height);
            //}

// Write the text at the right bottom of the image.
            for (int y = image.Height-25; y < image.Height; y++)
            {
                for (int x = image.Width-100; x < image.Width; x++)
                {
                    PointF pointF = new PointF(x, y);
                    graphic.DrawString(watermark, myFont, brush, pointF);
                    x += Convert.ToInt32(textSize.Width);
                }
                y += Convert.ToInt32(textSize.Height);
            }

using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, GetImageFormat(context.Request.PhysicalPath));
                imageBytes = memoryStream.ToArray();
            }

}
        return imageBytes;
    }

#region IHttpHandler Members

public bool IsReusable
    {
        get { return false; }
    }

public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();
        context.Response.ContentType = GetContentType(context.Request.PhysicalPath);
        byte[] imageBytes = WatermarkImage(context);
        if (imageBytes != null)
        {
            context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
        }
        else
        {
            // No bytes = no image which equals NO FILE.   
            // Therefore send a 404 - not found response.
            context.Response.StatusCode = 404;
        }
        context.Response.End();
    }

#endregion
}

第二步,在web.config里添加如下代码:

代码如下:

<httpHandlers>
      <!--<add verb="GET" type="ImageHandler" path="*.jpg,*.png,*.gif,*.bmp"/>-->
      <add verb="GET" type="ImageHandler" path="Uploads/*/*.jpg"/>     
    </httpHandlers>

(0)

相关推荐

  • ASP.NET简单好用功能齐全图片上传工具类(水印、缩略图、裁剪等)

    使用方法: UploadImage ui = new UploadImage(); /***可选参数***/ ui.SetWordWater = "哈哈";//文字水印 // ui.SetPicWater = Server.MapPath("2.png");//图片水印(图片和文字都赋值图片有效) ui.SetPositionWater = 4;//水印图片的位置 0居中.1左上角.2右上角.3左下角.4右下角 ui.SetSmallImgHeight = &quo

  • ASP.NET实现上传图片并生成缩略图的方法

    本文实例讲述了ASP.NET实现上传图片并生成缩略图的方法.分享给大家供大家参考,具体如下: protected void bt_upload_Click(object sender, EventArgs e) { //检查上传文件的格式是否有效 if (this.UploadFile.PostedFile.ContentType.ToLower().IndexOf("image") < 0) { Response.Write("上传图片格式无效!"); re

  • asp.net 添加水印的代码(已测试)

    加水印的功能代码如下所示 复制代码 代码如下: /// <summary> /// 图片修改类,主要是用来保护图片版权的,版权归原作者所有 /// </summary> public class picmark { #region "member fields" private string modifyImagePath = null; private string drawedImagePath = null; private int rightSpace;

  • asp.net文件上传功能(单文件,多文件,自定义生成缩略图,水印)

    前言 上传功能,是大家经常用到了,可能每一个项目都可以会用到.网上到处都有上传功能的代码.比我写的好的有很多.我这里也仅是分享我的代码. 功能实现点 1.单个文件上传: 2.多个文件上传: 3.对于图片等类型的图像,可以自定义生成缩略图大小: 4.文件服务器扩展. 模式 主要使用的是"模板方法"的设计模式. 本文章的功能优缺点 1.可以自定义生成缩略图的大小,任意定义.对于像微生活运动户外商城(http://sports.8t8x.com/) .淘宝网等的网站,他们需要上传大量的商品图

  • Asp.net 文件上传类(取得文件后缀名,保存文件,加入文字水印)

    复制代码 代码如下: 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; usi

  • ASP.Net 上传图片并生成高清晰缩略图

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DT

  • asp.net图片上传生成缩略图的注意事项

    bitmap.Save(imgPath,ImageFormat.Jpeg);   //这是保存缩略图的一段代码,其中的ImageFormat.Jpeg一定不能省略,即使你保存的文件本来就是jpg格式的,也不能去掉.因为如果去掉的话,生成的缩略图比原始图片还要大! //另外,imgPath必须首先创建,否则会产生GDI+的一般性错误. path=System.Web.HttpContext.Current.Server.MapPath(path); 使用if(!System.IO.Director

  • asp.net 上传图片并同时生成缩略图的代码

    复制代码 代码如下: <%@ Page Language="C#" ResponseEncoding="gb2312" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Drawing" %> <%@ I

  • asp.net上传图片并作处理水印与缩略图的实例代码

    方法类: 复制代码 代码如下: upFileClass.cs 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.HtmlC

  • asp.net实现生成缩略图及给原始图加水印的方法示例

    本文实例讲述了asp.net实现生成缩略图及给原始图加水印的方法.分享给大家供大家参考,具体如下: using System.IO; using System.Drawing.Imaging; private void Button1_ServerClick(object sender, System.EventArgs e) { Graphics g=null; System.Drawing.Image upimage=null; System.Drawing.Image thumimg=nu

  • asp.net下GDI+的一些常用应用(水印,文字,圆角处理)技巧

    public class MyGDI {     public static void CreateWatermark(string sSrcFilePath, string sDstFilePath, string sText1, string sColor1, string sSize1, string sFont1, string sText2, string sColor2, string sSize2, string sFont2, string sBgColor, string sT

随机推荐