您的位置 首页 php

php海报生成

 <?php
namespace app\service;

class PosterService{
  
    public static function create($config = [], $filename = ''){
        $imageDefault = array(
          'url'=>'图片路径'
            'left'    => 0,
            'top'     => 0,
            'width'   => 100,
            'height'  => 100,
            'opacity' => 100,
            'circle'  => 0
        );
        $qrcodeDefault = [
            'text'   => '二维码内存',
            'size'   => 100,
            'margin' => 2,
            'left'   => 0,
            'top'    => 0,
            'color'  => '0,0,0',
            'callback' => function(){}
        ];
        $textDefault =  array(
            'text'      => '文字内存',
            'left'      => 0,
            'top'       => 0,
            'align'       => '',//center
            'font-size' => 32,//字号
            'color'     => '0,0,0', //字体颜色
            'angle'     => 0,
            'font-path'  => '' //字体路径
        );

        $background = $config['background'];//海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);

        $backgroundWidth = imagesx($background);    //背景宽度
        $backgroundHeight = imagesy($background);   //背景高度

        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);

        //imageColorTransparent($imageRes, $color);    //颜色透明

        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));

        if (!empty($config['qrcode'])){
            foreach ($config['qrcode'] as $item){
                $item = array_merge($qrcodeDefault, $item);
                list($r,$b,$g) = explode(',', $item['color']);
                $item['color'] = ['r' => $r, 'g' => $b, 'b' => $g];
                $baseImage = imagecreatefromstring($item['callback']($item));
                $resWidth  = $resHeight = min(imagesx($baseImage), imagesy($baseImage));;
                //建立画板 ,缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($item['size'], $item['size']);
                // 码的背景颜色
                $color  = imagecolorallocate($canvas, 255, 255, 255);
                // 设置透明背景
                imagecolortransparent($canvas, $color);
                imagefill($canvas,0,0,$color);
                //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
                imagecopyresampled($canvas, $baseImage, 0, 0, 0, 0, $item['size'], $item['size'],$resWidth, $resHeight);

                imagecopymerge($imageRes, $canvas, $item['left'],$item['top'],0,0, $item['size'], $item['size'],100);
            }
        }
        //处理了图片
        if(!empty($config['image'])){
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val);

                $info = getimagesize($val['url']);
                if($val['circle']){       //如果传的是字符串图像流
                    $canvas = self::imageRadius($val['url'], $val['width']/2);
                }else{
                    $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                    $res = $function($val['url']);
                    $resWidth = $info[0];
                    $resHeight = $info[1];
                    //建立画板 ,缩放图片至指定尺寸
                    $canvas=imagecreatetruecolor($val['width'], $val['height']);
                    imagefill($canvas, 0, 0, $color);
                    //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
                    imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
                }
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'], $val['top'], 0, 0, $val['width'], $val['height'],$val['opacity']);//左,上,右,下,宽度,高度,透明度
                imagedestroy($canvas);
            }
        }

        //处理文字
        if(!empty($config['text'])){
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['color']);
                $color = imagecolorallocate($imageRes, $R, $G, $B);
                $arr = imagettfbbox($val['font-size'],0,$val['font-path'],$val['text']);
                $text_height = $arr[3] - $arr[5];
                if ($val['align'] == 'center'){
                    $text_width = $arr[2]-$arr[0];
                    $val['left'] = ($backgroundWidth - $text_width)/2;
                }else{
                    $val['left'] = $val['left'] < 0 ? $backgroundWidth- abs($val['left']):$val['left'];
                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight- abs($val['top']) : $val['top'];
                $val['top'] += $text_height;
                imagettftext($imageRes,$val['font-size'],$val['angle'],$val['left'],$val['top'],$color,$val['font-path'],$val['text']);
            }
        }

        //生成图片
        if(!empty($filename)){
            if ($filename == 'base64'){
                ob_start();
                imagepng($imageRes);//在浏览器上显示
                $string = strval(ob_get_contents());
                ob_end_clean();
                return 'data:image/png;base64,'.base64_encode($string);
            }
            $res = imagepng($imageRes, RUNTIME_PATH.'/'. $filename,90); //保存到本地
            imagedestroy($imageRes);
            if(!$res) return false;
            return $filename;
        }else{
            ob_start();
            imagepng($imageRes);//在浏览器上显示
            $string = strval(ob_get_contents());
            ob_end_clean();
            return $string;
        }
    }


    /**
     * 生成圆形
     * @param $image 图片地址
     * @param null $radius 半径
     * @return false|\GdImage|resource
     */    public static function imageRadius($image, $radius = null){
        /**
         * 处理圆形图
         * @param $image 图片地址
         * @return string
         */        $logo = imagecreatefromstring(file_get_contents($image));//源图象连接资源。
        $height = $width = min(imagesx($logo), imagesy($logo));
        if ($radius && $width / 2 < $radius){
            $new_w = $new_h = $radius * 2;
            $new   = imagecreatetruecolor($new_w, $new_h);
            imagecopyresized($new, $logo,0, 0,0, 0, $new_w, $new_h, $width, $height);
            $width  = $height = $new_w;
            $logo  = $new;
        }

        //创建一个和二维码图片一样大小的真彩色画布
        $canvas = imagecreatetruecolor($width, $height);
        $color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
        imagesavealpha($canvas, true);
        imagealphablending($canvas, false);
        imagefill($canvas, 0, 0, $color);
        imageColorTransparent($canvas, $color);
        $r = $width / 2;   //半径
        for ($x = 0; $x < $width; $x++) {
            for ($y = 0; $y < $height; $y++) {
                $rgb_color = imagecolorat($logo, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r) < ($r * $r)))) {
                    imagesetpixel($canvas, $x, $y, $rgb_color);
                }
            }
        }
        imagedestroy($logo);
        /*ob_start();
        imagepng($canvas);//在浏览器上显示
        $string = strval(ob_get_contents());
        ob_end_clean();
        file_put_contents(RUNTIME_PATH.'/avatar.png',$string);*/        return $canvas;
    }
}

  

