/**
* 接收图片信息并进行转码
* @param $file
* @return bool|string
*/
public function uploadImg($file)
{
$imgUrl = base64_encode(file_get_contents($file));
if($imgUrl) {
$url = $this -> base64_img("data:image/png;base64,".$imgUrl);
return $url;
}
}
/**
* 接收文件流并生成图片存储
* @param $base64_image_content
* @return bool|string
*/
public function base64_img($base)
{
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base, $result)){
$type = $result[2];
$path = "upload/";
$new_file = date('Ymd',time())."/";
if(!file_exists($path.$new_file)){
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($path.$new_file, 0700,true);
}
$new_file = $new_file.time().rand(10000,99999).".{$type}";
if (file_put_contents($path.$new_file, base64_decode(str_replace($result[1], '', $base)))){
// return "http://".$_SERVER['SERVER_NAME']."/upload/".$new_file;
return "/upload/".$new_file;
}else{
return false;
}
}else{
return false;
}
}
压缩图片
/**
* 按照指定的尺寸压缩图片
* @param $source_path 原图路径
* @param $imgWidth 目标宽度
* @param $imgHeight 目标高度
* @return bool|string
*/
function resize_image($source_path,$imgWidth,$imgHeight)
{
$source_info = getimagesize($source_path);
$source_mime = $source_info['mime'];
switch ($source_mime)
{
case 'image/gif':
$source_image = imagecreatefromgif($source_path);
break;
case 'image/jpeg':
$source_image = imagecreatefromjpeg($source_path);
break;
case 'image/png':
$source_image = imagecreatefrompng($source_path);
break;
default:
return false;
break;
}
$target_image = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $imgWidth, $imgHeight, $source_info[0], $source_info[1]);
//保存图片到本地
$dir = 'upload/'. date("Ymd") . '/';
if (!is_dir($dir)) {
mkdir($dir, 0777);
}
$fileName = $dir.date("YmdHis").uniqid().'.jpg';
if(!imagejpeg($target_image,'./'.$fileName)){
$fileName = '';
}
imagedestroy($target_image);
return $fileName;
}