着色图像相当容易完成,尤其是使用 PHP 的 GD 库。我们需要做的就是加载一个图像,创建一个特定颜色的相同大小的空白图像,然后将两个图像合并在一起。
事实上,我们完全可以用imagecopymerge()函数来做到这一点 ,但创建一个函数来包装所有这些也是有意义的。
以下函数采用图像资源(由 所创建 imagecreatefrompng())、颜色的红色、绿色和蓝色值,以及在图像顶部叠加颜色的百分比。可以将百分比设置为 0 表示没有效果,设置为 100 表示使用给定颜色完全替换图像。
/** * Colorise an image. * * @param resource $image * The image resource. * @param int $r * The red part of the color (0 to 255). * @param int $g * The green part of the color (0 to 255). * @param int $b * The blue part of the color (0 to 255). * @param int $percent * The percentage of colorisation that should occur. */ function imagecolorise(&$image, $r, $g, $b, $percent) { // 确保百分比限于给定值。 if ($percent < 0) { $percent = 0; } elseif ($percent > 100) { $percent = 100; } // 获取图像的宽度。 $imageWidth = imagesx($image); // 获取图像的高度。 $imageHeight = imagesy($image); // 创建停留图像。 $layover = imagecreate($imageWidth, $imageHeight); // 在此图像上分配颜色。 $color = imagecolorallocate($layover, $r, $g, $b); // 将停留图像合并到另一个图像之上。 imagecopymerge($image, $layover, 0, 0, 0, 0, $imageWidth, $imageHeight, $percent); // 销毁停留图像。 imagedestroy($layover); }
我们可以通过以下方式使用此功能。
// 加载图像。 $image = imagecreatefromjpeg('my_image.jpeg'); // 使用 75% 饱和度的蓝色对图像进行着色。 imagecolorise($image, 10, 10, 200, 75); // 保存新图像。 imagepng($image, 'colorised.png'); // 销毁加载的图像。 imagedestroy($image);
以下图为例。
旅行家。
如果我们通过上面的代码处理它,我们可以将非常深的蓝色应用于图像,使其看起来像这样。
使用此功能可以快速将蒙版应用于图像以帮助其融入网页背景。还可以使用该 imagecopymerge()功能通过将一个图像叠加在另一个图像上来为图像创建水印。