GD 向图像添加边框不起作用

GD adding border to image not working

所以我有 PHP class 并且我正在尝试在上传的图片周围添加带间距的白色边框:

private function __draw_white_border()
{
    // get source image and dimensions.
    $src = $this->file_data['im'];
    $src_w = imagesx($src);
    $src_h = imagesy($src);
    // create destination image with dimensions increased from $src for borders.
    $dest_w = $src_w + 10;
    $dest_h = $src_h + 10;
    $dest = imagecreatetruecolor($dest_w, $dest_h);
    // draw white border (no need for black since new images default to that).
    imagerectangle($dest, 1, 1, $dest_w - 2, $dest_h - 2, 0x00ffffff);
    imagerectangle($dest, 0, 0, $dest_w - 1, $dest_h - 1, 0x00ffffff);
    // copy source image into destination image.
    imagecopy($dest, $src, 5, 5, 0, 0, $src_w, $src_h);
}

此功能在不在 class 中时工作正常,但在 class 中它不起作用。似乎此功能不保存图像或其他东西,我不知道。它应该从我认为的 $this->file_data['im'] 加载图像并保存到相同的目的地以进行进一步操作。哪里出了问题?

在此方法 运行 之后,您不会将修改后的图像放回可以再次访问它的任何地方。此代码(见最后一行)将其放回原始图像的来源。

private function __draw_white_border()
{
    // get source image and dimensions.
    $src = $this->file_data['im'];
    $src_w = imagesx($src);
    $src_h = imagesy($src);
    // create destination image with dimensions increased from $src for borders.
    $dest_w = $src_w + 10;
    $dest_h = $src_h + 10;
    $dest = imagecreatetruecolor($dest_w, $dest_h);
    // draw white border (no need for black since new images default to that).
    imagerectangle($dest, 1, 1, $dest_w - 2, $dest_h - 2, 0x00ffffff);
    imagerectangle($dest, 0, 0, $dest_w - 1, $dest_h - 1, 0x00ffffff);
    // copy source image into destination image.
    imagecopy($dest, $src, 5, 5, 0, 0, $src_w, $src_h);

    $this->file_data['im'] = $dest;
}

您需要创建 2 张图片并将主图片叠加在稍大的第二张图片之上。这样,将在主图像的边缘周围看到较大的图像,使其看起来像一个边框。

http://php.net/manual/en/function.imagecopy.php

我用它来正确地分层图像。如果目标图像较大,可以说是 100x100 像素。源图像为 80x80px。您将向源图像的 x 和 y 添加 10,这会将源图像置于 100x100px 图像的中心。如果 100x100px 图像是纯黑色图像,它将生成干净的黑色边框