使用方法

 $data = [
    'text' => [
        [
            'text' => $user['nickname'],
            'top' => 410,
            'align' => 'center',
            'font-path' =>'/home/wwwroot/public/static/SourceHanSansCN-Regular.otf'
        ]
    ],
    'qrcode' => [
        [
            'text'     => $redirect,
            'margin'   => 0,
            'left'     => 180,
            'top'      => 500,
            'size'     => 430,
            'callback' => function ($config) {
               $qrcode = new QrCode($item['text']);
                $qrcode->setForegroundColor($item['color']);
                $qrcode->setSize($item['size']);
                $qrcode->setMargin($item['margin']);
               return $qrcode->writeString();
            }
        ]
    ],
    'background' => '/home/wwwroot/public/share_poster'
];
// 二进制流
return PosterService::create($data);
// 返回base64
return PosterService::create($data,'base64');  

文章来源:智云一二三科技

文章标题:php海报生成

文章地址:https://www.zhihuclub.com/77282.shtml

关于作者: 智云科技

热门文章

评论已关闭

32条评论

  1. Packaging Size 10 Tablets Composition Anastrozole 1mg Brand Armotraz Manufacturer Cipla Treatment Breast cancer Prescription Non prescription Prescription Grade Standard Medicine Grade Packaging Type Box Form Tablet Storage Store at Room Temperature 10 30 Degree C Strength 1mg

  2. Trans 3, 4, 5 trihydroxystilbene resveratrol, a phytoalexin present in grapes and grape products such as wine, has been identified as a chemopreventive agent

  3. Interestingly, the protective vitamin D breast cancer association persisted only in premenopausal women, with a 33 risk reduction OR 0

  4. In addition, because of the side effects and inconvenience of parenteral administration of the first generation, second, and third generation of the aromatase inhibitors such as anastrozole, formestane and letrozole were developed 115

  5. Of relevance to this review, early onset endometrial cancer was reported in the mother and cousin aged 46 and 42 years of two brothers carrying the c

  6. 7 In addition, mice do not develop the ability to hear until approximately P12 and the organ of Corti is not fully mature until after P15

  7. Now, you can shop with confidence for form- fitting shirts that aren t several sizes too large for your stomach

  8. The marked effects of SGLT2is on HF outcomes in CV outcome trials, in which all patients had T2D by definition, led researchers to speculate whether these agents have a benefit in patients with HFrEF without T2D

  9. In MCF7, BT474, T47D and ZR75B transfection experiments we found that the reporter was correctly silent in the absence of added estradiol, and correctly induced with the addition of physiological levels of estradiol under normoxic conditions Fig

  10. HOW TO USE Read the Patient Information Leaflet if available from your pharmacist before you start taking fosamprenavir and each time you get a refill

  11. Robison stressed that while the incidence of serious chronic conditions among childhood cancer survivors has decreased since the 1970s, it is still higher than what is seen in the general population Armstrong et al

  12. Keywords Androgen; Estrogen; Hormone therapy; Melanoma; Steroid hormone receptors; Tamoxifen

  13. Watanabe T 2018 Improving outcomes for patients with distal renal tubular acidosis recent advances and challenges ahead

  14. Tamoxifen is an anti estrogen drug and inhibitor of the synthesis and release of cell growth factors 1985; 5 297 306

  15. Due to the blood flow, the question of payment security cannot be overstressed Ann N Y Acad Sci 2009 Feb; 1155 278 83 Wang et al Calcium antagonizing activity of S petasin, a hypotensive sesquiterpene from Petasites formosanus, on inotropic and chronotropic responses in isolated rat atria and cardiac myocytes

  16. 4, has an estimated half life of 2 3 h and is excreted more than 80 in the urine Lantus is available in a Solostar pen delivery system in a concentration of 100 units ml and in a 10 ml vial of the 100 units ml concentration

  17. The predominance of Tam effects on endometrial proliferation, morphology, and transcriptional profiles suggests that endometrial risks for E 2 Tam may be similar to Tam alone

  18. DCIS treatment consists of surgery and or radiation and the development of an early detection prevention plan I was diagnosed with PCOS a year ago

  19. At the time, I already had a flight booked to see my mom in a month, so I just made an appointment in Missouri

  20. To target angiogenesis and tumor growth in vivo and to deliver nanoparticle associated therapeutic or imaging agents specifically to tumor vasculature, nanoparticles are coupled to aptamers that selectively bind E selectin, such as ESTA 1

  21. NSAIDs, including CELEBREX, can lead to new onset of hypertension or worsening of preexisting hypertension, either of which may contribute to the increased incidence of CV events

网站地图