.NET中生成水印更好的方法

为了保护知识产权,防止资源被盗用,水印在博客、网店等场景中非常常见。

本文首先演示了基于System.Drawing.Image做正常操作。然后基于Direct2D/WIC/DirectWrite,演示了一种全新、不同的“”操作。

方法1-System.Drawing给图片加水印

System.Drawing.Image原生属于GDI的一部分,是Windows Only,但随着NuGet包System.Drawing.Common的发布,现在System.Drawing.Image已经支持linux

Install-Package System.Drawing.Common -Version 4.5.1

以下代码演示了如何从给图片加水印:

// 加水印
var watermarkedStream = new MemoryStream();
using (var img = Image.FromStream(File.OpenRead(@"D:\_\WatermarkDemo.png")))
{
using (var graphic = Graphics.FromImage(img))
{
var font = new Font("微软雅黑", 30, FontStyle.Bold, GraphicsUnit.Pixel);
var color = Color.FromArgb(128, 255, 255, 255);
var brush = new SolidBrush(color);
var point = new Point(img.Width - 130, img.Height - 50); graphic.DrawString("水印在此", font, brush, point);
img.Save(watermarkedStream, ImageFormat.Png);
}
}

效果如图(没有黄色剪头):

附:Edi.Wang做了一个NuGet包,可以轻松地配置水印参数:

方法2-Direct2D/WIC给图片加水印

Direct2D源于Windows 8/IE 10,安装IE 10之后,Windows 7也能用。Direct2D基于Direct3D,很显然,是Windows Only的。

Direct2DWindows下一代的2D渲染库,随着Direct2D一起发布的,还有Windows Imaging Component(简称WIC)和DirectWrite

相关说明和文档链接:

技术 说明 链接
Direct2D 基于硬件加速的2D图形渲染 Go
WIC 高性能图片编码、解码 Go
DirectWrite 基于硬件加速的文字渲染 Go

如果您打开链接看了一眼,就不难看出,这些技术都是基于COM的,但我们使用.NET,不是吗?

好在我们有SharpDX

SharpDX对这些DirectX技术做了封装,在这个Demo中,我们需要安装SharpDX.Direct2D1SharpDX.Mathematics两个包:

Install-Package SharpDX.Direct2D1 -Version 4.2.0
Install-Package SharpDX.Mathematics -Version 4.2.0

以下代码演示了如何使用SharpDX.Direct2D1给图片加水印:

using D2D = SharpDX.Direct2D1;
using DWrite = SharpDX.DirectWrite;
using SharpDX;
using SharpDX.IO;
using WIC = SharpDX.WIC; MemoryStream AddWatermark(Stream fileName, string watermarkText)
{
using (var wic = new WIC.ImagingFactory2())
using (var d2d = new D2D.Factory())
using (var image = CreateWicImage(wic, fileName))
using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image))
using (var dwriteFactory = new SharpDX.DirectWrite.Factory())
using (var brush = new D2D.SolidColorBrush(target, new Color(0xff, 0xff, 0xff, 0x7f)))
{
target.BeginDraw();
{
target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear);
target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
var textFormat = new DWrite.TextFormat(dwriteFactory, "微软雅黑", DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, 30.0f);
target.DrawText(watermarkText, textFormat, new RectangleF(target.Size.Width - 130, target.Size.Height - 50, int.MaxValue, int.MaxValue), brush);
}
target.EndDraw(); var ms = new MemoryStream();
SaveD2DBitmap(wic, wicBitmap, ms);
return ms;
}
} void SaveD2DBitmap(WIC.ImagingFactory wicFactory, WIC.Bitmap wicBitmap, Stream outputStream)
{
using (var encoder = new WIC.BitmapEncoder(wicFactory, WIC.ContainerFormatGuids.Png))
{
encoder.Initialize(outputStream);
using (var frame = new WIC.BitmapFrameEncode(encoder))
{
frame.Initialize();
frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height); var pixelFormat = wicBitmap.PixelFormat;
frame.SetPixelFormat(ref pixelFormat);
frame.WriteSource(wicBitmap); frame.Commit();
encoder.Commit();
}
}
} WIC.FormatConverter CreateWicImage(WIC.ImagingFactory wicFactory, Stream stream)
{
using (var decoder = new WIC.PngBitmapDecoder(wicFactory))
{
var decodeStream = new WIC.WICStream(wicFactory, stream);
decoder.Initialize(decodeStream, WIC.DecodeOptions.CacheOnLoad);
using (var decodeFrame = decoder.GetFrame(0))
{
var converter = new WIC.FormatConverter(wicFactory);
converter.Initialize(decodeFrame, WIC.PixelFormat.Format32bppPBGRA);
return converter;
}
}
}

调用方式:

File.WriteAllBytes(@"D:\_\Demo2.png", AddWatermark(File.OpenRead(@"D:\_\WatermarkDemo.png"), "水印在此").ToArray());

效果也是一切正常:

有什么区别?

System.Drawing只花了14行,Direct2D却需要整整60行!复杂程度惊人!为什么要舍简单求复杂呢?

因为System.Drawing没有硬件加速,而且生成的图片也没有反走样(Anti-aliasing),这导致使用System.Drawing相比之下较慢,而且生成图片的效果稍差:

很明显可以看出,Direct2D生成的图片更平滑。

作者:周杰

出处:https://www.cnblogs.com/sdflysha

本文采用
知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议
进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

