技术饭

php通过GD库生成简单的印章图片

copylian    0 评论    7890 浏览    2023.06.23

php通过GD库生成简单的印章图片,GD库是php处理图形的扩展库,GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片,也可以给图片加水印。php的gd库有很多的函数可以生成各式各样的图片,比如电子印章、电子公司盖章等等。

function getSealImg($name = ""){

        //在图像上写入文本

        //  $font = 'simsun.ttc';

        $font = 'STZHONGS.TTF';

        $width = 120;

        $height = 120;

        $thickness = 2; //线条边框粗细

        $fontsize = 38; //字体大小

        //创建图像对象

        $image = imagecreatetruecolor($width, $height);

        //设置背景颜色和文本颜色

        $bg_color = imagecolorallocatealpha($image , 255 , 255 , 255, 127); //透明背景

        $text_color = imagecolorallocate($image, 255, 0, 0); //文本颜色

        $rect_color = imagecolorallocate($image, 255, 0, 0); //边框红色

        

        //填充背景色

        imagefill($image, 0, 0, $bg_color);

        //设置透明

        imagecolortransparent($image, $bg_color);

        //边框粗细

        imagesetthickness($image, $thickness);

        //画一个矩形

        imagerectangle($image, 0, 1, $width - $thickness, $height - $thickness, $rect_color);

        //添加文本

        $nameArr = mb_str_split($name);

        $top = 15;

        $left = 10;

        //获取字体大小

        $box = imagettfbbox($fontsize, 0, $font, $nameArr[0]);

        $fontHeight = $box[3] - $box[5];

        $fontWidth = $box[4] - $box[6];

        //写入文字

        if(isset($nameArr[0])){

                imagettftext($image, $fontsize, 0, $width - $fontWidth - $left,$fontHeight, $text_color, $font, $nameArr[0]);

        }

        if(isset($nameArr[1])) {

                imagettftext($image, $fontsize, 0, $width - $fontWidth - $left, $height - $top, $text_color, $font, $nameArr[1]);

        }

        if(isset($nameArr[2])) {

                imagettftext($image, $fontsize, 0, $left-2, $fontHeight, $text_color, $font, $nameArr[2]);

        }

        if(isset($nameArr[3])) {

                imagettftext($image, $fontsize, 0, $left-2, $height - $top, $text_color, $font, $nameArr[3]);

        }

        //创建缓冲区

        ob_start();

        

        //保存图像

        imagepng($image);

        $buffer = ob_get_clean();

        //  ob_end_clean();

        $base64 = base64_encode($buffer);

        $imageData = 'data:'. "image/png" . ';base64,' . $base64;

        return $imageData;

}


$name = "丁世强印";

echo getSealImg($name);


执行结果:

下载.png


只袄早~~~
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!
php gd 印章 

文明上网理性发言!

  • 还没有评论,沙发等你来抢