上传/压缩图片

/**
 * 接收图片信息并进行转码
 * @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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值