root@green-blog:~$ view-post --id 15

← بازگشت به لیست
[2026-05-04 10:48:49]

کارکرد تبدیل عکس به ASCII

2 min read
به طور کلی ، دوتا مورد خیلی مطرحه توی تبدیل عکس به کاراکتر اسکی (دیگه خودتون درست بخونینش).
1. ارتفاع و نسبت بندی.
2. اندازه گیری میزان روشنایی هر نقطه از عکس.
این کدیه که در نهایت استفاده کردم ، از روی تایم پست بندی و فاصله پست ها هم میتونید بفهمید که منطقا خودم ننوشتمش، با کمک هوش مصنوعی دوست داشتنی نوشتمش.

php
<?php

function imageToAscii($imagePath, $newWidth = 100) {

if (!file_exists($imagePath)) {
return "Image not found!";
}


$imageInfo = getimagesize($imagePath);
$mime = $imageInfo['mime'];

// detect file type
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($imagePath);
break;
case 'image/png':
$image = imagecreatefrompng($imagePath);
break;
case 'image/gif':
$image = imagecreatefromgif($imagePath);
break;
default:
return "Unsupported image type!";
}

$width = imagesx($image);
$height = imagesy($image);

// calcuating height
$aspectRatio = $height / $width;
$newHeight = intval($aspectRatio * $newWidth * 0.55); //a random number for ratio.

// resize
$resized = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// ASCII characters (from dark to light)
$chars = "@%#*+=-:. ";

$ascii = "";

for ($y = 0; $y < $newHeight; $y++) {
for ($x = 0; $x < $newWidth; $x++) {
$rgb = imagecolorat($resized, $x, $y);

$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

// convert to grayscale
$gray = ($r + $g + $b) / 3;

// map to character
$index = intval(($gray / 255) * (strlen($chars) - 1));
$ascii .= $chars[$index];
}
$ascii .= "\n";
}

imagedestroy($image);
imagedestroy($resized);

return $ascii;
}



btw توی تست اول هم باید یه دایرکتوری درست میکردم که نکرده بودم، هم پسوند فایل webp بود و حواسم به این موضوع نبود که کد ساپورتش نمیکنه.

// rendering post snapshot...