php生成简单的字符画


前言

在网上看到用程序生成的字符画,感觉蛮有趣到,自己就找相关的资料也做了个简陋的。其中用到了php的GD库函数以及RGB转换成灰度的计算公式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

class codeimg {

private function getGray($r, $g, $b) {
return 0.299 * $r + 0.578 * $g + 0.114 * $b;
}

private function code ($gray) {
if ($gray <= 30) {
return '#';
} else if ($gray > 30 && $gray <= 60) {
return '&';
} else if ($gray > 60 && $gray <= 120) {
return '$';
} else if ($gray > 120 && $gray <= 150) {
return '*';
} else if ($gray > 150 && $gray <= 180) {
return 'o';
} else if ($gray > 180 && $gray <= 210) {
return '!';
} else if ($gray > 210 && $gray <= 240) {
return ';';
} else {
return ' ';
}
}

private function getRgb ($img,$x, $y) {
$rgb = ImageColorAt($img, $x ,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
return $this->getGray($r, $g, $b);
}

private function file ($filetxt,$str) {
$txt = fopen($filetxt, 'w+');
fwrite($txt, $str);
fclose($txt);
}

public function getImg($file,$filetxt) {
$img = imagecreatefromjpeg($file);
$w = imagesx($img);
$h = imagesy($img);
$newimg = imagecreatetruecolor($w, $h);
imagecopymergegray($newimg,$img,0,0,0,0,$w,$h,90);
$str = '';

for ($y = 0; $y < $h; $y += 6) {
for ($x = 0; $x < $w; $x += 4) {
$str .= $this->code($this->getRgb($newimg , $x , $y));
}
$str .= PHP_EOL;
}

$this->file($filetxt, $str);
}
}


$file = new codeimg();
$file->getImg('1.jpg', 'code.txt');