Vital Vital - 3 months ago 30
PowerShell Question

DrawString with outline in image

How I can draw outlined string? For example: solid color of string white, border is black. Which method I must use to get this effect? Maybe somebody know some example.

$swp_curr_dir = split-path -parent $MyInvocation.MyCommand.Definition
[void][reflection.assembly]::loadwithpartialname("system.windows.forms")

function AddTextToImage {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][String] $sourcePath,
[Parameter(Mandatory=$true)][String] $destPath,
[Parameter(Mandatory=$true)][String] $Title
)

Write-Verbose "Load System.Drawing"
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null

$srcImg = [System.Drawing.Image]::FromFile($sourcePath)

$outputIImg = New-Object System.Drawing.Bitmap([int]($srcImg.width)),([int]($srcImg.height))

$Image = [System.Drawing.Graphics]::FromImage($outputIImg)
$Image.SmoothingMode = "AntiAlias"

$img_rectangle = New-Object Drawing.Rectangle 0, 0, $srcImg.Width, $srcImg.Height
$Image.DrawImage($srcImg, $img_rectangle, 0, 0, $srcImg.Width, $srcImg.Height, ([Drawing.GraphicsUnit]::Pixel))

$Font = New-Object System.Drawing.Font("Bauhaus 93", 200, "Bold","Pixel")

$rect = [System.Drawing.RectangleF]::FromLTRB(0, 0, $srcImg.Width, $srcImg.Height)
$format = [System.Drawing.StringFormat]::GenericDefault
$format.Alignment = [System.Drawing.StringAlignment]::Center
$format.LineAlignment = [System.Drawing.StringAlignment]::Center

$Brush = New-Object Drawing.SolidBrush([System.Drawing.Color]::FromArgb(255, 255, 255, 255))

$Image.DrawString($Title, $Font, $Brush, $rect, $format)

$outputIImg.save($destPath, [System.Drawing.Imaging.ImageFormat]::jpeg)
$outputIImg.Dispose()
$srcImg.Dispose()
}

AddTextToImage -sourcePath ($swp_curr_dir + "\image.jpg") -destPath ($swp_curr_dir + "\output.jpg") -Title "Some title d ias hdiusahdiusahdias hdisahidu sad sad sa ad asd asd asd sad sad asd as long"

cmd /c pause

Answer

You can use path like below:

...
$Image.DrawString($Title, $Font, $Brush, $rect, $format)

$path = New-Object System.Drawing.Drawing2D.GraphicsPath
$path.AddString($Title, $Font.FontFamily, $Font.Style, $Font.Size, $rect, $format)
$Image.DrawPath([System.Drawing.Pens]::Black, $path)

$outputIImg.save($destPath, [System.Drawing.Imaging.ImageFormat]::jpeg)
...
Comments