1. 环境准备

首先,确保你的PHP环境中已经安装了GD库。GD库是PHP中用于处理图像的扩展,它提供了丰富的图像处理函数。

2. 加载图片

$image = imagecreatefromjpeg('path/to/your/image.jpg');

3. 创建相框

$frameWidth = 20; // 相框宽度
$frameHeight = 20; // 相框高度
$newWidth = imagesx($image) + $frameWidth * 2;
$newHeight = imagesy($image) + $frameHeight * 2;

$frameImage = imagecreatetruecolor($newWidth, $newHeight);

这里,我们设置了相框的宽度和高度,并计算了新的图像尺寸。

4. 绘制相框

使用imagefilledrectangle函数绘制相框:

// 绘制相框的内部填充
imagefilledrectangle($frameImage, 0, 0, $newWidth, $newHeight, imagecolorallocate($frameImage, 255, 255, 255));

// 绘制相框的边框
imagefilledrectangle($frameImage, $frameWidth - 1, $frameHeight - 1, $newWidth - $frameWidth, $newHeight - $frameHeight, imagecolorallocate($frameImage, 0, 0, 0));

这里,我们首先绘制了相框的内部填充,然后绘制了边框。

5. 合成图片

imagecopy($frameImage, $image, $frameWidth, $frameHeight, 0, 0, imagesx($image), imagesy($image));

6. 保存或输出图片

imagejpeg($frameImage, 'path/to/save/image_with_frame.jpg');

7. 清理资源

在完成所有操作后,不要忘记释放图像资源:

imagedestroy($image);
imagedestroy($frameImage);