晓夏

北漂的女孩

Good Luck To You!

php+GD库生成推广图-微信推广

浏览量:439

图片.png

<?php
/**
 * 批量导入csv文件
 * @author lianghuiju@chuchujie.com
 * @lastModifyTime 2018/05/26
 * @lastModify lianghuiju@chuchujie.com
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>批量生成图片</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div style="margin: 10px auto 12px;padding-left: 50px;clear: both;">
    <span style="position: relative;margin-right: 8px;border-radius: 5px;display: inline-block;width: 300px;height: 30px;border: 1px solid #bbb;">
        <input type="text" id="text-input" style="margin: 0;width: 286px;height: 22px;border: none;" placeholder= "选择文件"/>
        <input type="file" id="file-input" style="position: absolute;margin: 0;top: 0;left: 0;width: 300px;height: 30px;filter:alpha(opacity=0);-moz-opacity:0.0;-khtml-opacity: 0.0;opacity: 0.0;cursor:pointer;" title="点击上传"/>
    </span>
    <input type="radio" name="type" checked="checked" value='1' /><label style="display: inline-block">长条形</label>
    <input type="radio" name="type" value='2' /><label style="display: inline-block">正方形</label>
    <input type="radio" name="type" value='3' /><label style="display: inline-block">打标</label>
    &nbsp;&nbsp;
 <button id="batch-import" class="btn btn-success" >开始生成图片</button>
</div>
<div style="margin: 10px auto 12px;padding-left: 50px;clear: both;" >
    <p id="import-status">待导入...</p>
    <div style="width: 370px;height: 16px;border: 1px solid #ccc;border-radius: 10px;float: left;">
        <span id="progress-status" style="display: inline-block;background: #85c440;border-radius: 10px;height: 18px;"></span>
    </div>
    <div id="progress-text" style="margin-left:3px; width: 40px; text-align:right; height:18px;line-height:18px;float:left;">0%</div>
    <div style="padding-left: 50px;clear: both;">
        <ul style="margin-top: 12px;padding: 6px 0 4px;line-height: 30px;" id="error-list"></ul>
    </div>
</div>
<div style="margin: 10px auto 12px;padding-left: 50px;clear: both;" >
    <a href="createImg.php" target="_blank" style="font-size: 16px">手动生成图片</a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <a href="limitTimeBuy.php" target="_blank" style="font-size: 16px">生成限时抢图片</a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <a href="tbToastImg.php" target="_blank" style="font-size: 16px">生成淘宝商品弹窗图</a>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var url = "/123/admin/app.php?method=createMpCardImg";

 $(document).ready(function(){
        $('#batch-import').bind('click', startImport);
 $('#file-input').change(function(){
            $('#text-input').val(this.value);
 });
 });

 var pushData = [];
 var dataLength = 0;
 var statusHint = $('#import-status');
 var type = '';

 function startImport() {
        type = $('input[name="type"]:checked').val();
 if (typeof FileReader === "undefined"){
            alert("请使用最新版Chrome浏览器");
 return;
 }
        var fileInput = $('#file-input');//获取文件组件对象
 if (fileInput.length < 1 || typeof fileInput[0].files === "undefined"){
            alert("没有找到文件上传控件");
 return;
 }
        if (fileInput[0].files.length < 1){
            alert("请选择要导入的文件");
 return;
 }
        var rltFile = fileInput[0].files[0];//获取文件信息对象
 var ext = /\.[^\.]+/.exec(rltFile.name);
 if (ext[0] !== ".csv"){
            alert("文件格式不正确,请导入csv文件");
 return;
 }
        var buttonObj = $(this); //按钮对象
 buttonObj.attr("disabled", true);
 statusHint.text('导入中...');

 var fileReader = new FileReader();//new一个文件读取对象
 fileReader.readAsText(rltFile, "GB2312");
 fileReader.onload = function (ev) {
            var lines = fileReader.result.split("\n");

 for (var i = 1; i <= lines.length; i++){ //从1开始,不读表头
 if (!lines[i] || typeof lines[i].split === "undefined"){ continue; }
                var tempData = lines[i].split(",");
 var data = {
                    "type" : type,
 "product_name"  : tempData[0],
 "product_id"   : tempData[1],
 "product_price": tempData[2],
 "product_benefit_one": tempData[3],
 "product_benefit_two": tempData[4]
                };

 pushData.push(data)
            }
            dataLength = pushData.length;

 startPush();
 };
 }

    function startPush() {
        if (dataLength < 0) {
            statusHint.text("没有数据被导入");
 return;
 }
        var progress = $('#progress-status');
 var pt = $('#progress-text');
 var eul = $('#error-list');
 var downloadAct = document.getElementById('download_img');
 var imgBlob = null;
 var url = null;

 if (pushData.length <= 0) {
            statusHint.text('导入完成!');
 progress.css('width', '100%');
 pt.text('100%');
 $('#btn-import').attr('disabled', false);
 return;
 } else {
            var w = Math.round(((dataLength - pushData.length) / dataLength) * 100);
 progress.css('width', w + '%');
 pt.text(w + '%');
 }
        var item = pushData.shift(); //删除一个元素并返回元素的值
 $.ajax({
            url     : url,
 type    : 'POST',
 data    : item,
 dataType: 'json',
 success : function(d){
                if (0 == parseInt(d.errno)) {
                    imgBlob = dataURLtoBlob(d.data.image);
 url = URL.createObjectURL(imgBlob);
 downloadAct.setAttribute('href',url);
 downloadAct.setAttribute('download', item.product_id + '.jpg');
 downloadAct.click();

 } else {
                    eul.append($('<li>'+item.product_name+':'+item.product_id+'['+d.msg+']</li>'));
 }
                startPush();
 }
        });
 }

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
 while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
 }
        return new Blob([u8arr], { type: mime });
 }
</script>
</body>
</html>

生成原始图片:

图片.png图片.png图片.png


图片.png图片.png


php后台操作

<?php
define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);

$method = trim($_REQUEST['method']);
if ($method == "createMpCardImg") {
    $res = createMpCardImg();
}else if($method == "createLimitBuyCardImg"){
    $res = createLimitBuyCardImg();
}else if( $method =='createTbToastImg'){
    $res = createTbToastImg();
}
/**
 * 生成宣传图
 * author        :lianghuiju@chuchujie.com
 * function_name : createMpCardImg
 * datetime      : 2019/6/21
 * description   :
 */
