Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 737|回复: 0

php使用GD库将图片圆角 解决背景变黑问题 以及 图片丢失问题

[复制链接]
  • TA的每日心情
    奋斗
    7 天前
  • 签到天数: 803 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726482
    发表于 2021-6-5 12:57:53 | 显示全部楼层 |阅读模式
    if (!function_exists('gene_poster')) {
    
        function gene_poster($param)
        {
            $user = User::where(['id' => $param['user_id']])->find();
            $link = "http://".$_SERVER['SERVER_NAME'] . '/index/user/register/pid/' . $user['id'];
          /*  echo '<pre>';
            print_r($link);
            exit;*/
            $background = $param['background'];
            $nickname = $user['nickname'];
            $mobile = $user['mobile'];
            $avatar = $user['avatar'];
    
            $path = "../public/uploads/" . date('Ymd') . "/qrcode/";
            $poster_path = "../public/uploads/" . date('Ymd') . "/poster/";
    
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
    
            if (!is_dir($poster_path)) {
                mkdir($poster_path, 0777, true);
            }
    
            if (!$user['qrcode']) {
                /*1生成二维码存储*/
                $qr = new Endroid\QrCode\QrCode();
                $qr_code_img = $qr->setText($link)
                    ->setSize(300)
                    ->setPadding(10)
                    ->setErrorCorrection('high')
                    ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                    ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
                    ->setLabel('')
                    ->setLabelFontSize(16)
                    ->setImageType(Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
    
    
                //$path = "";
    
    
                $qrcode_file_name = $path . date('YmdHis') . $param['user_id'] . ".png";
                $re = $qr_code_img->save($qrcode_file_name);
                User::where(['id' => $param['user_id']])->update(['qrcode' => $qrcode_file_name]);
            } else {
                $qrcode_file_name = $user['qrcode'];
            }
    
            $font_path = '../public/assets/fonts/captcha.ttf';
            $font_path = 'D:\WORK\project\kangaroocollege\public\assets\fonts\fangzhengheitijianti.TTF';
            /*echo '<pre>';
            print_r(is_file($font_path));
            exit;*/
    
            /*2画图 保存*/
            $config = array(
                'text' => array(
                    array(
                        'text' => $nickname,
                        'left' => 350,
                        'top' => 2050,
                        'fontPath' => $font_path,     //字体文件
                        'fontSize' => 50,             //字号
                        'fontColor' => '255,255,255',       //字体颜色
                        'angle' => 0,
                    ),
    
                    array(
                        'text' => $mobile,
                        'left' => 350,
                        'top' => 2150,
                        'fontPath' => $font_path,     //字体文件
                        'fontSize' => 50,             //字号
                        'fontColor' => '255,255,255',       //字体颜色
                        'angle' => 0,
                    ),
    
                    array(
                        'text' => '我是你的专属客服',
                        'left' => 160,
                        'top' => 2250,
                        'fontPath' => $font_path,     //字体文件
                        'fontSize' => 60,             //字号
                        'fontColor' => '255,255,255',       //字体颜色
                        'angle' => 0,
                    ),
                    array(
                        'text' => '可向我咨询',
                        'left' => 160,
                        'top' => 2350,
                        'fontPath' => $font_path,     //字体文件
                        'fontSize' => 60,             //字号
                        'fontColor' => '255,255,255',       //字体颜色
                        'angle' => 0,
                    )
                ),
                'image' => array(
                    array(
                       // 'url' => $avatar,       //图片资源路径
                        'url' => border_radius($avatar),       //图片资源路径
                        'left' => 160,
                        'top' => 2000,
                        'stream' => 0,             //图片资源是否是字符串图像流
                        'right' => 0,
                        'bottom' => 0,
                        'width' => 150,
                        'height' => 150,
                        'opacity' => 100
                    ),
                    array(
                        'url' => $qrcode_file_name,
                        'left' => 900,
                        'top' => 2000,
                        'right' => 0,
                        'stream' => 0,
                        'bottom' => 0,
                        'width' => 400,
                        'height' => 400,
                        'opacity' => 100
                    ),
    
                ),
                'background' => $background,
            );
            $post_file_name = $poster_path . date('YmdHis') . $param['user_id'] . ".png";;
    //echo createPoster($config,$filename);
            return createPoster($config, $post_file_name);
    
        }
    }
    
    /**
     * 生成宣传海报
     * @param array  参数,包括图片和文字
     * @param string $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
     * @return bool|string [type] [description]
     */
    function createPoster($config = array(), $filename = "")
    {
    //    echo '<pre>';
    //    print_r($config);
    //  //  print_r($config['background']);
    //    exit;
        //如果要看报什么错,可以先注释调这个header
        //if (empty($filename)) header("content-type: image/png");
        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100
        );
        $textDefault = array(
            'text' => '',
            'left' => 0,
            'top' => 0,
            'fontSize' => 32,       //字号
            'fontColor' => '255,255,255', //字体颜色
            'angle' => 0,
        );
        $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['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) {   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
    
                //建立画板 ,缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
    
                /*echo '<pre>';
                print_r(1);
                exit;*/
                /* --- 用以处理缩放png图透明背景变黑色问题 开始 --- */
                if($key == 0){
                    $color = imagecolorallocatealpha($canvas,255,255,255,127);
                    imagecolortransparent($canvas,$color);
                    imagefill($canvas,0,0,$color);
                }
                /* --- 用以处理缩放png图透明背景变黑色问题 结束 --- */
    
    
                //关键函数,参数(目标资源,源,目标资源的开始坐标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'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左,上,右,下,宽度,高度,透明度
            }
        }
        //处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
    
    //            echo '<pre>';
    //            print_r($val['fontPath']);
    //            print_r(is_file($val['fontPath']));
    //            exit;
    
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
            }
        }
    
        //这一句一定要有
        imagealphablending( $imageRes,false );
    
        imagesavealpha($imageRes, true);
        //生成图片
        if (!empty($filename)) {
            $res = imagepng($imageRes, $filename, 5); //保存到本地
            imagedestroy($imageRes);
            if (!$res) return false;
            return $filename;
        } else {
            imagejpeg($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
        }
    }
    
    /**
     *图片修圆角
     */
    function border_radius($imgpath)
    {
        $ext = pathinfo($imgpath);
       /* echo '<pre>';
        print_r($ext);
        exit;*/
        $src_img = null;
        if(isset($ext['extension'])){
            switch ($ext['extension']) {
                case 'jpg':
                    $src_img = imagecreatefromjpeg($imgpath);
                    break;
                case 'png':
                    $src_img = imagecreatefrompng($imgpath);
                    break;
    
            }
        }else{
            $src_img = imagecreatefromjpeg($imgpath);
        }
    
        $wh = getimagesize($imgpath);
        $w = $wh[0];
        $h = $wh[1];
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagealphablending( $img,false );
    
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
    
        $avatar_path = "../public/uploads/" . date('Ymd') . "/avatar/";
    
    
        if (!is_dir($avatar_path)) {
            mkdir($avatar_path, 0777, true);
        }
    //    echo '<pre>';
    //    print_r($img);
    //    exit;
      //  file_put_contents($avatar_path.'avatar'.date('Ymd').".jpg",$img);
        $filename = $avatar_path.'avatar'.date('Ymd').".png";
        header("content-type:image/png");
        imagepng($img, $filename, 5); //保存到本地
      /*  imagepng($img);
        imagedestroy($img);
        exit;*/
        return $filename;
    }
    

      

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-11-24 11:07 , Processed in 0.064873 second(s), 30 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表