先來看看效果圖:
背景圖(生成前):
生成後:
軟件使用插件Intervention/image,這個是官網
1.首先,給LARAVEL中安裝該插件
composer require intervention/image
2.修改config/app.php文件,就是給文件裏面的providers那裏和aliases那裏分別加入這兩句
在$providers
中加入這句
Intervention\Image\ImageServiceProvider::class
在 $aliases
中加入這句.
'Image' => Intervention\Image\Facades\Image::class
3.在要使用的控制器頂部,加入
use Image;
4.以下爲控制器中的方法,給圖片插入文字並顯示
public function createCertification(){
// create Image from file
$img = Image::make(public_path().'\img\hjzs.png'); //背景圖的地址
// use callback to define details
$img->text('大美女', 150, 260, function($font) {
$font->file(public_path().'\font\hwzs.ttf'); //字體的地址,地址錯誤會報GD庫的錯
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});
$img->text('二十二', 290, 320, function($font) {
$font->file(public_path().'\font\hwzs.ttf');
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});
$img->text('春天在哪裏啊春天在哪裏', 500, 375, function($font) {
$font->file(public_path().'\font\hwzs.ttf');
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});
$img->text('省', 530, 428, function($font) {
$font->file(public_path().'\font\hwzs.ttf');
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});
$img->text('壹', 660, 428, function($font) {
$font->file(public_path().'\font\hwzs.ttf');
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});
return $img->response("png");
}
這樣就可以了,注意結尾是response()這個是輸出到瀏覽器,這樣會節約我們的空間,如果想保存,可以用save()方法哦
這個插件還有很多有用的方法,具體不多贅述了,大家可以去官網進行查詢
可能有同學說,那有人的作文題目字多,有的人字少,那怎麼讓題目居中呢?
這裏我研究了一下:位置480頂到左邊能放14字,位置700在正中2字,算下來是20位置一個字,我們讓初始位置爲700,超過兩個字每多一個字就往左移動20個像素,代碼如下
//位置480頂到左邊能放14字,位置700在正中2字,20位置一個字
$x = 700;
$title = "春天到底在哪裏啊";
$font_len = mb_strlen($title)>14?14:mb_strlen($title);
$x = 700-20*($font_len-2);
$img->text($title, $x, 375, function($font) {
$font->file(public_path().'\font\hwzs.ttf');
$font->size(35);
// $font->color('#fdf6e3');
// $font->align('center');
// $font->valign('top');
// $font->angle(45);
});