给图片加上带版权的水印

时间:2024-02-17 22:33:59
我们在网站上有些时候需要给图片加上带版权的水印,.net的Graphics类可以很轻松的实现这一点。

效果图:(图片最上端的那行字便是我们加上的版权水印了)


实现代码:
/// <summary>
    
/// 生成带版权水印的图片
    
/// </summary>
    
/// <param name="IconImg">要生成水印图片的文件地址</param>

    private void MakeWaterMark(string IconImg)
    
{
        
//定义输出位图
        Bitmap bmp = new Bitmap(640480);
        
//定义绘图对象
        Graphics g = Graphics.FromImage(bmp);
        
//描述绘图矩形区域 
        Rectangle newRect = new Rectangle(00640480);
        
//设置背景色
        g.FillRectangle(new SolidBrush(Color.White), newRect);
        
//获取要生成水印的图片
        Bitmap newBitmap = new Bitmap(IconImg);
        g.DrawImage(newBitmap, 
1616);
        
//定义水印字的字体
        Font font = new Font(
                               
"Arial"
                               
12
                               FontStyle.Bold
                            );
        
//定义水印字的格式刷
        LinearGradientBrush brush = new LinearGradientBrush(
                                                              
new Rectangle(007123), 
                                                              Color.Red,
                                                              Color.Blue, 
                                                              30f, 
                                                              
true
                                                           );
        
//给照片打上水印
        g.DrawString("copyright by test. " + System.DateTime.Now.ToShortDateString(), font, brush, 00);
        
//保存为新的输出图片
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmp.Save(ms, ImageFormat.Jpeg);

        
//输出图片
        Response.ClearContent();
        Response.ContentType 
= "image/jpeg";
        Response.BinaryWrite(ms.ToArray());
    }