php 图像处理和 GD 合并图片和往图片上写文字

使用php原生GD库,在已有的一张图片上写入文字,并且将另一张图片也加到原图片上。

<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
$font_file = './arial.ttf';

// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');

// Output image to the browser

//将另一张图片合并到图片上
imagecopymerge($im, $img2, 50, 970, 0, 0, 200, 200, 100);

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

注意:将两张图片合并时,需要考虑到图片的透明度。

将中文写在图片上时需要考虑到编码,和写入方式(一次性写入很多汉字,还是逐字写入,要写入很多汉字时,需要计算文字排版位置等)

$img = imagecreatefromstring($imgRes);
//注意这里
imagesavealpha($img, true);
imagecopy($im, $img, 296, 490, 0, 0, 158, 152);

//写入汉字,一行15个字
for ($i = 0; $i < mb_strlen($text); $i++) {
                $line = floor($i / 15);
                $x = 175 + $width * ($i - 15 * $line);
                imagettftext($im, 16, 0, $x, $y + $height * $line, $fontColor, $defaultFont, mb_substr($text, $i, 1));
            }
get
dirname(__DIR__) //根目录
mb_substr()
mb_strlen()
strlen()