Skip to content

Instantly share code, notes, and snippets.

@ElianFabian
Last active March 5, 2024 00:20
Show Gist options
  • Save ElianFabian/0c887f77b7759f785c98f5732185f80b to your computer and use it in GitHub Desktop.
Save ElianFabian/0c887f77b7759f785c98f5732185f80b to your computer and use it in GitHub Desktop.
Functions to convert an image into a ASCII text and vicerversa (only works for Windows).
function Convert-ImageToAscii(
[Parameter(ParameterSetName = "A")]
[string] $Path,
[Parameter(ParameterSetName = "B")]
[System.Drawing.Bitmap] $Image,
[switch] $UseAlpha
) {
$bitMap = if ($Path) {
[System.Drawing.Bitmap]::FromFile((Resolve-Path $Path))
}
else { $Image }
$result = if ($UseAlpha) {
@(
foreach ($y in (0..($bitMap.Height - 1))) {
foreach ($x in (0..($bitMap.Width - 1))) {
$color = $bitMap.GetPixel($x, $y)
$redChar = [char]$color.R
$greenChar = [char]$color.G
$blueChar = [char]$color.B
$alphaChar = [char]$color.A
"$redChar$greenChar$blueChar$alphaChar"
}
}
) -join ""
}
else {
@(
foreach ($y in (0..($bitMap.Height - 1))) {
foreach ($x in (0..($bitMap.Width - 1))) {
$color = $bitMap.GetPixel($x, $y)
$redChar = [char]$color.R
$greenChar = [char]$color.G
$blueChar = [char]$color.B
"$redChar$greenChar$blueChar"
}
}
) -join ""
}
$result.Replace("`0", '')
}
function Convert-AsciiToImage(
[Parameter(ParameterSetName = "A")]
[string] $Path,
[Parameter(ParameterSetName = "B")]
[string] $Text,
[switch] $UseAlpha
) {
[byte[]] $pixelBytesFromText = if ($Text) {
[System.Text.Encoding]::ASCII.GetBytes($Text)
}
else { [System.IO.File]::ReadAllBytes((Resolve-Path $Path)) }
$charactersPerPixel = $UseAlpha ? 4 : 3
$width = [int][math]::Ceiling( [math]::Sqrt($pixelBytesFromText.Length / $charactersPerPixel) )
$height = [int]$width
$imageFromText = [System.Drawing.Bitmap]::new($width, $height)
if ($UseAlpha) {
for ($y = 0; $y -lt $height; $y++) {
$yTimesWidth = $y * $width
for ($x = 0; $x -lt $width; $x++) {
$pixelIndex = ($yTimesWidth + $x) * $charactersPerPixel
$red = $pixelBytesFromText[$pixelIndex]
$green = $pixelBytesFromText[$pixelIndex + 1]
$blue = $pixelBytesFromText[$pixelIndex + 2]
$alpha = $pixelBytesFromText[$pixelIndex + 3]
$color = [System.Drawing.Color]::FromArgb($alpha, $red, $green, $blue)
$imageFromText.SetPixel($x, $y, $color)
}
}
}
else {
for ($y = 0; $y -lt $height; $y++) {
$yTimesWidth = $y * $width
for ($x = 0; $x -lt $width; $x++) {
$pixelIndex = ($yTimesWidth + $x) * $charactersPerPixel
$red = $pixelBytesFromText[$pixelIndex]
$green = $pixelBytesFromText[$pixelIndex + 1]
$blue = $pixelBytesFromText[$pixelIndex + 2]
$color = [System.Drawing.Color]::FromArgb($red, $green, $blue)
$imageFromText.SetPixel($x, $y, $color)
}
}
}
return $imageFromText
}
Export-ModuleMember -Function *-*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment