php 實現將文本、圖片寫到同一張圖上面以及文本的自動換行


以laravel框架為例:

 

首先controller中引用ImageManager;

use Intervention\Image\ImageManager;

 

下面就是關鍵處理,

  

$date = date('Y年m月d日 H:i', $data['time']);
$title = $data['title'];
$content = $data['content'];
$id = $data['id'];
//原圖地址-畫布
$dir = env('UPLOAD_FILE_ORIGINAL_DIR', 'Thumb') . '/' .env('UPLOAD_FILE_TEMP_DIR', 'Temp');
$baseImage = 'news_base.png';
$baseFile = public_path($dir.'/'.$baseImage);

//生成圖片地址
$shareImage = $dir.'/' .$id. '.png';
$shareFile = public_path($shareImage);

//插入畫布的圖片
$img = public_path($img);

//圖片處理方法類
$manager = new ImageManager();
$fontTtf = public_path('fonts/DroidSansFallback.ttf');

$image = $manager->make($baseFile)
//insert text
->text($date, 219, 384, function ($font) {
$font->file($fontTtf);
$font->size(30);
$font->color('#FCA969');
$font->align('left');
});
//這個部分尤為重要:當文本中出現數字時,根據字符串長度換行,行末會出現多余空格,所以決定用下面的這種根據寬度實現自動換行
function autowrap($fontsize, $angle, $fontface, $string, $width) {
// 參數分別是 字體大小, 角度, 字體名稱, 字符串, 預設寬度
$content = "";
// 將字符串拆分成一個個單字 保存到數組 letter 中
preg_match_all("/./u", $string, $arr);
$letter = $arr[0];
foreach($letter as $l) {
$teststr = $content.$l;
$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
if (($testbox[2] > $width) && ($content !== "")) {
$content .= PHP_EOL;
}
$content .= $l;
}
return $content;
}

$i=577; //top
$box = autowrap(30, 0, $fontTtf, $title, $i);

$image = $image->text($box, 113, $i, function ($font) {
$font->file(public_path('fonts/DroidSansFallback.ttf'));
$font->size(34);
$font->color('#222222');
$font->align('top');
});

//insert content
$i=715; //top
$box = autowrap(30, 0, $fontTtf, $content, $i);
$image = $image->text($box, 117, $i, function ($font) {
$font->file(public_path('fonts/DroidSansFallback.ttf'));
$font->size(30);
$font->color('#666666');
$font->align('top');
});

//insert img
$image = $image->insert($img, 'bottom-left', 115, 450);

$image->save($shareFile);

好了!到這里就實現了,如果你中間也遇到自動換行效果不是很好的時候,就好好看看標紅的部分找找原因吧~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM