为图片添加水印

 添加水印图片的类

using System;using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Drawing.Drawing2D;
using System.Web.UI.WebControls.WebParts;


/*利用.net中System.Drawing命名空间下的常用类我们就可以轻松的为图片添加文字水印和图片水印,
 * 并且可以自定义水印文字和水印图片的大小、位置、颜色、透明度等等!对于jpg或者png等图片,
 * 可以直接通过Graphics g= Graphics.FromImage(image)来获得Graphics对象,但对于gif图片,
 * 通过这种方法无法获得Graphics对象,解决这个问题的方法是首先根据.gif文件的大小生成一个位图作图区,
 * 然后将原图复制到作图区,做进行处理*/
/// <summary>  
///ImageHandler 的摘要说明  
/// 首先是一个制作水印的类:ImageHandler,然后在Web.Config文件中加入如下一句话
///<httpHandlers>
///<!--图片水印-->
///<add verb="*" path="Images/*.jpg" type="ImageHandler"/>
///</httpHandlers>
/// </summary>  
public class ImageHandlers : IHttpHandler
{
    private const string waterMark_URL = "~/images/firefox.png";//水印图
    private const string defaultImage_URL = "~/images/20090618091638.jpg";//没有图片时默认显示的图片(暂无图片不加水印)
    private float Transparency = 1;
    private int MarkX = 0;
    private int MarkY = 0;

    public ImageHandlers()
    {
        //  
        //TODO: 在此处添加构造函数逻辑  
        //  
    }

