圖檔添加水印
對圖像進行處理,我們選擇使用intervention/image擴充包,如果項目中沒有安裝,可以使用composer進行安裝
composer require intervention/image
安裝成功,隻需要在項目檔案開頭引入該擴充封包件即可
use Intervention\Image\ImageManager
對圖檔添加文字水印
//擷取可用字型清單,字型庫放在根目錄下fonts檔案夾裡
$fonts = array_values(array_diff(scandir('fonts'), ['..', '.']));
//随機選取一種字型
//$fontFile = $fonts[rand(0, strlen(count($fonts)))];
$fontFile = $fonts[$fontType];
$img = Image::make($final_url)->text($text, $x, $y, function ($font) use ($fontFile) {
//設定字型類型(可引入字型庫)
$font->file(realpath("fonts/{$fontFile}"));
//設定字型大小
$font->size(45);
//設定字型顔色
//$font->color(array(102, 102, 102, 0.3));
$font->color("#FBDC6C");
//設定字型内邊距
$font->align('left');
$font->valign('top');
//傾斜角度
//$font->angle(45);
})//->resize(200, 200)
;
//圖檔輸出
echo $img->response('jpg');
參數說明 | 注釋 |
---|---|
final_url | 要添加水印的圖檔 |
text | 水印文字内容 |
x | 水印左(右)邊距 |
y | 水印上(下)邊距 |
對圖檔添加圖檔水印
//處理原圖檔
$img = Image::make($image_url)->resize($imageWidth, $imageHeight, function ($constraint) {
$constraint->aspectRatio();
});
//處理水印圖檔
if ($type == 'full'){
//水印圖檔全屏(與原圖大小一樣)
$watermark = Image::make($water_image)
->resize($imageWidth, $imageHeight);
$img->insert($watermark, 'bottom');
}else{
$watermark = Image::make($water_image)
->resize( //設定水印圖檔的大小
$waterImageWidth / 5, $waterImageHeight / 5,
function ($constraint) {
$constraint->aspectRatio();
}
);
//将水印圖檔添加到原圖上
$img->insert($watermark, $type, $x, $y);
}
echo $img->response('jpg');
參數說明 | 注釋 |
---|---|
image_url | 原圖檔url |
watermark | 水印圖檔url |
type | 邊距類型,可取值:full,top-left,top-right,bottom-left,bottom-right |
x | 水印左(右)邊距 |
y | 水印上(下)邊距 |