function createMpCardImg() {
    $productName = $_REQUEST['product_name'];
    $productId = trim($_REQUEST['product_id']);
    $productPrice = $_REQUEST['product_price'];
    $productBenefitOne = isset($_REQUEST['product_benefit_one']) ? $_REQUEST['product_benefit_one'] : '';
    $productBenefitTwo = isset($_REQUEST['product_benefit_two']) ? $_REQUEST['product_benefit_two'] : '';
    $type = $_REQUEST['type'];
    $downloadType = isset($_REQUEST['download_type']) ? $_REQUEST['download_type'] : 0;
    $downloadType = isset($downloadType) ? $downloadType : 0;
    if (empty($productId) || !is_numeric($productId) || empty($type)) {
        renderOutput(array(), 1, 'param error', true);
    }
    $productBenefit = $productBenefitOne . ' ' . $productBenefitTwo;

    $productDetailUrl = 'https://api-product.chuchujie.com/api.php';
    $data = array(
        'channel' => 'QD_appstore',
        'package_name' => 'com.culiukeji.huanletao',
        'client_version' => '3.9.101',
        'ageGroup' => 'AG_0to24',
        'client_type' => 'WAP',
        'api_version' => 'v5',
        'imei' => '',
        'gender' => '1',
        'token' => '',
        'userId' => '',
        'front_version' => '201801041124',
        'method' => 'product_detail',
        'product_id' => $productId
    );
    $productData = array('data' => json_encode($data));
    $headers = array('content-type' => 'application/x-www-form-urlencoded', 'charset' => 'UTF-8');
    $productDetail = httpPost($productDetailUrl, $productData, $headers, true);
    if (empty($productDetail['data']['product'])) {
        renderOutput(array(), 1, '获取商品信息错误', true);
    }

    $productImg = $productDetail['data']['product']['image_urls_head'][0];


    $handleText = function ($text) {
        mb_internal_encoding("UTF-8");
        $len = mb_strlen($text);
        if ($len > 10) {
            $text = substr_replace($text, '...', 30);
        }

        return $text;
    };
    //设置字体路径
    putenv('GDFONTPATH=' . realpath('.'));
    $font = ROOT_PATH."font/PingFang.ttc";

    if ($type == 1) {
        //打开底图
        $im = @imagecreatefromjpeg(ROOT_PATH.'images/mp_card_cfx.jpg');
        if (!$im) {
            renderOutput(array(), 2, 'get image failed', true);
        }

        $page_width = 744;   //图片标准宽度
        $name_font_size = 26;
        $copy_img_size = 250;

        $black = imagecolorallocate($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        $ccjRed = imagecolorallocate($im, 227, 51, 93);
        $red = imagecolorallocate($im, 255, 0, 0);

        //处理商品图
        $goods_tmp_str = file_get_contents($productImg);
        $goods_im = imagecreatetruecolor($copy_img_size, $copy_img_size);
        imagefill($goods_im, 0, 0, $white);
        if ($goods_tmp_str) {
            $goods_tmp_im = imagecreatefromstring($goods_tmp_str);
            if (is_resource($goods_tmp_im)) {
                imagecolorallocate($goods_im, 255, 255, 255);
                $g_src_w = imagesx($goods_tmp_im);
                $g_src_h = imagesy($goods_tmp_im);
                imagecopyresized($goods_im, $goods_tmp_im, 0, 0, 0, 0, $copy_img_size, $copy_img_size, $g_src_w, $g_src_h);
            } else {
                renderOutput(array(), 3, 'create image failed', true);
            }
        } else {
            renderOutput(array(), 4, 'create image failed', true);
        }

        imagecopy($im, $goods_im, 30, 26, 0, 0, $copy_img_size, $copy_img_size); //商品图

        //处理商品名
        $name1Lines = $productName;
        $name1_x = 325;
        imagettftext($im, $name_font_size, 0, $name1_x, 55, $black, $font, $name1Lines);
        imagettftext($im, $name_font_size, 0, $name1_x, 55, $black, $font, $name1Lines);

        //处理利益点
        $name2Lines = $productBenefit;
        $name2_x = 330;
        imagettftext($im, 21, 0, $name2_x, 130, $black, $font, $name2Lines);

        //处理价格
        $name3Lines = $productPrice;
        $name3_x = 465;
        imagettftext($im, 29, 0, $name3_x, 265, $ccjRed, $font, $name3Lines);
    } else if ($type == 2) {
        //打开底图
        $im = @imagecreatefromjpeg(ROOT_PATH.'images/mp_card_zfx.jpg');

        if (!$im) {
            renderOutput(array(), 2, 'get image failed', true);
        }

        $page_width = 364;   //图片标准宽度
        $name_font_size = 24;
        $copy_img_size = 358;

        $black = imagecolorallocate($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        $ccjRed = imagecolorallocate($im, 227, 51, 93);
        $red = imagecolorallocate($im, 255, 0, 0);

        //处理商品图
        $goods_tmp_str = file_get_contents($productImg);
        $goods_im = imagecreatetruecolor($copy_img_size, $copy_img_size);
        imagefill($goods_im, 0, 0, $white);
        if ($goods_tmp_str) {
            $goods_tmp_im = imagecreatefromstring($goods_tmp_str);
            if (is_resource($goods_tmp_im)) {
                imagecolorallocate($goods_im, 255, 255, 255);
                $g_src_w = imagesx($goods_tmp_im);
                $g_src_h = imagesy($goods_tmp_im);
                imagecopyresized($goods_im, $goods_tmp_im, 0, 0, 0, 0, $copy_img_size, $copy_img_size, $g_src_w, $g_src_h);
            } else {
                renderOutput(array(), 3, 'create image failed', true);
            }
        } else {
            renderOutput(array(), 4, 'create image failed', true);
        }

        imagecopy($im, $goods_im, 3, 10, 0, 0, $copy_img_size, $copy_img_size); //商品图

        //处理商品名
        $name1Lines = $productName;
        $name1Bbox = imagettfbbox($name_font_size, 0, $font, $name1Lines);
        $name1_width = $name1Bbox[4] - $name1Bbox[0];
        $name1_x = round($page_width / 2) - round($name1_width / 2);
        $name1_y = 410;
        imagettftext($im, $name_font_size, 0, $name1_x, $name1_y, $black, $font, $name1Lines);
        imagettftext($im, $name_font_size, 0, $name1_x, $name1_y, $black, $font, $name1Lines);

        //处理价格
        $name3Lines = $productPrice;
        $name3_x = 138;
        imagettftext($im, 27, 0, $name3_x, 456, $red, $font, $name3Lines);
    } else if ($type == 3) {
        //打开底图
        $im = @imagecreatefromjpeg(ROOT_PATH.'images/99base.jpg');

        if (!$im) {
            renderOutput(array(), 2, 'get image failed', true);
        }

        $page_width = 400;   //图片标准宽度
        $copy_img_size = 400;

        $black = imagecolorallocate($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        $ccjRed = imagecolorallocate($im, 227, 51, 93);
        $red = imagecolorallocate($im, 255, 0, 0);

        //处理商品图
        $goods_tmp_str = file_get_contents($productImg);
        $goods_im = imagecreatetruecolor($copy_img_size, $copy_img_size);
        imagefill($goods_im, 0, 0, $white);
        if ($goods_tmp_str) {
            $goods_tmp_im = imagecreatefromstring($goods_tmp_str);
            if (is_resource($goods_tmp_im)) {
                imagecolorallocate($goods_im, 255, 255, 255);
                $g_src_w = imagesx($goods_tmp_im);
                $g_src_h = imagesy($goods_tmp_im);
                imagecopyresized($goods_im, $goods_tmp_im, 0, 0, 0, 0, $copy_img_size, $copy_img_size, $g_src_w, $g_src_h);
            } else {
                renderOutput(array(), 3, 'create image failed', true);
            }
        } else {
            renderOutput(array(), 4, 'create image failed', true);
        }

        imagecopy($im, $goods_im, 3, 10, 0, 0, $copy_img_size, $copy_img_size); //商品图

        //处理角标图
        $mark_tmp_str = file_get_contents(ROOT_PATH.'images/99mark.png');
        $mark_im = imagecreatetruecolor(150, 60);
        imagesavealpha($mark_im, true);
        $hyaline = imagecolorallocatealpha($mark_im, 255, 0, 0, 127);
        imagefill($mark_im, 0, 0, $hyaline);

        if ($mark_tmp_str) {
            $mark_tmp_im = imagecreatefromstring($mark_tmp_str);
            if (is_resource($mark_tmp_im)) {
                imagecolorallocate($mark_im, 255, 255, 255);
                $g_src_w = imagesx($mark_tmp_im);
                $g_src_h = imagesy($mark_tmp_im);
                imagecopyresized($mark_im, $mark_tmp_im, 0, 0, 0, 0, 150, 60, $g_src_w, $g_src_h);
            } else {
                renderOutput(array(), 3, 'create image failed', true);
            }
        } else {
            renderOutput(array(), 4, 'create image failed', true);
        }

        imagecopy($im, $mark_im, 0, 0, 0, 0, 150, 60); //角标图

        //$imMark = @imagecreatefrompng(ROOT_PATH.'images/99mark.png');
        //imagecopymerge($im, $imMark,0,0,0,0,150,60,100);
    }

    ob_start();
    imagejpeg($im, NULL, 100); //图片质量 100
    $contents = ob_get_clean();
    //header("Content-Type: image/jpeg");
    //echo $contents;

    if ($downloadType) {
        $finishFileName = $productId . '.jpg';
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $finishFileName);
        header('Content-Transfer-Encoding: binary');
        echo $contents;
        exit();
    }

    $imageContents = 'data:image/jpeg;base64,' . base64_encode($contents);
    $data = array('image' => $imageContents);

    renderOutput($data, 0, 'success', true);
}

/**
 * 生成限时抢图片
 * author        :lianghuiju@chuchujie.com
 * function_name : createLimitBuyCardImg
 * datetime      : 2019/6/21
 * description   :
 */
function createLimitBuyCardImg() {
    $scene = $_REQUEST['scene'];
    $productOneId = $_REQUEST['product_one_id'];
    $productOnePrice = $_REQUEST['product_one_price'];
    $productTwoId = $_REQUEST['product_two_id'];
    $productTwoPrice = $_REQUEST['product_two_price'];
    $productThreeId = $_REQUEST['product_three_id'];
    $productThreePrice = $_REQUEST['product_three_price'];

    $productOneId = trim($productOneId);
    $productTwoId = trim($productTwoId);
    $productThreeId = trim($productThreeId);

    if (empty($productOneId) || empty($productTwoId) || empty($productThreeId)) {
        echo "<script>alert('参数错误');window.history.back(-1);</script>";
        die;
    }

    $productIds = array($productOneId, $productTwoId, $productThreeId);
    $productPriceArr = array($productOnePrice, $productTwoPrice, $productThreePrice);

    $productDetailUrl = 'https://api-product.chuchujie.com/api.php';
    $productInfo = array();
    $finishFileName = '';
    foreach ($productIds as $k => $productId) {
        $data = array(
            'channel' => 'QD_appstore',
            'package_name' => 'com.culiukeji.huanletao',
            'client_version' => '3.9.101',
            'ageGroup' => 'AG_0to24',
            'client_type' => 'WAP',
            'api_version' => 'v5',
            'imei' => '',
            'gender' => '1',
            'token' => '',
            'userId' => '',
            'front_version' => '201801041124',
            'method' => 'product_detail',
            'product_id' => $productId
        );
        $productData = array('data' => json_encode($data));
        $headers = array('content-type' => 'application/x-www-form-urlencoded', 'charset' => 'UTF-8');
        $productDetail = httpPost($productDetailUrl, $productData, $headers, true);

        if (empty($productDetail['data']['product'])) {
            echo "<script>alert('获取商品信息错误,商品id-' + $productId);window.history.back(-1);</script>";
            die;
        }

        $productInfo[$k]['productImg'] = $productDetail['data']['product']['image_urls_head'][0];
        $productInfo[$k]['productPrice'] = $productPriceArr[$k];

        $finishFileName .= $productId . '-';
    }
    $finishFileName = rtrim($finishFileName, '-');
    $finishFileName .= '.jpg';

    //设置字体路径
    putenv('GDFONTPATH=' . realpath('.'));
    $font = ROOT_PATH.'font/PingFang.ttc';

    //打开底图
    $baseImgFilePath = ROOT_PATH.'images/limit' . $scene . '.jpg';
    $im = imagecreatefromjpeg($baseImgFilePath);

    if (!$im) {
        echo "<script>alert('获取模板图错误'); window.history.back(-1);</script>";
        die;
    }

    $price_font_size = 22;
    $copy_img_size = 232;

    $black = imagecolorallocate($im, 0, 0, 0);
    $white = imagecolorallocate($im, 255, 255, 255);
    $ccjRed = imagecolorallocate($im, 227, 51, 93);
    $red = imagecolorallocate($im, 255, 0, 0);

    foreach ($productInfo as $k => $subProductInfo) {
        $productImg = $subProductInfo['productImg'];
        $productPrice = $subProductInfo['productPrice'];

        //处理商品图
        $goods_tmp_str = file_get_contents($productImg);
        $goods_im = imagecreatetruecolor($copy_img_size, $copy_img_size);
        imagefill($goods_im, 0, 0, $white);
        if ($goods_tmp_str) {
            $goods_tmp_im = imagecreatefromstring($goods_tmp_str);
            if (is_resource($goods_tmp_im)) {
                imagecolorallocate($goods_im, 255, 255, 255);
                $g_src_w = imagesx($goods_tmp_im);
                $g_src_h = imagesy($goods_tmp_im);
                imagecopyresized($goods_im, $goods_tmp_im, 0, 0, 0, 0, $copy_img_size, $copy_img_size, $g_src_w, $g_src_h);
            } else {
                echo "<script>alert('构造商品图错误');window.history.back(-1);</script>";
                die;
            }
        } else {
            echo "<script>alert('创建商品图错误');window.history.back(-1);</script>";
            die;
        }
        if ($k == 0) {
            $img_x = 58;
            $price_x = 208;
        } else if ($k == 1) {
            $img_x = 343;
            $price_x = 494;
        } else {
            $img_x = 629;
            $price_x = 784;
        }

        $img_y = 92;
        $price_y = 356;
        imagecopy($im, $goods_im, $img_x, $img_y, 0, 0, $copy_img_size, $copy_img_size); //商品图

        //处理价格
        imagettftext($im, $price_font_size, 0, $price_x, $price_y, $red, $font, $productPrice);
        imagettftext($im, $price_font_size, 0, $price_x, $price_y, $red, $font, $productPrice);
        imagettftext($im, $price_font_size, 0, $price_x + 2, $price_y, $red, $font, $productPrice);
        imagettftext($im, $price_font_size, 0, $price_x + 2, $price_y, $red, $font, $productPrice);
    }

    ob_start();
    imagejpeg($im, null, 100); //图片质量 100
    $contents = ob_get_clean();

    //header("Content-Type: image/jpeg");

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . $finishFileName);
    header('Content-Transfer-Encoding: binary');
    echo $contents;

    exit();
}


/**
 * 生成淘宝商品弹窗图
 * author        :lianghuiju@chuchujie.com
 * function_name : createTbToastImg
 * datetime      : 2019/6/21
 * description   :
 */
function createTbToastImg() {
    $productOnePrice = $_REQUEST['product_one_price'];
    $productOneTitle = $_REQUEST['product_one_title'];

    $productImgOne = isset($_FILES['product_img_one']) ? $_FILES['product_img_one'] : array();

    if (empty($productImgOne)) {
        echo "<script>alert('图片上传错误');window.history.back(-1);</script>";
        die;
    }
    if (($productImgOne['size'] / 1024) > 200) {
        echo "<script>alert('商品图片需小于200KB');window.history.back(-1);</script>";
        die;
    }
    if (empty($productOnePrice) || !is_numeric($productOnePrice) || empty($productOneTitle)) {
        echo "<script>alert('商品一信息错误');window.history.back(-1);</script>";
        die;
    }

    $productOnePrice = trim($productOnePrice);
    $productOneTitle = trim($productOneTitle);

    //设置字体路径
    putenv('GDFONTPATH=' . realpath('.'));
    $font = ROOT_PATH.'font/PingFang.ttc';

    //打开底图
    $baseImgFilePath = ROOT_PATH.'images/mp_card_scfx.jpg';

    $copyImgSize = 600;
    $priceFontSize = 58;
    $imgX = 74;
    $imgY = 50;
    $priceX = 436;
    $priceY = 845;

    $im = @imagecreatefromjpeg($baseImgFilePath);
    if (!$im) {
        echo "<script>alert('获取模板图错误'); window.history.back(-1);</script>";
        die;
    }
    $black = imagecolorallocate($im, 0, 0, 0);
    $white = imagecolorallocate($im, 255, 255, 255);
    $ccjRed = imagecolorallocate($im, 227, 51, 93);
    $red = imagecolorallocate($im, 255, 0, 0);

    //处理商品图
    $productOneImage = file_get_contents($productImgOne['tmp_name']);
    $goods_im = imagecreatetruecolor($copyImgSize, $copyImgSize);
    imagefill($goods_im, 0, 0, $white);
    if ($productOneImage) {
        $goods_tmp_im = imagecreatefromstring($productOneImage);
        if (is_resource($goods_tmp_im)) {
            imagecolorallocate($goods_im, 255, 255, 255);
            $g_src_w = imagesx($goods_tmp_im);
            $g_src_h = imagesy($goods_tmp_im);
            imagecopyresized($goods_im, $goods_tmp_im, 0, 0, 0, 0, $copyImgSize, $copyImgSize, $g_src_w, $g_src_h);
        } else {
            echo "<script>alert('构造商品图错误');window.history.back(-1);</script>";
            die;
        }
    } else {
        echo "<script>alert('创建商品图错误');window.history.back(-1);</script>";
        die;
    }

    imagecopy($im, $goods_im, $imgX, $imgY, 0, 0, $copyImgSize, $copyImgSize); //商品图

    //处理商品名
    $name1Lines = $productOneTitle;
    $name_font_size = 38;
    $productTitleBox = imagettfbbox($name_font_size, 0, $font, $name1Lines);
    $productTitleWidth = $productTitleBox[4] - $productTitleBox[0];
    $name1_x = 375 - round($productTitleWidth / 2);
    $name1_y = 730;
    imagettftext($im, $name_font_size, 0, $name1_x, $name1_y, $black, $font, $name1Lines);
    imagettftext($im, $name_font_size, 0, $name1_x, $name1_y, $black, $font, $name1Lines);

    //处理价格
    imagettftext($im, $priceFontSize, 0, $priceX, $priceY, $ccjRed, $font, $productOnePrice);
    imagettftext($im, $priceFontSize, 0, $priceX, $priceY, $ccjRed, $font, $productOnePrice);

    ob_start();
    imagejpeg($im);
    $contents = ob_get_clean();

    //header("Content-Type: image/jpeg");

    $finishFileName = $productOneTitle . '.jpg';
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . $finishFileName);
    header('Content-Transfer-Encoding: binary');

    echo $contents;
    exit();
}

