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

所属分类: 网络编程 / ASP.NET 阅读数: 1830
收藏 0 赞 0 分享

第一步,添加一个一般处理程序(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>

更多精彩内容其他人还在看

开源跨平台运行服务插件TaskCore.MainForm

这篇文章主要为大家详细介绍了开源跨平台运行服务插件TaskCore.MainForm的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

CKEditor自定义按钮插入服务端图片

这篇文章主要为大家详细介绍了CKEditor自定义按钮插入服务端图片的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Asp.net Web Api实现图片点击式图片验证码功能

现在验证码的形式越来越丰富,今天要实现的是在点击图片中的文字来进行校验的验证码。下面通过本文给大家分享Asp.net Web Api实现图片点击式图片验证码功能,需要的的朋友参考下吧
收藏 0 赞 0 分享

WPF实现ScrollViewer滚动到指定控件处

这篇文章主要为大家详细介绍了WPF实现ScrollViewer滚动到指定控件处,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

WPF实现带全选复选框的列表控件

这篇文章主要为大家详细介绍了WPF实现带全选复选框的列表控件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Asp.net MVC 中利用jquery datatables 实现数据分页显示功能

这篇文章主要介绍了Asp.net MVC 中利用jquery datatables 实现数据分页显示功能,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

asp.net 利用NPOI导出Excel通用类的方法

本篇文章主要介绍了asp.net 利用NPOI导出Excel通用类的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

VS2015自带LocalDB数据库用法详解

这篇文章主要为大家详细介绍了VS2015自带LocalDB数据库的用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SignalR Self Host+MVC等多端消息推送服务(一)

这篇文章主要为大家详细介绍了SignalR Self Host+MVC等多端消息推送服务,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SignalR Self Host+MVC等多端消息推送服务(二)

这篇文章主要为大家详细介绍了SignalR Self Host+MVC等多端消息推送服务的第二篇,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多