PHP---将两张身份证照片合并为一张

最近要开发一个功能,前端上传身份证照片的正反面,后台需要将该这两张身份证照片进行合并。

参考:

https://blog.csdn.net/weixin_34375251/article/details/93723189

具体代码示例:

public function mergeImage($one = '',$two = '',$name = 'idcard')
{
    $rootPath = input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME');
    $oneImgPath = $rootPath . $one;
    $twoImgPath = $rootPath . $two;
    $oneImgObj = getimagesize($oneImgPath);
    $twoImgObj = getimagesize($twoImgPath);

    $oneImgWidth = $oneImgObj[0];
    $oneImgHeight = $oneImgObj[1];
    $twoImgWidth = $twoImgObj[0];
    $twoImgHeight = $twoImgObj[1];

    $canvasWidth = $oneImgWidth > $twoImgWidth ? $oneImgWidth : $twoImgWidth;
    $canvasHeight = $oneImgHeight + $twoImgHeight;

    $imgOne = imagecreatefromjpeg($oneImgPath);
    $imgTwo = imagecreatefromjpeg($twoImgPath);

    $canvas = imagecreatetruecolor($canvasWidth,$canvasHeight);
    imagefill($canvas,0,0,imagecolorallocate($canvas,255,255,255));

    $imgOneX = ($canvasWidth - $oneImgWidth) / 2;
    $imgTwoX = ($canvasWidth - $twoImgWidth) / 2;

    imagecopyresampled($canvas,$imgOne,intval($imgOneX),0,0,0,$oneImgWidth,$oneImgHeight, $oneImgWidth,$oneImgHeight);
    imagecopyresampled($canvas,$imgTwo,intval($imgTwoX),$oneImgHeight,0,0,$twoImgWidth,$twoImgHeight, $twoImgWidth,$twoImgHeight);

    $desPath = 'storage/upload/idcard/'.$name.'.jpg'; // 文件名字
    file_exists($desPath)&&unlink($desPath);
    imagejpeg($canvas,$desPath,100);
    return $desPath;
}

具体使用,仅需要掉用该方法的时候,传入需要合并的照片即可。

// 正面 反面 命名
$result = $this->mergeImage($idcardFront,$idcardBack,'idcard-45124545');

打完收工!

posted @ 2022-05-12 14:35  帅到要去报警  阅读(653)  评论(0编辑  收藏  举报