1.注册阿里云
2.开通阿里云OSS服务
3.下载阿里云OSS-SDK,将下载下来的文件解压到extend目录
4.代码demo
//将图片裁剪成圆形
public static function roundedCorners($imgpath){
list($width,$height,$type) = getimagesize($imgpath);//获取上传图片大小
if ($width != $height) {//如果上传图片不是正方形,取最小宽度作为最终生成图的大小
if ($width > $height) {
$imsize = $height;
} else {
$imsize = $width;
}
}
$im = imagecreatetruecolor($imsize, $imsize);//这里创建第一个图像
$white = imagecolorallocate($im, 255, 255, 255);// 随便取两个颜色,这里取黑色和白色
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $white);//将图片填充为白色
imagefilledellipse($im, $imsize/2, $imsize/2, $imsize, $imsize, $black);//然后再图片中间画一个黑色的圆
imagecolortransparent($im, $black);//将黑色设为透明的,则现在四个角是白色的,然后中间是透明的
switch ($type) {
case '2':
$img = imagecreatefromjpeg($imgpath);//这里创建的是第二个图像
break;
default:
$img = imagecreatefrompng($imgpath);//这里创建的是第二个图像
break;
}
$final = imagecreatetruecolor($imsize, $imsize);//再创建一个图像,第三个图像
imagecopyresampled($final, $img, 0, 0, ($width-$imsize)/2, ($height-$imsize)/2, $imsize, $imsize, $imsize, $imsize);//先将第二个图像(图片)压在空白的图像上,根据最小宽度,居中裁剪,成为第四个图像
imagecopymerge($final, $im, 0, 0, 0, 0, $imsize, $imsize, 100);//再将第一个图像压在第四个图像上,由于中间是透明的,所以现在图像上中间是图片,四个角都是白色的,第五个图
imagecolortransparent($im, $white);//然后将白色设置为透明的,现在这个图四个角是透明的,然后中间是黑色的
imagecopymerge($im, $final, 0, 0, 0, 0, $imsize, $imsize, 100);//将第五个图压在最后的图像上,就可以得到最后的圆形的图了
return $im;//返回图片
}
//图片上传到OSS
<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\File;
require_once APP_PATH . '/../extend/aliyun-oss/autoload.php';
use OSS\Core\OssException;
use OSS\OssClient;
class Alioss
{
public static function uploadFile($file,$type) {
$mulu = 'headimg';
if($type){
$imgtype = $type;
$content = $file;
}else{
$content = file_get_contents($file);
$imginfo = getimagesize($file);
$imgtype = str_replace('image/', '', $imginfo['mime']);
}
// echo $imgtype;exit;
try {
$KeyId = config('alioss.KeyId');
$KeySecret = config('alioss.KeySecret');
$EndPoint = config('alioss.EndPoint');
$Bucket = config('alioss.Bucket');
//实例化
$ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
//sha1加密 生成文件名 连接后缀
$fileName = $mulu.'/'.sha1(date('YmdHis', time()) . uniqid()) . '.' . $imgtype;
$options = [];
//执行阿里云上传
$result = $ossClient->putObject($Bucket, $fileName, $content,$options);
//图片地址:$result['info']['url']
$arr = ['code'=>200,'msg'=>'上传成功','data'=>$result['info']['url']];
} catch (OssException $e) {
$arr = ['code'=>0,'msg'=>$e->getMessage(),'data'=>''];
}
var_dump($arr);
}
}
//调用
use app\api\controller\Alioss;
public function test() {
$url = 'https://upload-images.jianshu.io/upload_images/8396841-50c151628048a0cf.png';
$imginfo = getimagesize($url);
switch ($imginfo['2']) {
case 1:
$type = 'gif';
break;
case 2:
$type = 'jpg';
break;
case 3:
$type = 'png';
break;
case 6:
$type = 'bmp';
break;
}
$img = self::roundedCorners($url); // 裁剪成圆形资源
// header("content-type:image/jpeg");
imagejpeg($img);
imagedestroy($img);
$img = ob_get_contents();
ob_end_clean();
$res = Alioss::uploadFile($img,$type);
}