php---在图片上写字

在做开发的时候,经常会需要用到图片和文字结合,比如做海报等。

具体代码:

// 生成图片
public function createimg()
{

    // 1. 创建画布(从现有图片或新建)
    $imagePath = 'bg4.jpg';
    $image = imagecreatefromjpeg($imagePath); // 支持 JPEG/PNG/GIF

    // 2. 设置颜色(RGB)
    $textColor = imagecolorallocate($image, 255, 0, 255); // 白色
    $bgColor = imagecolorallocate($image, 0, 0, 0);        // 黑色(备用)

    // 3. 设置字体(需指定字体文件路径)
    $fontFile = 'Arial.ttf'; // 确保服务器上有此字体文件
    $fontSize = 20;

    // 4. 写入文字(参数:图像, 字号, 角度, X坐标, Y坐标, 颜色, 字体文件, 文字内容)
    $text = "Hello, PHP!";

    // 添加文字(使用系统字体)
    imagestring($image, 5, 50, 50, $text, $black);
    imagettftext($image, $fontSize, 0, 50, 100, $textColor, $fontFile, $text);

    // 5. 输出图像
    header('Content-Type: image/jpeg');
    imagejpeg($image);

    // 或保存到文件
    // imagejpeg($image, 'output-2.jpg');

    // 6. 释放内存
    imagedestroy($image);
}

打完收工!

posted @ 2025-07-12 09:36  帅到要去报警  阅读(18)  评论(0)    收藏  举报