Convertir cualquier archivo de imagen en un arte ASCII en PowerShell

Esto es algo muy bueno que tengo que compartir. Con el poder de PowerShell, puede convertir cualquier archivo de imagen, JPG o PNG, en un archivo de texto sin formato que puede abrir en el Bloc de notas. Gracias a PowerTips.

Aquí está el código, comience con la función.

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()
}

Entonces, aquí se explica cómo usarlo para llamar a la función, generar el archivo ASCII y mostrarlo.

$Path = "folderimagefile.jpg"
$OutPath = "$env.tempasciiart.txt"

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

Invoke-Item -Path $OutPath

Ahora probémoslo con Elias Pettersson, el novato del año en la NHL. Si no sabe quién es, aquí está.

Elias Pettersson

Y aquí está la versión AscII de él, generada por PowerShell.

imagen 30 - Convertir cualquier archivo de imagen en un arte ASCII en PowerShell
Versión AscII de Elias Pettersson

Muy impresionante.

¿Adivina qué es más divertido? Mira a Rick Astley cantar y bailar en el modo AscII.

Deja un comentario