PHP之微信头像加水印

需求描述

公众号小程序用户引流, 微信头像上面加 "武汉加油"水印图片, 用户通过微信分享的方式吸引用户关注公众号

代码

/**
 * 下载微信头像
 * @param $url 微信头像路径(授权登录获取的头像路径)
 */
public function downloadImageFromUrl($url) {  
    // 临时存放图片路径
    $path = base_path('public/pplgWechat/');
    // 因为不知道最后接受到的文件是什么格式,先建立一个临时文件,用于保存
    $tmpFile = tempnam(sys_get_temp_dir(), 'image');
    # 文件下载 BEGIN #
    // 打开临时文件,用于写入(w),b二进制文件
    $resource = fopen($tmpFile, 'wb');

    // 初始化curl
    $curl = curl_init($url);
    // 设置输出文件为刚打开的
    curl_setopt($curl, CURLOPT_FILE, $resource);
    // 不需要头文件
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 执行
    curl_exec($curl);
    // 关闭curl
    curl_close($curl);
    // 关闭文件
    fclose($resource);

    # 文件下载 END #
    // 获取文件类型
    if (function_exists('exif_imagetype')) {
        // 读取一个图像的第一个字节并检查其签名(这里需要打开mbstring及php_exif)
        $fileType = exif_imagetype($tmpFile);
    } else {
        // 获取文件大小,里面第二个参数是文件类型 (这里后缀可以直接通过getimagesize($url)来获取,但是很慢)
        $fileInfo = getimagesize($tmpFile);
        $fileType = $fileInfo[2];
    }

    // 根据文件类型获取后缀名
    $extension = image_type_to_extension($fileType);
    // 计算指定文件的 MD5 散列值,作为保存的文件名,重复下载同一个文件不会产生重复保存,相同的文件散列值相同
    $md5FileName = md5_file($tmpFile);
    // 最终保存的文件
    $returnFile = $path . $md5FileName . $extension;

    // 检查传过来的路径是否存在,不存在就创建
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }

    // 复制临时文件到最终保存的文件中
    copy($tmpFile, $returnFile);
    // 释放临时文件
    @unlink($tmpFile);
    // 返回保存的文件路径
    return $returnFile;
}

/**
 * 微信头像加水印
 * @param $url 微信头像路径(本地头像文件路径)
 */
public function mergeImage($url,$user_id)
{

    $water = str_replace('/','\\',base_path('public/pplgWechat/') . 'water.png');
    $im = imagecreatefromjpeg($url);
    $stamp= imagecreatefrompng($water);

    // 设置水印图像的外边距,并且获取水印图像的尺寸
    $marge_right = 0;
    $marge_bottom = 0;
    $sx = imagesx($stamp);
    $sy = imagesy($stamp);

    // 利用图像的宽度和水印的外边距计算位置,并且将水印复制到图像上
    imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

    $pic_name = 'head_'.$user_id.'.jpg';
    // 图片全路径
    $pic = base_path('public/pplgWechat/') . $pic_name;
    $this->url =  $pic;
    $this->head_name =  $pic_name;

    // 输出图像并释放内存
    // header('Content-type: image/png');
    imagepng($im,$pic);
    imagedestroy($im);

}

微信默认头像不是高清头像的解决办法

// 微信头像原始路径(小图)
// https://wx.qlogo.cn/mmopen/vi_32/RWib8FCKWu7d78sU05kCKAd2IWBf5d0m4DldCDu7fEqtGvibL2jG8uRFxvhiap54SjwCc7dxgC2ltNicb0c1PYVH6w/132
// 微信高清头像原始路径(大图)
// https://wx.qlogo.cn/mmopen/vi_32/RWib8FCKWu7d78sU05kCKAd2IWBf5d0m4DldCDu7fEqtGvibL2jG8uRFxvhiap54SjwCc7dxgC2ltNicb0c1PYVH6w/0
$high = str_ireplace('132','0 ',$headimgurl)

如有错误之处, 大家评论区交流, 谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值