顾名思义:用骰子的六个面来绘制图像。
简单而有趣的一个项目。

左图是原图,右图是骰子图,放大右图可以看出是由骰子的六个面组成的。
实现步骤:
- 将图像划分为
n*n若干个部分 - 计算每部分的平均灰度
- 根据平均灰度的值绘制骰子
完整实现代码(php):
// 原图
$image = imagecreatefromstring(file_get_contents($_GET['image']));
$width = imagesx($image);
$height = imagesy($image);
// 骰子六个面对应的图像
$dices = [
imagecreatefrompng('dices/dice-1.png'),
imagecreatefrompng('dices/dice-2.png'),
imagecreatefrompng('dices/dice-3.png'),
imagecreatefrompng('dices/dice-4.png'),
imagecreatefrompng('dices/dice-5.png'),
imagecreatefrompng('dices/dice-6.png'),
];
// 最终生成的图片
$output = imagecreatetruecolor($width, $height);
// 原图划分为 8*8 若干个部分
$step = 8;
for ($y = 0; $y < $height; $y += $step) {
for ($x = 0; $x < $width; $x += $step) {
// 计算每个像素点的灰度,得到总和
$grey = 0;
$pixel = 0;
for ($y2 = 0; $y2 < $step; $y2++) {
for ($x2 = 0; $x2 < $step; $x2++) {
$xPoint = $x + $x2;
$yPoint = $y + $y2;
if ($xPoint < $width && $yPoint < $height) {
$rgb = imagecolorat($image, $x + $x2, $y + $y2);
$grey += ($rgb >> 16 & 0xff) * 0.3 +
($rgb >> 8 & 0xff) * 0.59 +
($rgb >> 0 & 0xff) * 0.11;
$pixel++;
}
}
}
// 得出该部分平均灰度,并根据灰度值为该部分绘制骰子
$grey /= $pixel;
$index = $grey > 212 ? 5 : ($grey > 170 ? 4 : ($grey > 127 ? 3 : ($grey > 85 ? 2 : ($grey > 42 ? 1 : 0))));
imagecopyresized($output, $dices[$index], $x, $y, 0, 0, $step, $step, 64, 64);
}
}
// 输出最终图片
header('Content-type: image/png');
imagepng($output);
哇这也太强了,大佬我好崇拜你(