要上傳到OSS的話需要先安裝OSS
composer require aliyuncs/oss-sdk-php
不囉嗦,直接貼代碼(自己公司項目已上線保證可用)
(注:多張圖片就再代碼的$config 裏面的image數組裏多寫一套配置,多種文字要合成的話也是多寫一套配置, 在製作時候是通過循環處理沒套配置的!)
class PostersController extends BaseController
{
use User;
//生成海報
public function getPoster(Request $request){
$params = $request->all();
//海報參數驗證
$validatorOrders = Validator::make($params,Posters::$validate_rule,Posters::$message,Posters::$attributeNames);
if($validatorOrders->fails()) {
$errorMsg = $validatorOrders->messages()->first();
return $this->error($errorMsg);
}
$params['title'] = str_replace(' ', '',removeEmoji($params['title']));
$params['vice_title'] = removeEmoji(str_replace(' ', '',removeEmoji($params['vice_title'])));
if(mb_strlen($params['title'],'UTF8')>9){
return $this->error('標題不能超過9個字');
}
if(mb_strlen($params['vice_title'],'UTF8')>60){
return $this->error('副標題不能超過60個字');
}
//獲取海報信息
$config = array(
'image'=>array(
array(
'url'=>$params['code_image'], //二維碼地址
'is_yuan'=>false, //true圖片圓形處理
'stream'=>0,
'left'=>-1, //小於0爲小平居中
'top'=>0, //等於0時上下居中
'right'=>0,
'width'=>200, //圖像寬
'height'=>200, //圖像高
'opacity'=>100 //透明度
),
array(
'url'=>$params['logo_image'], //頭像地址
'is_yuan'=>true, //true圖片圓形處理
'stream'=>0,
'left'=>90, //小於0爲小平居中
'top'=>43,
'right'=>0,
'width'=>230, //圖像寬
'height'=>71, //圖像高
'opacity'=>100 //透明度
),
),
'text'=>array(
[
'text'=>$params['title'], //文字內容
'left'=>-1, //小於0爲水平居中
'top'=>254,
'width'=>726,
'fontSize'=>56, //字號
'fontColor'=>'245,218,152', //字體顏色
'angle'=>0,
'hang_size'=>46, //行高
'fontPath'=>public_path('static/font/simkai.ttf'), //字體文件
],
[
'text'=>$params['vice_title'], //文字內容
'left'=>132, //小於0爲水平居中
'top'=>379,
'width'=>583,
'fontSize'=>26, //字號
'fontColor'=>'245,218,152', //字體顏色
'angle'=>0,
'hang_size'=>20, //行高
'fontPath'=>public_path('static/font/simkai.ttf'), //字體文件
],
[
'text'=>$params['name'], //文字內容
'left'=>-1, //小於0爲水平居中
'top'=>865,
'width'=>242,
'fontSize'=>28, //字號
'fontColor'=>'245,218,152', //字體顏色
'angle'=>0,
'hang_size'=>27, //行高
'fontPath'=>public_path('static/font/simkai.ttf'), //字體文件
],
[
'text'=>$params['tel'], //文字內容
'left'=>-1, //小於0爲水平居中
'top'=>929,
'width'=>242,
'fontSize'=>24, //字號
'fontColor'=>'245,218,152', //字體顏色
'angle'=>0,
'hang_size'=>19, //行高
'fontPath'=>public_path('static/font/simkai.ttf'), //字體文件
],
[
'text'=>$params['address'], //文字內容
'left'=>-1, //小於0爲水平居中
'top'=>973,
'width'=>242,
'fontSize'=>24, //字號
'fontColor'=>'245,218,152', //字體顏色
'angle'=>0,
'hang_size'=>29, //行高
'fontPath'=>public_path('static/font/simkai.ttf'), //字體文件
],
),
'background'=>'https://qunxianghui-mall-upload.oss-cn-hangzhou.aliyuncs.com/upload/image/20190410/0311f58b024472485f3d7c24e0541926.png', //背景圖
);
$filename = public_path().'/liwei'.time().'.jpg';
//$filename爲空是直接瀏覽器顯示圖片
// $poster_img = PoserService::createPoster($config);
$poster_img = PoserService::createPoster($config,$filename);
if($poster_img){
$params['image'] = $poster_img;
$params['user_id'] = $this->user_id;
$params['store_id'] = $this->store_id;
$params['created_at'] = time();
$params['updated_at'] = time();
$res = Posters::create($params);
if($res){
return $this->success('製作成功',$params);
}else{
return $this->success('製作失敗');
}
}else{
return $this->success('製作失敗');
}
}
}
上面用到我封裝的服務裏面的代碼,繼續貼代碼
<?php
/**
* Created by PhpStorm.
* User: liwei
* Date: 2019/4/9
* Time: 17:17
*/
namespace App\Services;
use OSS\OssClient;
use OSS\Core\OssException;
use DB;
use Exception;
class Poster
{
/**
* 生成宣傳海報
* @param array /包括圖片和文字
* @param string $filename 生成海報文件名,不傳此參數則不生成文件,直接輸出圖片
* @return [type] [description]
*/
public static function createPoster($config = array() , $filename = ""){
//如果要看報什麼錯,可以先註釋調這個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,
'width'=>0,
'fontSize' => 32, //字號
'fontColor' => '255,255,255', //字體顏色
'angle' => 0,
'hang_size'=>10, //行高
);
$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);
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);
//如果是透明的gif或png做透明處理
$ext = pathinfo($val['url']);
if (array_key_exists('extension',$ext)) {
if ($ext['extension'] == 'gif' || $ext['extension'] == 'png') {
imageColorTransparent($canvas, $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'];
//如果left小於-1我這做成了計算讓其水平居中
if ($val['left'] < 0) {
$val['left'] = ceil($backgroundWidth - $val['width']) / 2;
}
// $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
$val['top'] = $val['top'] ==0 ? ceil($backgroundHeight- $val['height'])/2 : $val['top'];
//放置圖像
imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左,上,右,下,寬度,高度,透明度
}
}
//處理文字
if (!empty($config['text'])) {
$text_image ='';
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'];
//如果left小於-1我這做成了計算讓其水平居中
if ($val['left'] < 0) {
$fontBox = imagettfbbox($val['fontSize'], 0, $val['fontPath'], $val['text']); //文字水平居中實質
$val['left'] = ceil(($backgroundWidth - $fontBox[2]) / 2); //計算文字的水平位置
}
$val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
$pos=[
"color" => [$R, $G, $B],
'top'=> $val['top'],
'angle' => 0,
'fontSize'=> $val['fontSize'],
'str_width'=> $val['width'],
'back_width'=> $backgroundInfo[0],
'left'=> $val['left'],
'hangSize'=> $val['hang_size'],
'fontPath'=> $val['fontPath']
];
Poster::draw_txt_to($imageRes,$pos,$val['text'],true); // 自動換行處理
// imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
}
}
//生成圖片
if (!empty($filename)) {
$res = imagejpeg($imageRes, $filename, 90); //保存到本地
if (!$res){
return false;
}
$ossFileName = 'upload/image/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) .'.jpg';
try {
$config = config('app.aliyun_oss');
//實例化對象 將配置傳入
$ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
//這裏是有sha1加密 生成文件名 之後連接上後綴
$result = $ossClient->uploadFile($config['Bucket'], $ossFileName, $filename);
$arr = [
'oss_url' => $result['info']['url'], //上傳資源地址
'relative_path' => $ossFileName //數據庫保存名稱(相對路徑)
];
} catch (OssException $e) {
return $e->getMessage();
}finally {
imagedestroy($imageRes);
unlink($filename);
}
return $arr['oss_url'];
} else {
header("Content-type:image/png");
imagejpeg($imageRes); //在瀏覽器上顯示
imagedestroy($imageRes);
}
}
public static function draw_txt_to($card, $pos, $str)
{
$str_top = $pos["top"];
$angle = $pos["angle"];
$fontsize = $pos["fontSize"];
$str_width = $pos['str_width'];
$back_width = $pos['back_width'];
$margin_left = $pos["left"];
$hang_size = $pos["hangSize"];
$temp_string ='';
$font_file = $pos["fontPath"]; //字體
$tp = 0;
$font_color = imagecolorallocate($card, $pos["color"][0], $pos["color"][1], $pos["color"][2]);
// 參數分別是 字體大小, 角度, 字體名稱, 字符串, 預設寬度
$content = "";
// 將字符串拆分成一個個單字 保存到數組 letter 中
preg_match_all("/./u", $str, $arr);
$letter = $arr[0];
foreach($letter as $l) {
$teststr = $content.$l;
$testbox = imagettfbbox($fontsize, $angle, $font_file, $teststr);
if (($testbox[2] > $str_width) && ($content !== "")) {
$content .= PHP_EOL;
}
$content .= $l;
}
$textbox = imagettfbbox($fontsize, $angle, $font_file,$content);
$txt_height = $textbox[0]-$textbox[7];
$text_width = $textbox[2]-$textbox[0];
$x = ($back_width - $text_width) / 2; //文字居中
$y = $str_top+$txt_height+14; // 加9爲調整行距
imagettftext($card, $fontsize, $angle, $x, $y, $font_color, $font_file, $content);
}
/**
* 文字自動換行算法
* @param $card 畫板
* @param $pos 數組,top距離畫板頂端的距離,fontsize文字的大小,width寬度,left距離左邊的距離,hang_size行高
* @param $str 要寫的字符串
* @param $iswrite 是否輸出,true, 花出文字,false只計算佔用的高度
* @return int 返回整個字符所佔用的高度
*/
public static function is_firstfuhao($str)
{
$fuhaos = array("\"", "“", "'", "<", "《",);
return in_array($str, $fuhaos);
}