    public void ProcessRequest(HttpContext context)
    {
        //得到请求路径
            string url = context.Request.Url.AbsoluteUri;
            bool IsInterestUrl;
        System.Drawing.Image img;
        //加载文件  
        img = Image.FromFile(context.Request.PhysicalPath);
      
        if (!Path.GetExtension(context.Request.PhysicalPath).ToLower().Equals(".gif") )
        {
            System.Drawing.Image ImageConver;
     
            是否包含图片路径
            // IsInterestUrl = url.Contains("admin");
            //if (!IsInterestUrl)
            //{
            //    ImageConver = System.Drawing.Image.FromFile(context.Request.PhysicalPath);
            //    ImageConver.Save(context.Response.OutputStream, ImageConver.RawFormat);
            //    ImageConver.Dispose();
            //    return;
            //}

            if (File.Exists(context.Request.PhysicalPath))
            {
                //加载文件  
                ImageConver = Image.FromFile(context.Request.PhysicalPath);
                //加载水印图片  
                Image waterMark = Image.FromFile(context.Request.MapPath(waterMark_URL));
                //重新画布  
                Graphics g = Graphics.FromImage(ImageConver);
                g.DrawImage(waterMark, new Rectangle(ImageConver.Width - waterMark.Width, ImageConver.Height - waterMark.Height, waterMark.Width, waterMark.Height), 0, 0, waterMark.Width, waterMark.Height, GraphicsUnit.Pixel);
                g.Dispose();
                waterMark.Dispose();
            }
            else
            {
                ImageConver = Image.FromFile(context.Request.MapPath(defaultImage_URL));
            }

            //设置输出格式  
            context.Response.ContentType = "image/jpeg";
            ImageConver.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            ImageConver.Dispose();
            context.Response.End();
            return;
        }
        else
        {
            是否包含图片路径
            // IsInterestUrl = url.Contains("admin");
            //if (!IsInterestUrl)
            //{
            //    img = System.Drawing.Image.FromFile(context.Request.PhysicalPath);
            //    img.Save(context.Response.OutputStream, img.RawFormat);
            //    img.Dispose();
            //    return;
            //}
            //获得水印图像
            Image markImg = Image.FromFile((context.Request.MapPath(waterMark_URL)));
            //创建颜色矩阵
            float[][] ptsArray ={
           new float[] {1, 0, 0, 0, 0},
           new float[] {0, 1, 0, 0, 0},
           new float[] {0, 0, 1, 0, 0},
           new float[] {0, 0, 0, this.Transparency, 0}, //注意:此处为0.0f为完全透明,1.0f为完全不透明
           new float[] {0, 0, 0, 0, 1}};
            ColorMatrix colorMatrix = new ColorMatrix(ptsArray);
            //新建一个Image属性
            ImageAttributes imageAttributes = new ImageAttributes();
            //将颜色矩阵添加到属性
            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default,
             ColorAdjustType.Default);
            //生成位图作图区
            Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb);
            //设置分辨率
            newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
            //创建Graphics
            Graphics g = Graphics.FromImage(newBitmap);
            //消除锯齿
            g.SmoothingMode = SmoothingMode.AntiAlias;
            //拷贝原图到作图区
            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            //如果原图过小
            if (markImg.Width > img.Width || markImg.Height > img.Height)
            {
                System.Drawing.Image.GetThumbnailImageAbort callb = null;
                //对水印图片生成缩略图,缩小到原图得1/4
                System.Drawing.Image new_img = markImg.GetThumbnailImage(img.Width / 4, markImg.Height * img.Width / markImg.Width, callb, new System.IntPtr());
                //添加水印
                g.DrawImage(new_img, new Rectangle(img.Width - new_img.Width, img.Height - new_img.Height, new_img.Width, new_img.Height), 0, 0, new_img.Width, new_img.Height, GraphicsUnit.Pixel, imageAttributes);
                //释放缩略图
                new_img.Dispose();
                //释放Graphics
                g.Dispose();
                //将生成得图片读入MemoryStream
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                newBitmap.Save(ms, ImageFormat.Jpeg);
                //返回新的Image对象
                img = Image.FromStream(ms);
                return img;
                newBitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                newBitmap.Dispose();
                context.Response.End();
            }
            //原图足够大
            else
            {
                //添加水印
                g.DrawImage(markImg, new Rectangle(img.Width - markImg.Width, img.Height - markImg.Height, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes);
                //释放Graphics
                g.Dispose();
                //将生成得图片读入MemoryStream
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                newBitmap.Save(ms, ImageFormat.Jpeg);
                //返回新的Image对象
                img = Image.FromStream(ms);
                newBitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                newBitmap.Dispose();
                context.Response.End();

            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

 

 

前台页面:

<body>
    <form id="form1" runat="server">
    <div>jkkjj
                  <asp:Image ID="Image3" runat="server"  ImageUrl="~/images/1_09.jpg"/>
          <asp:Image ID="Image2" runat="server"  ImageUrl="~/images/100x100-right.gif"/>
                    <asp:Image ID="Image4" runat="server"  ImageUrl="~/images/a.gif"/>
                        <asp:Image ID="Image5" runat="server"  ImageUrl="~/images/02.png"/>
    </div>
   
<%-- 

方法一:(添加水印图片):首先是一个制作水印的类:ImageHandlers,接下来,我们要做一个很关键的配置,那就是在Web.Config文件中加入如下一句话
 <httpHandlers>

<!--图片水印-->
      <add verb="*" path="Images/*.jpg,*.gif,*.png" type="ImageHandlers"/>

</httpHandlers>
在iis上的配置:主目录-配置-添加映射:可执行文件:c:/windows/microsoft.net/framework/v2.0.50727/aspnet_isapi.dll,
扩展名:需要添加水印的图片格式(与配置文件中设置的格式一致),全部动作,取消选中确认文件是否存在


方法二(添加水印字符):首先是一个制作水印的类:ShuiyinHandler,然后配置Web.Config文件
--%>
    </form>
</body>

 

 

 

添加水印字符的类

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls.WebParts;

/// <summary>
/// ShuiyinHandler 的摘要说明 添加水印文字
/// </summary>
public class ShuiyinHandler:IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        try
        {

            //得到请求路径
            string url = context.Request.Url.AbsoluteUri.ToLower();

            //获取加水印的文件路径
            //string monitorPath = ConfigurationManager.AppSettings["monitorPath"];

            //是否包含图片路径
            //bool IsInterestUrl = url.Contains(monitorPath);
            bool IsInterestUrl = url.Contains("images");
            System.Drawing.Image imgSource = null;

           

              //判断原图片是否存在
            string physicalPath = context.Request.PhysicalPath;
            if (!System.IO.File.Exists(physicalPath))
            {
                context.Response.Write("图片不存在");
                return;
            }

            //如果不是要加水印的文件或文件夹,就原样输出

            if (!IsInterestUrl)
            {
                imgSource = System.Drawing.Image.FromFile(physicalPath);
                imgSource.Save(context.Response.OutputStream, imgSource.RawFormat);
                imgSource.Dispose();
                return;
            }

            imgSource = System.Drawing.Image.FromFile(physicalPath);

            //判断是否是索引图像格式(gif格式的图片)
            if (imgSource.PixelFormat == PixelFormat.Format1bppIndexed || imgSource.PixelFormat == PixelFormat.Format4bppIndexed || imgSource.PixelFormat == PixelFormat.Format8bppIndexed)
            {

                //转成位图,这步很重要
                Bitmap bitmap = new Bitmap(imgSource.Width, imgSource.Height);

                System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);
                System.Drawing.Font font = new System.Drawing.Font("Arial Black", 10.0f, System.Drawing.FontStyle.Italic);

                //将原图画在位图上

                graphic.DrawImage(imgSource, new Point(0, 0));

                //将水印加在位图上

                graphic.DrawString("www.www.com", font, System.Drawing.Brushes.Red, new System.Drawing.PointF(imgSource.HorizontalResolution + imgSource.Width - 190, imgSource.VerticalResolution + imgSource.Height - 118));

                //将位图输入到流
                bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);

                graphic.Dispose();
                imgSource.Dispose();
                bitmap.Dispose();

            }
            else
            {

                //不是索引图像格式,直接在上面加上水印

                System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(imgSource);
               // float num= imgSource.Width / 20;
                System.Drawing.Font font = new System.Drawing.Font("Arial Black",18.0f, System.Drawing.FontStyle.Italic);
                graphic.DrawString("www.www.com", font, System.Drawing.Brushes.Red,new System.Drawing.PointF(imgSource.HorizontalResolution+imgSource.Width-290,imgSource.VerticalResolution+imgSource.Height-130));
            
                imgSource.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);


                imgSource.Dispose();
                graphic.Dispose();
            }

            //标明类型为jpg:如果不标注,IE没有问题,但Firefox会出现乱码
            context.Response.ContentType = "image/jpeg";
            context.Response.Flush();
            context.Response.End();
        }
        catch
        {
            throw;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值