Turning Any Image File to An ASCII Art in PowerShell

1

This is something pretty cool that I have to share. With the power of PowerShell, you can turn any image file, JPG or PNG, into a plain text file that you can open in Notepad. Thanks to PowerTips.

Here is the code, start with the function.

function Convert-ImageToAsciiArt
{
param(
[Parameter(Mandatory)][String]
$Path,
[ValidateRange(20,20000)]
[int]$MaxWidth=80,
#character height:width ratio
[float]$ratio = 1.5 )

# load drawing functionality
Add-Type -AssemblyName System.Drawing
# characters from dark to light
$characters = '$#H&@*+;:-,. '.ToCharArray()
$c = $characters.count
# load image and get image size
$image = [Drawing.Image]::FromFile($path )
[int]$maxheight = $image.Height / ($image.Width / $maxwidth) / $ratio
# paint image on a bitmap with the desired size
$bitmap = new-object Drawing.Bitmap($image ,$maxwidth,$maxheight)
# use a string builder to store the characters
[System.Text.StringBuilder]$sb = ""
# take each pixel line...
for ([int]$y=0; $y -lt $bitmap.Height; $y++)
{
# take each pixel column...
for ([int]$x=0; $x -lt $bitmap.Width; $x++)
{
# examine pixel
$color = $bitmap.GetPixel($x, $y)
$brightness = $color.GetBrightness()
# choose the character that best matches the pixel brightness
[int]$offset = [Math]::Floor($brightness*$c)
$ch = $characters[$offset]
if (-not $ch) { $ch = $characters[-1] }
# add character to line
$null = $sb.Append($ch)
}
# add a new line
$null = $sb.AppendLine()
}
# clean up and return string
$image.Dispose() $sb.ToString()
}

Then, here is how to use it to call the function, generate the ASCII file and display it.

$Path = "folder\imagefile.jpg"
$OutPath = "$env.temp\asciiart.txt"

Convert-ImageToAsciiArt -Path $Path -MaxWidth 150 |
Set-Content -Path $OutPath -Encoding UTF8

Invoke-Item -Path $OutPath

Now let’s give it a test run on Elias Pettersson, the rookie of the year in NHL. If you don’t know who he, here is him.

5864.vresize.350.425.medium.50 - Turning Any Image File to An ASCII Art in PowerShell
Elias Pettersson

And here is the AscII version of him, generated by PowerShell.

image 30 - Turning Any Image File to An ASCII Art in PowerShell
AscII version of Elias Pettersson

Pretty impressive.

Guess what’s more fun? Watch Rick Astley sing and dance in AscII mode.

1 COMMENT

  1. Works but you have to edit this otherwise it throws an error – very nice! :
    # clean up and return string
    $image.Dispose() $sb.ToString()

    to this
    # clean up and return string
    $image.Dispose()
    $sb.ToString()

LEAVE A REPLY

Please enter your comment!
Please enter your name here