Home  >  Article  >  Operation and Maintenance  >  How nginx adds watermark to images through PHP proxy

How nginx adds watermark to images through PHP proxy

PHPz
PHPzforward
2023-05-29 08:37:111651browse

How nginx adds watermark to images through PHP proxy

nginx configuration proxy

location ~ /image/.*\.(gif|jpg|jpeg|png)$ {
    proxy_pass http://127.0.0.1:8888/test/watermark?url=$request_uri;
}

/img/ matches the directory prefix to be proxied, $request_uri parameter is accessed Image path.

php watermark class

/** 水印类
 * Class Watermark
 * @package app\test
 */
class Watermark
{
    /** 合成图片水印
     * @param string $dstImage 原图片
     * @param string $waterImg 水印图
     */
    public static function imageMarking($dstImage, $waterImg){
        //获取图片信息
        $dstInfo = getimagesize($dstImage);
        $waterInfo = getimagesize($waterImg);
        //创建图像
        $dstImgObj = self::imageCreateFrom($dstImage, $dstInfo[2]);
        $waterImgObj = self::imageCreateFrom($waterImg, $waterInfo[2]);
        //合成水印
        imagecopyresized($dstImgObj,$waterImgObj,0, 0,0,0,$dstInfo[0], $dstInfo[1],$waterInfo[0],$waterInfo[1]);
        //输出图片
        self::imageOut($dstImgObj,$waterInfo[2]);
        //销毁资源对象
        imagedestroy($dstImgObj);
        imagedestroy($waterImgObj);
    }
    /** 生成图片对象
     * @param string $imgFile 图片路径
     * @param string $type 图片类型
     * @return false|\GdImage|resource
     */
    private static function imageCreateFrom($imgFile, $type) {
        switch ($type) {
            case IMAGETYPE_GIF:
                return imagecreatefromgif($imgFile);
            case IMAGETYPE_JPEG:
                return imagecreatefromjpeg($imgFile);
            case IMAGETYPE_PNG:
                return imagecreatefrompng($imgFile);
            default :   //其他格式
        }
    }
    /** 输出图片
     * @param string $imageObj
     * @param string $type
     */
    private static function imageOut($imageObj,$type){
        switch ($type) {
            case 1:
                header("Content-Type: image/gif");
                imagegif($imageObj);
                break;
            case 2:
                header("Content-Type: image/jpeg");
                imagejpeg($imageObj);
                break;
            case 3:
                header("Content-Type: image/png");
                imagepng($imageObj);
                break;
            default: //其他格式
        }
    }
}

Call example

public function watermark(){
    //图片路径前缀
    $image = '/data/img/' . input('url');
    self::imageMarking($image,'watermark.png');
    exit;
}

The above is the detailed content of How nginx adds watermark to images through PHP proxy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete