使用 VB.NET GDI+ 盖章图像






1.67/5 (7投票s)
一篇关于使用 VB.NET GDI+ 进行图像盖章的文章。

引言
最近我遇到了一个任务,需要在不干扰图像内容的情况下盖章。我一直在想如何实现它。我搜索了很多,但没有找到完全符合我要求的解决方案。因此,在研究了 GDI+ 库并花费了一些时间和精力后,我得到了自己的解决方案。我认为这段代码可以帮助那些手头有相同或类似任务的人。这段代码可以帮助在不干扰原始内容的情况下盖章。盖章可以是一个空白图像,也可以是在图像上写有文字的图像。
Using the Code
有许多类,如 Bitmap
、Image
、Graphics
、Font
、Brush
等,可以使用 .NET 框架执行图形操作。为了简化图像盖章过程,让我们看一下演示如何盖章图像的代码。
创建盖章就像创建 Bitmap
对象本身一样简单,只需指定其高度和宽度。此任务仅涉及三个步骤
- 创建
Bitmap
对象 - 使用
Bitmap
对象创建Graphics
对象 - 使用
Graphics
类的DrawString()
方法
'Create Bitmap object of specific width and height
Dim ImgStamp As New Bitmap(intWidth, intHeight)
'Obtain Graphics object to perform graphics opration
Dim g As Graphics = Graphics.FromImage(ImgStamp)
'Use drawString method of the graphics object to write text on target bitmap
g.DrawString("Test", New Font("Arial", 15, FontStyle.Bold), _
New SolidBrush(Color.Red), 25, 35)
'Save this bitmap using its save method as .Tiff,.jpg or any other image
ImgStamp.Save(YourPath & "\MyStamp.Tiff" )
'You can optionally specify the ImageFormat using ImageFormat Class
ImgStamp.Save(YourPath & "\MyStamp.Tiff",_
System.Drawing.Imaging.ImageFormat.Tiff)
DrawString()
方法接受 Font
和 Brush
对象,以便在 Bitmap
上绘制文本。您可以使用 FontDialog
的属性(如 fontName
、大小和样式)来创建自己的 Font
对象,同样可以使用 Color
对象来创建 Brush
对象。最后两个参数是在 Bitmap
上写入文本的起始 X 和 Y 位置。以下是在原始图像上盖章的代码
'Construct a bitmap object using original image so
'you can draw this object on the target bitmap
Dim OrgImg As New Bitmap(strImagePath)
'Construct a bitmap object for the stamp image
Dim StampImg As New Bitmap(StampImagePath & "\MyStamp.Tiff")
'Create target bitmap to draw both original image and stamp image.
Dim TarImg As New Bitmap(OrgImg.Width, OrgImg.Height + StampImg.Height)
'Obtain a Graphics object from & for that Bitmap
Dim gr As Graphics = Graphics.FromImage(TarImg)
'Draw the original image first on the target bitmap using graphics object
gr.DrawImage(OrgImg, 0, 0, OrgImg.Width, OrgImg.Height)
'Now draw the stamp image on the target bitmap using graphics object
gr.DrawImage(StampImg, 0, OrgImg.Height, StampImg.Width, StampImg.Height)
'Save the target bitmap as image file
TarImg.Save(YourPath & "\MyStamppedImage.Tiff")
上面的代码将创建名为 MyStamppedImage.jpg 的新图像文件,其中包含原始内容和附加的盖章图像,粘贴在原始图像内容的下方,而不会干扰原始图像文件的内容。
关注点
这段代码仅在原始图像内容的末尾创建了一个盖章,但您可以在同一图像上创建多个盖章,甚至可以在原始图像的内容顶部创建盖章。您可以使用 Color
对象创建不同颜色的盖章。通过使用 Color.FromArgb()
方法,您可以创建任何颜色来创建盖章的背景色和前景色。您甚至可以压缩原始图像或盖章图像以获得更高的清晰度。
历史
- 2007 年 8 月 20 日 -- 发布原始版本
- 2007 年 8 月 22 日 -- 更新了演示项目版本