php绘图添加水印,文字使用imagick库的操作

1.创建画布或者使用图片创建背景图

php 复制代码
  /**
     * 创建或加载背景画布
     */
    static function backgroundImage($backgroundImagePath = '')
    {
        if (!file_exists($backgroundImagePath) || !is_readable($backgroundImagePath)) {
            // 下载远程图片并本地缓存
            $imageData = file_get_contents($backgroundImagePath);
            $path = 'uploads/qr_images/backgroundImagePath.png';
            file_put_contents($path, $imageData);
            $backgroundImagePath = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
        }

        try {
            self::$canvas = new Imagick($backgroundImagePath);
        } catch (\Exception $e) {
            throw new \Exception("无法加载背景图: " . $e->getMessage());
        }
    }

2.添加文字到画布上,需要获取字体,然后就是设置了颜色和字体的位置

php 复制代码
    /**
     * 添加文字到画布上
     */
    static function text($text, $fontSize, $x, $y, $color, $statusX = '', $statusY = '')
    {
        $fontPath = $_SERVER['DOCUMENT_ROOT'] . '/assets/fonts/SourceHanSansK-Regular.ttf';

        // 创建绘图对象
        $draw = new ImagickDraw();
        $draw->setFont($fontPath);
        $draw->setFontSize($fontSize);

        // 设置颜色
        $colorStr = sprintf('rgb(%d,%d,%d)', $color[0], $color[1], $color[2]);
        $draw->setFillColor(new ImagickPixel($colorStr));

        // 对齐方式处理
        $width = self::getTextWidth($text, $fontSize, $fontPath);
        $height = self::getTextHeight($text, $fontSize, $fontPath);

        switch ($statusX) {
            case 'center':
                $x = (self::$canvas->getImageWidth() - $width) / 2;
                break;
            case 'left':
                $x = 0;
                break;
            case 'right':
                $x = self::$canvas->getImageWidth() - $width;
                break;
        }

        switch ($statusY) {
            case 'center':
                $y = (self::$canvas->getImageHeight() - $height) / 2 + $height;
                break;
            case 'top':
                $y = $height;
                break;
            case 'bottom':
                $y = self::$canvas->getImageHeight() - $height;
                break;
        }

        // 绘制文本
        self::$canvas->annotateImage($draw, $x, $y, 0, $text);
    }
php 复制代码
/**
 * 获取文字宽度
 */
static function getTextWidth($text, $fontSize, $fontPath)
{
    $draw = new ImagickDraw();
    $draw->setFont($fontPath);
    $draw->setFontSize($fontSize);
    $metrics = self::$canvas->queryFontMetrics($draw, $text);
    return $metrics['textWidth'];
}

/**
 * 获取文字高度
 */
static function getTextHeight($text, $fontSize, $fontPath)
{
    $draw = new ImagickDraw();
    $draw->setFont($fontPath);
    $draw->setFontSize($fontSize);
    $metrics = self::$canvas->queryFontMetrics($draw, $text);
    return $metrics['textHeight'];
}

3.添加水印,其中设置位置

php 复制代码
    /**
     * 添加图片水印
     */
    static function image($imagePath, $x, $y, $statusX = '', $statusY = '')
    {
        if (!file_exists($imagePath) || !is_readable($imagePath)) {
            $imageData = file_get_contents($imagePath);
            $path = 'uploads/qr_images/headimgurl.png';
            file_put_contents($path, $imageData);
            $imagePath = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;

        try {
            $image = new Imagick($imagePath);
        } catch (\Exception $e) {
            throw new \Exception("无法加载水印图: " . $e->getMessage());
        }

        $imageWidth = $image->getImageWidth();
        $imageHeight = $image->getImageHeight();

        switch ($statusX) {
            case 'center':
                $x = (self::$canvas->getImageWidth() - $imageWidth) / 2;
                break;
            case 'left':
                $x = 0;
                break;
            case 'right':
                $x = self::$canvas->getImageWidth() - $imageWidth;
                break;
        }

        switch ($statusY) {
            case 'center':
                $y = (self::$canvas->getImageHeight() - $imageHeight) / 2;
                break;
            case 'top':
                $y = 0;
                break;
            case 'bottom':
                $y = self::$canvas->getImageHeight() - $imageHeight;
                break;
        }

        self::$canvas->compositeImage($image, Imagick::COMPOSITE_DEFAULT, $x, $y);
    }

4.保存图像

php 复制代码
/**
 * 保存图像
 */
static function save($outPath = '')
{
    $outPath = $outPath ?: 'uploads/qr_images/';
    if (!file_exists($outPath)) {
        mkdir($outPath, 0755, true);
    }

    $fileName = 'watermark_' . md5(time() . random_int(1000, 9999)) . '.png';
    $filePath = $outPath . $fileName;

    try {
        self::$canvas->writeImage($filePath);
        self::$canvas->clear();
        self::$canvas->destroy();
    } catch (\Exception $e) {
        return Tools::set_fail("保存失败:" . $e->getMessage());
    }

    return $filePath;
}

5.调用绘图添加水印和文字

这里的image是控制器,上方的方法都是写在其中的

相关推荐
yong99904 分钟前
基于C#与三菱FX5U PLC实现以太网通信
网络·c#·php
wxin_VXbishe2 小时前
springboot居家养老管理系统-计算机毕业设计源码55953
java·c++·spring boot·python·spring·django·php
老兵发新帖5 小时前
ubuntu网络管理功能分析
数据库·ubuntu·php
毕设源码-钟学长6 小时前
【开题答辩全过程】以 基于PHP的家常菜谱教程网站为例,包含答辩的问题和答案
开发语言·php
星光一影7 小时前
美容/心理咨询/问诊/法律咨询/牙医预约/线上线下预约/牙医行业通用医疗预约咨询小程序
mysql·小程序·vue·php·uniapp
jllllyuz8 小时前
基于遗传算法的33节点配电网网络重构MATLAB实现
matlab·重构·php
白狐_7989 小时前
计算机网络复习全书(详细整理)
开发语言·计算机网络·php
bing.shao9 小时前
Golang select多路复用踩坑
数据库·golang·php
catchadmin9 小时前
Laravel + Vue3 前后端分离开源后台管理框架 CatchAdmin v5.0 Beta 发布
php·laravel
郑州光合科技余经理10 小时前
解决方案:全球化时代下的海外版外卖系统
大数据·开发语言·前端·javascript·人工智能·架构·php