在之前的技能中我们介绍了如何读取任何图片或照片,并将它转换为一个黑白 ASCII 艺术。今天,我们将修改 Convert-ImageToAsciiArt
函数:它输入一个函数并将它转换为彩色的 ASCII 艺术!
像素的亮度值将被转换为合适的 ASCII 字符,并且像素的颜色值将应用到该字符。ASCII 艺术将写入 HTML 文件,因为 HTML 是表示彩色文字的最简单格式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| function Convert-ImageToAsciiArt { param( [Parameter(Mandatory)][String] $ImagePath,
[Parameter(Mandatory)][String] $OutputHtmlPath,
[ValidateRange(20,20000)] [int]$MaxWidth=80 )
,
[float]$ratio = 1.5
Add-Type -AssemblyName System.Drawing
$characters = & $c = $characters.count
$image = [Drawing.Image]::FromFile($ImagePath) [int]$maxheight = $image.Height / ($image.Width / $maxwidth) / $ratio
$bitmap = new-object Drawing.Bitmap($image,$maxwidth,$maxheight)
[System.Text.StringBuilder]$sb = "<html><building style='font-family:""Consolas""'>"
for ([int]$y=0; $y -lt $bitmap.Height; $y++) { $null = $sb.Append("<nobr>") for ([int]$x=0; $x -lt $bitmap.Width; $x++) { $color = $bitmap.GetPixel($x,$y) $brightness = $color.GetBrightness() [int]$offset = [Math]::Floor($brightness*$c) $ch = $characters[$offset] if (-not $ch) { $ch = $characters[-1] } $col = "#{0:x2}{1:x2}{2:x2}" -f $color.r, $color.g, $color.b if ($ch -eq & $null = $sb.Append( "<span style=""color:$col""; ""white-space: nowrap;"">$ch</span>") } $null = $sb.AppendLine("</nobr><br/>") }
$null = $sb.AppendLine("</building></html>")
$image.Dispose()
Set-Content -Path $OutputHtmlPath -Value $sb.ToString() -Encoding UTF8 }
|
还有以下是如何将一张图片转换为一个漂亮的 ASCII 艺术,并在浏览器VS显示,甚至在彩色打印机中打印出来:
1 2 3 4 5
| $ImagePath = "C:\someInputPicture.jpg" $OutPath = "$home\desktop\ASCIIArt.htm"
Convert-ImageToAsciiArt -ImagePath $ImagePath -OutputHtml $OutPath -MaxWidth 150 Invoke-Item -Path $OutPath
|
可以通过调整 -MaxWidth
来控制细节。如果增加了宽度,那么也必须调整字体大小并增加字符数。对于更小的字符,您可能需要调整这行:
1
| [System.Text.StringBuilder]$sb = "<html><building style='font-family:""Consolas""'>"
|
例如将它改为这行:
1
| [System.Text.StringBuilder]$sb = "<html><building style='font-family:""Consolas"";font-size:4px'>"
|