/**
 * 生成唯一id
 * @return string
 * author        :lianghuiju@chuchujie.com
 * function_name : makeUniqId
 * datetime      : 2019/6/21
 * description   :
 */
function makeUniqId() {
    $chars = array(
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
        'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
        'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3',
        '4', '5', '6', '7', '8', '9'
    );

    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i = 0; $i < 12; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }

    return date('YmdHis') . $output;
}

/**
 * Curl Post请求
 * @param $url
 * @param null $data
 * @param array $headers
 * @param bool $buildQuery
 * @param bool $toArray
 * @param null $cookie
 * @return mixed|string
 * author        :lianghuiju@chuchujie.com
 * function_name : httpPost
 * datetime      : 2019/6/21
 * description   :
 */
function httpPost($url, $data = null, $headers = array(), $buildQuery = false, $toArray = true, $cookie = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);

    if ($buildQuery) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    //设置header头参数
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    if (!empty($cookie)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    $rlt = curl_exec($ch);
    if ($toArray) {
        $rlt = json_decode($rlt, true);
    }

    if (curl_errno($ch)) {
        $msg = curl_error($ch);
        $curl_errno = curl_errno($ch);
        log_message('error', "Curl Error {$curl_errno}:{$msg} method[POST] url[$url]");
        return $msg;
    }

    curl_close($ch);

    return $rlt;
}

/**
 * 通用HttpGet请求方法
 * @param $url
 * @param array $headers
 * @param bool $toArray
 * @return mixed
 * author        :lianghuiju@chuchujie.com
 * function_name : httpGet
 * datetime      : 2019/6/21
 * description   :
 */
function httpGet($url, $headers = array(), $toArray = true) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2000);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);

    //设置header头参数
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $curlRlt = curl_exec($ch);
    if ($toArray) {
        $curlRlt = json_decode($curlRlt, true);
    }

    $curl_errno = curl_errno($ch);
    if ($curl_errno) {
        $curl_error = curl_error($ch);
        $errmsg = "Curl Error {$curl_errno}:{$curl_error} method[GET] url[$url]";
        log_message('ERROR', $errmsg);
    }

    curl_close($ch);

    return $curlRlt;
}

function renderOutput($data = array(), $errno = 0, $msg = '', $exit = false) {
    $result = json_encode(compact('errno', 'msg', 'data'));
    echo $result;
    if ($exit == true || $errno == 0) {
        die;
    }
}

图片.png

页面展示.rar

images.rar

font字体需要自己下载,太多选择,符合自己的字体就好,我用的ADOBEHEITISTD-REGULAR.OTF和PingFang.ttc








神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。