天天看点

图片添加水印图片添加水印

图片添加水印

对图像进行处理,我们选择使用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 水印上(下)边距