.NET中生成水印更好的方法的更多相关文章

  1. JAVA中生成指定位数随机数的方法总结

    JAVA中生成指定位数随机数的方法很多,下面列举几种比较常用的方法. 方法一.通过Math类 public static String getRandom1(int len) { int rs = ( ...

  2. C#中生成随机数的几种方法

    Random 类 Random类默认的无参构造函数可以根据当前系统时钟为种子,进行一系列算法得出要求范围内的伪随机数 Random rd = new Random() rd.next(,)(生成1~1 ...

  3. .NET中生成动态验证码

    .NET中生成动态验证码 验证码是图片上写上几个字,然后对这几个字做特殊处理,如扭曲.旋转.修改文字位置,然后加入一些线条,或加入一些特殊效果,使这些在人类能正常识别的同时,机器却很难识别出来,以达到 ...

  4. c#封装DBHelper类 c# 图片加水印 (摘)C#生成随机数的三种方法 使用LINQ、Lambda 表达式 、委托快速比较两个集合,找出需要新增、修改、删除的对象 c# 制作正方形图片 JavaScript 事件循环及异步原理(完全指北)

    c#封装DBHelper类   public enum EffentNextType { /// <summary> /// 对其他语句无任何影响 /// </summary> ...

  5. JAVA中生成、解析二维码图片的方法

    JAVA中生成.解析二维码的方法并不复杂,使用google的zxing包就可以实现.下面的方法包含了生成二维码.在中间附加logo.添加文字功能,并有解析二维码的方法. 一.下载zxing的架包,并导 ...

  6. oracle中生成大批量数据的方法-下

    方法五:使用PLSQL的数据生成器 首先测试环境建立:dept表 CREATE TABLE dept(deptno NUMBER(6),dname VARCHAR2(20),loc VARCHAR2( ...

  7. Flink assignAscendingTimestamps 生成水印的三个重载方法

    先简单介绍一下Timestamp 和Watermark 的概念: 1. Timestamp和Watermark都是基于事件的时间字段生成的 2. Timestamp和Watermark是两个不同的东西 ...

  8. C# 动态创建SQL数据库(二) 在.net core web项目中生成二维码 后台Post/Get 请求接口 方式 WebForm 页面ajax 请求后台页面 方法 实现输入框小数多 自动进位展示,编辑时实际值不变 快速掌握Gif动态图实现代码 C#处理和对接HTTP接口请求

    C# 动态创建SQL数据库(二) 使用Entity Framework  创建数据库与表 前面文章有说到使用SQL语句动态创建数据库与数据表,这次直接使用Entriy Framwork 的ORM对象关 ...

  9. Oracle中生成uuid的方法

    Oracle中生成uuid的方法 下载LOFTER客户端 在Oracle SQL 提供了一个生成uuid的函数sys_guid: http://download.oracle.com/docs/cd/ ...

随机推荐

  1. Android官方教程翻译(4)——启动另一个Activity

    Starting Another Activity 启动另一个Activity PREVIOUSNEXT THIS LESSON TEACHES YOU TO 这节课教你 1.   Respond t ...

  2. intraweb 11.0.63 for delphi7 破解

    资源地址:http://download.csdn.net/detail/marszzx/9472912 本资源来自互联网,整理后上传,本资源仅供学习使用,请勿作用商业用途 delphi开发网站,似乎 ...

  3. 使用Ocelot做网关

    1首先创建一个json的配置文件,文件名随便取,我取Ocelot.json 这个配置文件有两种配置方式,第一种,手动填写 服务所在的ip和端口:第二种,用Consul进行服务发现 第一种如下: { & ...

  4. 简明Python3教程 18.下一步是什么

    如果你有认真通读本书之前的内容并且实践其中包含的大量例程,那么你现在一定可以熟练使用python了. 同时你可能也编写了一些程序用于验证python特性并提高你的python技能.如果还没有这样做的话 ...

  5. WPF进阶教程 - 使用Decorator自定义带三角形的边框

    原文:WPF进阶教程 - 使用Decorator自定义带三角形的边框 写下来,备忘. Decorator,有装饰器.装饰品的意思,很容易让人联想到设计模式里面的装饰器模式.Decorator类负责包装 ...

  6. 形态学-扩大-C代码

    直接在代码,难.他们明白: void MorhpolotyDilate_ChenLee(unsigned char* pBinImg, int imgW, int imgH, Tpoint* mask ...

  7. cocos2d-x 源代码分析 : Ref (CCObject) 源代码分析 cocos2d-x内存管理策略

    从源代码版本号3.x.转载请注明 cocos2d-x 总的文件夹的源代码分析: http://blog.csdn.net/u011225840/article/details/31743129 1.R ...

  8. TestNg依靠先进的采用强制的依赖,并依赖序列的------TestNg依赖于特定的解释(两)

    原创文章,版权所有所有,转载,归因:http://blog.csdn.net/wanghantong TestNg使用dependsOnGroups属性来进行依赖測试, 測试方法依赖于某个或某些方法, ...

  9. MVC 创建强类型视图

    •在ViewModel中创建一个类型 •在Action中为ViewData.Model赋值 •在View中使用"@model类型"设置 14 手动创建强类型视图 •在ViewMod ...

  10. 【Windows10 IoT开发系列】API 移植工具

    原文:[Windows10 IoT开发系列]API 移植工具 Windows 10 IoT Core 中是否提供你的当前 Win32 应用程序或库所依赖的 API? 如果不提供,是否存在可使用的等效 ...