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('制作失败');
}
}
}
上面用到我封装的服务里面的代码,继续贴代码
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);
}