综合参考了两篇博客做的
https://blog.youkuaiyun.com/somehow1002/article/details/77600186
https://blog.youkuaiyun.com/qq_15096707/article/details/48918461
源代码如下:
class Drawing
{
/**
* @var:图像句柄
*/
protected $im;
/**
* @var:字体颜色
*/
protected $fontColor;
/**
* @var:背景颜色
*/
protected $backColor;
/**
* @var:源图资源
*/
protected $source_img;
/**
* 字符画输出到图片
* @param $imgName
*/
public function createImg($imgName)
{
$this->source_img = getimagesize($imgName);
if (empty($this->source_img) || !isset($this->source_img[0]) || !isset($this->source_img[1])) {
die('图片资源有误!');
}
//创建画布
$this->im = imagecreatetruecolor($this->source_img[0], $this->source_img[1]);
//设置画布背景颜色
$this->backColor = imagecolorallocate($this->im, 255, 255, 255);
imagefill($this->im, 0, 0, $this->backColor);
//创建字体颜色
$this->fontColor = imagecolorallocate($this->im, 0, 0, 0);
//写入内容
$this->output($imgName);
//输出图像到网页
header("content-type:image/png");
imagepng($this->im);
//销毁该图片
imagedestory($this->im);
}
/**
* 获得图像资源
* @param $imgName
* @return false|resource
*/
public function getImg($imgName)
{
if ($this->source_img[2] == 1) {
return imagecreatefromgif($imgName);
} else if ($this->source_img[2] == 2) {
return imagecreatefromjpeg($imgName);
} else if ($this->source_img[2] == 3) {
return imagecreatefrompng($imgName);
} else {
die("对不起,暂不支持该格式!");
}
}
/**
* 图像转字符画
* @param $imgName :图像名称
*/
public function output($imgName)
{
$im = $this->getImg($imgName);
$str = '@80GCLft1i;:,. ';//填充字符
//步长:选取每个像素块的代表点
$stepx = 8;
$stepy = 16;
$x = imagesx($im);
$y = imagesy($im);
for ($j = 0; $j < $y; $j += $stepy) {
$tmp = '';
for ($i = 0; $i < $x; $i += $stepx) {
//获取像素块的代表点RGB信息
$colors = imagecolorsforindex($im, imagecolorat($im, $i, $j));
//灰度值计算公式:Gray=R*0.3+G*0.59+B*0.11
$greyness = (0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]) / 255;
//根据灰度值选择合适的字符
$offset = (int)ceil($greyness * (strlen($str) - 1));
if ($offset == (strlen($str) - 1)) {
$tmp .= " ";
} else {
$tmp .= $str[$offset];
}
}
//使用imagestring写中文会出现乱码
imagestring($this->im, 4, 0, $j, $tmp, $this->fontColor);
}
imagedestroy($im);
}
}
调用:
$Drawing = new Drawing();
$Drawing->createImg('1.jpg');
效果图: