Web 开发PHP经验分享

PHP 批量给图片添加水印(多图,压缩水印大小)

2017-05-25  本文已影响77人  PEIZIJUN

这个例子是给图片批量添加图片水印, 文字水印道理相同,改一下就好了:
方法里传的参数是图片路径,传逗号字符串就好。
因为项目要求水印的比例要保持一直一样,所以想了个办法:
压缩水印或放大水印,生成一张新的水印图片,把水印添到图片上,再把生成的水印图片删掉。

function image_water($pathdata){
    $path = explode(',', $pathdata);
    $src_path = 'Public/Console/images/sss.png';   //这个是水印图片路径
    array_pop($path);    //因为我传的逗号字符串最后还有一个逗号,所以需要去掉最后一个空数组
    foreach($path as $p){
        $p = substr($p,1);   //处理一下路径,看项目具体情况操作
        list($width,$height,$type)=getimagesize($p);    // 获取图片信息
        list($src_w,$src_h)=getimagesize($src_path); 
        $bi = $src_w / $src_h; 
        $new_width = $width*0.3;        //压缩水印是图片的   0.3 
        $new_height = $new_width / $bi;

        $image_wp=imagecreatetruecolor($new_width, $new_height); 
        $c=imagecolorallocatealpha($image_wp , 0 , 0 , 0 ,127);//拾取一个完全透明的颜色
        imagealphablending($image_wp ,false);//关闭混合模式,以便透明颜色能覆盖原画布
        imagefill($image_wp , 0 , 0, $c);//填充
        imagesavealpha($image_wp ,true);//设置保存PNG时保留透明通道信息
        $image = imagecreatefrompng($src_path); 
        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $src_w, $src_h); 
        header('content-Type:image/png'); 
        imagepng($image_wp,'Public/Console/images/sss_s.png');
        $s_path = 'Public/Console/images/sss_s.png';
        $dst = imagecreatefromstring(file_get_contents($p));
        $src = imagecreatefromstring(file_get_contents($s_path));
        list($s_width,$h_height)=getimagesize($s_path); 
        $newwidth = $width - $s_width;
        $newheight = $height - $h_height;
        imagecopy($dst, $src, $newwidth, $newheight, 0, 0, $new_width, $new_height);
        switch($type){
              case 1://GIF
                header("content-type:image/gif");
                imagegif($dst,$p);
                unlink($s_path);
                break;
              case 2://JPG
                header("content-type:image/jpeg");
                imagejpeg($dst,$p);
                unlink($s_path);
                break;
              case 3://PNG
                header("content-type:image/png");
                imagepng($dst,$p);
                unlink($s_path);
                break;
              /*imagepng--以PNG格式将图像输出到浏览器或文件
              imagepng()将GD图像流(image)以png格式输出到标注输出(通常为浏览器),或者如果用filename给出了文件名则将其输出到文件*/
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读