PHP图片加文字水印,保存图片文件,并浏览器输出显示

本文介绍了一个使用PHP为图片添加文字水印的方法。通过定义函数attach_text_logo,可以将指定的文字水印添加到图片上,同时调整字体颜色、大小及位置。代码支持多种图片格式,包括jpg、png、gif和bmp。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP实现代码:

<?php
function attach_text_logo($imgFilePath, $textLogo) {
    //创建图片的实例
    $im = imagecreatefromstring(file_get_contents($imgFilePath));
    list($width, $height, $type, $attr) = getimagesize($imgFilePath);

    // 水印字体颜色
    $textColor = imagecolorallocate($im, 0xcc, 0xcc, 0xcc);
    // 水印字体大小
    $textSize = 10;

    // 下载地址(放到本地):https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf
    $fontFile = './arial.ttf';

    // 添加文字水印
    imagefttext($im, $textSize, 0, $width - 80, $height - 10, $textColor, $fontFile, $textLogo);

    // 保存文件 git/jpg/png/bmp
    $savePath = tempnam("/tmp", "pic");
    switch($type)
    {
    case 1:
        imagegif($im, $savePath);
        break;
    case 2:
        imagejpeg($im, $savePath);
        break;
    case 3:
        imagepng($im, $savePath);
        break;
    case 6:
        imagewbmp($im, $savePath);
        break;
    }

    imagedestroy($im);

    return $savePath;
}

// 加水印,并生成临时文件
$tmp = attach_text_logo('./a.jpg', '@dogstar');

// 直接输出到浏览器
$im = imagecreatefromstring(file_get_contents($tmp));
header('Content-Type: image/jpg');
imagejpeg($im);
imagedestroy($im);

 

运行效果:

 

注意点:

字体文件要下载到本地:https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf

将文本写入图像参考:http://php.net/manual/zh/function.imagefttext.php

转载于:https://my.oschina.net/dogstar/blog/2413698

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值