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

原创
2018/11/02 12:19
阅读数 2.3K

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

展开阅读全文
PHP
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部