Created
September 4, 2024 01:39
-
-
Save joetannenbaum/5fe69423af13d7285933095d6399dbd0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function imageToAscii($path, $maxWidth = 100, $maxHeight = 100) | |
{ | |
$contrast = 5; | |
$characters = str_split( | |
str_repeat(' ', $contrast * 10) | |
. '`.-\':_,^=;><+!rc*/z?sLTv)J7(|Fi{C}fI31tlu[neoZ5Yxjya]2ESwqkP6h9d4VpOGbUAKXHm8RD#$Bg0MNWQ%&@' | |
); | |
$image = imagecreatefromjpeg($path); | |
while (imagesx($image) > $maxWidth || imagesy($image) > $maxHeight) { | |
$image = imagescale($image, (int) (imagesx($image) * .75), (int) (imagesy($image) * .75)); | |
} | |
$width = imagesx($image); | |
$height = imagesy($image); | |
$lines = []; | |
for ($y = 0; $y < $height; $y++) { | |
$line = []; | |
for ($x = 0; $x < $width; $x++) { | |
$rgb = imagecolorat($image, $x, $y); | |
$r = ($rgb >> 16) & 0xFF; | |
$g = ($rgb >> 8) & 0xFF; | |
$b = $rgb & 0xFF; | |
$average = ($r + $g + $b) / 3; | |
$percentage = $average / 255; | |
$line[] = $characters[(int) max(($percentage * count($characters)) - 1, 0)]; | |
} | |
$lines[] = $line; | |
} | |
return $lines; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment