PowerShell给图片添加水印 9


背景

之前转载过一篇文章Powershell将bmp文件转换成ico文件,codecook回复到能否在图片上写一段文字。我进而联想到给图片添加文字水印。为了不影响图片整体的效果,一般图片的水印文字位于四个边角。今天借着圣诞节的气氛,顺便给所有PowerShell爱好者送下节日的祝福,哈哈!

需求

  • 函数名命名为:Draw-WatemarkString
  • 水印文字支持东南,西南,西北,东北,四个位置
  • 函数支持的参数包括图片文件,水印文字,位置,字体大小,字体颜色,字体名称,边缘宽度,字体风格(加粗,倾斜,下划线等)
  • 图片文件路径和水印文字为强制参数,其它均为可选参数

知识点

  • 调用c# System.Drawing命名空间下的Graphics.DrawString(string,font,brush,pointF)
  • System.Drawing.Image对象不能再原有的路径上保存,可以先保存到临时文件,然后替换原文件
  • 枚举值之间的或可以使用-bxor操作符
  • FontStyle变量必须声明为强类型,否则执行或操作后,变为整数,在初始化Font时失败
  • 使用[Parameter(Mandatory=$true)]限制参数为强制参数
  • 使用[ValidateNotNullOrEmpty()]限制参数如果指定,则不能为空或白空格
  • 使用[ValidateSet(obj1,obj2,objn)]限制参数的取值集合
  • 使用[ValidateRange(m,)]限制参数的取值区间
  • 使用[ValidatePattern($pattern)限制参数必须匹配指定模式(正则表达式)

脚本

<#
.Synopsis
   draw watemark string on a picture file. 
.DESCRIPTION
   draw watemark string on a picture file
.EXAMPLE
   Draw-WatemarkString -ImageFile 'D:\Merry Christmas.jpg' -Text 'Merry Christmas' -Location NorthWest -FontSize 35 -Color Red
.EXAMPLE
#>
function Draw-WatemarkString()
{
    param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [ValidatePattern("(.jpg)|(.png)|(.gif)$")]
    [io.fileinfo]$ImageFile,

    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Text,

    [ValidateSet("NorthWest", "NorthEast", "SouthWest","SouthEast")]
    [string]$Location='SouthEast',

    [System.Drawing.Color]$Color=[System.Drawing.Color]::Blue,

    [ValidateRange(1,[system.single]::MaxValue)]
    [float]$FontSize = 10,

    [string]$FontFamily='Microsoft YaHei',

    [ValidateRange(0,[system.single]::MaxValue)]
    [int]$margin = 2, 

    [switch]$Bold,
    [Switch]$Italic,
    [switch]$Underline,
    [switch]$Strikeout
    )

    # test image file exists
    if( -not (Test-Path $ImageFile) )
    {
        throw "Image file $ImageFile not exists. "
    }

    # font style
    [drawing.fontstyle]$fontStyle= [drawing.fontstyle]::Regular
    ( 
    ($Bold,[drawing.fontstyle]::Bold),
    ($Italic,[drawing.fontstyle]::Italic), 
    ($Underline,[drawing.fontstyle]::Underline), 
    ($Strikeout,[drawing.fontstyle]::Strikeout) 
    ) | foreach {
     if($_[0])
     {
        $fontStyle = $fontStyle -bxor $_[1]
     }
    }

    # graphics and brush
    $font = New-Object System.Drawing.Font($FontFamily, $FontSize,$fontStyle)
    $img = [drawing.image]::FromFile($ImageFile)
    $drawBrush =  [drawing.solidbrush]$Color
    $g = [drawing.graphics]::FromImage($img)
    $textSize = $g.MeasureString($Text,$font).ToPointF()
    $pointF = New-Object System.Drawing.PointF

    # location
    switch ($Location)
    {
      'NorthWest'
      {
        $pointF.X = $margin
        $pointF.Y = $margin
      }

      'NorthEast'
      {
        $pointF.X = $img.Width - $margin - $textSize.X
        $pointF.Y = $margin
      }

      'SouthWest'
      {
        $pointF.X = $margin
        $pointF.Y = $img.Height - $margin - $textSize.Y 
      }

      'SouthEast'
      {
         $pointF.X = $img.Width - $margin - $textSize.X
         $pointF.Y = $img.Height - $margin - $textSize.Y
      }
    }

    # draw string and save image to temporary file
    $g.DrawString($Text,$font,$drawBrush,$pointF)
    $tempImage = '{0}.tempImage' -f $ImageFile
    $img.Save($tempImage)

    # dispose graphics, brush, image
    $g.Dispose()
    $drawBrush.Dispose()
    $img.Dispose()

    # copy temporary file to original source
    Copy-Item $tempImage $ImageFile -Force
    Remove-Item $tempImage

}

示例和截图

示例

Draw-WatemarkString -ImageFile 'D:\Merry Christmas.jpg' -Text '祝广大PowerShell群友们:' -Location NorthWest -FontSize 35 -Color Red
Draw-WatemarkString -ImageFile 'D:\Merry Christmas.jpg' -Text '圣诞节快乐!' -Location NorthEast -FontSize 90 -Color Red -Bold -margin 60
Draw-WatemarkString -ImageFile 'D:\Merry Christmas.jpg' -Text 'PowerShell 中文博客:https://www.pstips.net' -Location SouthWest -FontSize 30 -Italic -Underline
Draw-WatemarkString -ImageFile 'D:\Merry Christmas.jpg' -Text '2013年12月25日' -Location SouthEast -FontSize 30 -Italic

截图

点击放大查看添加水印后的效果

PowerShell 给图片添加水印文字

PowerShell 给图片添加水印文字

 

本文链接: https://www.pstips.net/draw-watemark-string.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

9 条评论 “PowerShell给图片添加水印

  • codecook

    非常感谢,测试时有错误。
    参数属性必须是常量或脚本块。
    位于 :行:6 字符:46
    + [ValidatePattern(“(.jpg)|(.png)|(.gif)$” ) <<<< ]

      • codecook

        不是4.0.那在2.0怎么设置参数呢?想学习下。

        param(
            [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][ValidatePattern("(·.jpg)|(·.png)|(·.gif)$")][io.fileinfo]$ImageFile,
            [Parameter(Mandatory=$true)]    [ValidateNotNullOrEmpty()]    [string]$Text,
            [ValidateSet("NorthWest", "NorthEast", "SouthWest","SouthEast")]    [string]$Location='SouthEast',
            [System.Drawing.Color]$Color=[System.Drawing.Color]::Blue,
            [ValidateRange(1,[system.single]::MaxValue)]    [float]$FontSize = 10,
            [string]$FontFamily='Microsoft YaHei',
         
            [ValidateRange(0,[system.single]::MaxValue)]    [int]$margin = 2,
         
            [switch]$Bold,
            [Switch]$Italic,
            [switch]$Underline,
            [switch]$Strikeout
            )
        
  • codecook

    去掉那些限定类型,脚本能成功了。

    param(
        [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][ValidatePattern("(·.jpg)|(·.png)|(·.gif)$")][io.fileinfo]$ImageFile, 
        [Parameter(Mandatory=$true)]    [ValidateNotNullOrEmpty()]    [string]$Text, 
        [ValidateSet("NorthWest", "NorthEast", "SouthWest","SouthEast")]    [string]$Location='SouthEast', 
        [System.Drawing.Color]$Color=[System.Drawing.Color]::Blue, 
        [ValidateRange(1,[system.single]::MaxValue)]    [float]$FontSize = 10, 
        [string]$FontFamily='Microsoft YaHei', 
        [ValidateRange(0,[system.single]::MaxValue)]    [int]$margin = 2, 
        [switch]$Bold,
        [Switch]$Italic,
        [switch]$Underline,
        [switch]$Strikeout
        )
    
    • Mooser Lee 文章作者

      @codecook
      关于[switch],是一个参数。如果你指定了-yourswitch ,值就是true,否则就是false
      关于图片,评论不支持图片上传。
      关于评论中插入代码,可以使用
      <pre class=”brush:powershell”>
      Get-Command
      </pre>

      使用后效果

      Get-Command
      

      我把你的回复稍微更新了下,谢谢!