如何将水印添加到GD图像资源

时间:2014-10-16 15:58:49

标签: php image gd watermark

我使用php GD图像进行图像上传,但我想为调整大小的图像添加水印。我找到了一些添加水印的代码,但我无法使其工作。我需要一些提示。

function resizeImage($CurWidth, $CurHeight, $MaxSize, $DestFolder, $SrcImage, $Quality, $ImageType)
{
    //Check Image size is not 0
    if ($CurWidth <= 0 || $CurHeight <= 0) {
        return false;
    }

    //Construct a proportional size of new image
    $ImageScale = min($MaxSize / $CurWidth, $MaxSize / $CurWidth);
    $NewWidth   = ceil($ImageScale * $CurWidth);
    $NewHeight  = ceil($ImageScale * $CurHeight);
    $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);

    $watermark_png_file = 'watermark.png';

    //calculate center position of watermark image
    $watermark_left = ($NewWidth / 2) - (300 / 2); //watermark left
    $watermark_bottom = ($NewHeight / 2) - (100 / 2); //watermark bottom

    $watermark = imagecreatefrompng($watermark_png_file); //watermark image

    //use PHP imagecopy() to merge two images.
    imagecopy($NewCanves, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 100); //merge image

    // Resize Image
    if (imagecopyresampled($NewCanves, $SrcImage, 0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
    {
        switch (strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves, $DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves, $DestFolder);
                break;
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves, $DestFolder, $Quality);
                break;
            default:
                return false;
        }

        //Destroy image, frees memory
        if (is_resource($NewCanves)) imagedestroy($NewCanves);
        return true;
    }
}

我已经尝试过这段代码,但它不起作用:

function generate_watermarked_image($ImageType, $CurWidth, $CurHeight, $paddingFromBottomRight = 0)
{
    $watermarkFileLocation = 'logo.png';
    $watermarkImage = imagecreatefrompng($watermarkFileLocation);
    $watermarkWidth = imagesx($watermarkImage);
    $watermarkHeight = imagesy($watermarkImage);

    $originalImage = imagecreatefromstring($ImageType);

    $destX = $CurWidth - $watermarkWidth - $paddingFromBottomRight;
    $destY = $CurHeight - $watermarkHeight - $paddingFromBottomRight;

    // creating a cut resource
    $cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);

    // copying that section of the background to the cut
    imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);

    // placing the watermark now
    imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);

    // merging both of the images
    imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
}

0 个答案:

没有答案