/*
* 检查base64编码的图片格式
*/
function check_base64_img_string($img) {
if (!isset($img)) {
$msg = array(
'code' => false,
'message' => '参数错误'
);
return $msg;
}
$img = base64_decode($img);
$img_size = getimagesizefromstring($img);
if ($img_size == false) {
$msg = array(
'code' => false,
'message' => '非图片文件'
);
return $msg;
}
$img_size[2] = intval($img_size[2]);
if ($img_size[2] < 1 || $img_size[2] > 3) {//1 = GIF,2 = JPG,3 = PNG
$msg = array(
'code' => false,
'message' => '图片格式错误'
);
return $msg;
}
$ext = '';
switch ($img_size[2]) {
case 1:
$ext = '.gif';
break;
case 2:
$ext = '.jpg';
break;
case 3:
$ext = '.png';
break;
}
return array('code' => true, 'ext' => $ext);
}
//将 base64 后的图片内容存储为文件
function save_base64_img_file($img_string = '', $type = '') {
$type_array = array(
'business_license', //营业执照
'identity_card', //身份证
'bocc', //中银附件
'driving_license', //行驶证
'opening_accounts', //开户许可
'authorization', //授权委托书
'price_single', //核价单
'attached', //挂靠协议
'policy', //保险单
'invoice', //发票
);
if (!$img_string || !in_array($type, $type_array)) {
return array(
'code' => false,
'message' => '文件分类不存在'
);
}
$request = check_base64_img_string($img_string);
if (!$request['code']) {//没通过检查
return $request;
}
$upload_path = str_replace('\\', '/', ROOT_PATH);
$path = 'public/uploads/' . $type . '/' . date('Ymd') . '/';
$upload_path = $upload_path . $path;
if (!is_dir($upload_path)) {
mkdir($upload_path, 0755, true);
}
$file_name = get_rand_str(15, 1) . $request['ext'];
$file_path = $upload_path . '/' . $file_name;
$state = file_put_contents($file_path, base64_decode($img_string));
if ($state === false) {
return array(
'code' => false,
'message' => '图片保存失败'
);
}
return array(
'code' => true,
'path' => '/' . $path . $file_name,
);
}
TP5-上传图片方法
猜你喜欢
转载自blog.csdn.net/wake_me_up123/article/details/81017855
今日推荐
周排行