HTML5调用手机摄像头拍照并本地压缩照片上传,支持微信公众号网页,H5app页面等。

javascript / 2019年12月27日 14时57分 / 10925人浏览
HTML5调用手机摄像头拍照并本地压缩照片上传,支持微信公众号网页,H5app页面等。 html页面
 

css
 .pic{
                display: none;
                width: 50%;
            }
            .file {
                position: relative;
                display: inline-block;
                background: #D0EEFF;
                border: 1px solid #99D3F5;
                border-radius: 4px;
                padding: 4px 12px;
                overflow: hidden;
                color: #1E88C7;
                text-decoration: none;
                text-indent: 0;
                line-height: 20px;
            }
            .file input {
                position: absolute;
                font-size: 100px;
                right: 0;
                top: 0;
                opacity: 0;
            }
            .file:hover {
                background: #AADFFD;
                border-color: #78C3F3;
                color: #004974;
                text-decoration: none;
            }
js
     
   
php后台
 if ($this->request->isAjax()) {
        $param = input('post.');
        $pic = isset($param['pic']) ? $param['pic'] : '';
        if($pic != ''){
           $pic_url = up_base64img($pic);
           return ['code' => 1, 'url' => $pic_url, 'msg' => '上传成功'];
        }    
}
function up_base64img($img_data) {
    $img_data = trim($img_data);
    if (!empty($img_data)) {
        
        $reg = '/data:image\/(\w+?);base64,(.+)$/si';
        preg_match($reg, $img_data, $match_result);
        $file_name = date("his") . '_' . rand(10000, 99999) . '.' . $match_result[1];
        //定义图片储存文件目录
        $dir = DIR_IMAGE . 'images/house/' . date('ym');
        $path = 'house/' . date('ym') . '/' . $file_name;
        
        if (!is_dir($dir)) {
            //如果不存在就创建该目录
            mkdir($dir, 0777, true);
        }
        $pic_path = $dir . '/' . $file_name;
        $num = file_put_contents($pic_path, base64_decode($match_result[2]));
        if (!empty($num)) {
            //上传成功之后,再进行缩放操作
            //$image = \think\Image::open($logo_path);
            // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
            //$image->thumb(102, 36)->save($logo_path);
            return $path;
        } else {
            return '';
        }
    } else {
        return '';
    }
}