php 实现:给图片加文字水印,图片水印,压缩图片

发布于:2024-06-02 ⋅ 阅读:(80) ⋅ 点赞:(0)

演示环境:
1、windows10
2、phpstudy
3、php7.4

一、案例演示:

在这里插入图片描述
在这里插入图片描述

二、素材准备

1、准备一张原始图片
2、准备一张水印图片(透明底图的最好)
3、字体库(windows系统自带的字体库,路径在:C:\Windows\Fonts)
4、开启GD库
在这里插入图片描述
在这里插入图片描述

三、图片添加水印

1、文字水印封装类 FontWatermark.class.php

<?php

class FontWatermark
{
   
    private $sourceImagePath;
    private $fontPath;
    private $fontSize;
    private $watermarkText;
    private $outputImagePath;

    public function __construct($sourceImagePath, $fontPath, $fontSize, $watermarkText, $outputImagePath)
    {
   
        $this->sourceImagePath = $sourceImagePath;
        $this->fontPath = realpath($fontPath);  // 获取字体文件的绝对路径
        $this->fontSize = $fontSize;
        $this->watermarkText = $watermarkText;
        $this->outputImagePath = $outputImagePath;
    }

    public function addFontWatermark()
    {
   
        // 加载源图片
        $sourceImage = imagecreatefromjpeg($this->sourceImagePath);
        if (!$sourceImage) {
   
            die('无法加载源图片');
        }

        // 获取源图片的宽高
        $sourceWidth = imagesx($sourceImage);
        $sourceHeight = imagesy($sourceImage);

        // 确保字体文件存在
        if (!file_exists($this->fontPath)) {
   
            die('字体文件不存在: ' . $this->fontPath);
        }

        // 设置文字颜色 (白色)
        $white = imagecolorallocate($sourceImage, 255, 255, 255);

        // 设置文字阴影颜色 (黑色)
        $black = imagecolorallocate($sourceImage, 0, 0, 0);

        // 计算文字水印的边界框
        $textBox = imagettfbbox($this->fontSize, 0, $this->fontPath, $this->watermarkText);
        if ($textBox === false) {
   
            die

网站公告

今日签到

点亮在社区的每一天
去签到