php上传文件到七牛云
use zgldh\QiniuStorage\QiniuStorage;
use \Illuminate\Http\UploadedFile;
public function uploadImage(UploadedFile $image, string $disk, string $key) {
/** @var $qiniu \zgldh\QiniuStorage\QiniuStorage */
$qiniu = QiniuStorage::disk($disk); // 'goods_qiniu'
$token = $qiniu->uploadToken();
$qiniu->withUploadToken($token);
$path = $image->path();
$qiniu->put($key, file_get_contents($path));
/** @var $url \zgldh\QiniuStorage\QiniuUrl */
$url = $qiniu->downloadUrl($key);
unlink($path);
return array(
"path" => $path,
"url" => $url
);
}
图片下载,裁剪
<?php
namespace CarV2\Utils;
class Image
{
public static function download(string $src, string $outPath, $contentType = "") {
if (empty($contentType)) {
$dotIndex = strrpos($src, ".");
$ext = substr($src, $dotIndex);
$contentType = self::getContentTypeByExt($ext);
}
$ch = curl_init();
$headers = [
'accept: q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-ranges: bytes',
];
curl_setopt_array($ch, [
CURLOPT_URL => $src,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => $headers,
]);
$stream = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
ob_start();
header('Content-Type: '.$contentType);
file_put_contents($outPath, $stream);
ob_clean();
flush();
return $info;
}
private static function getContentTypeByExt($ext) {
$ext = ltrim(".", $ext);
switch ($ext) {
case 'jpg':
case 'jpeg': $type = 'image/jpeg'; break;
case 'png': $type = 'image/png'; break;
case 'gif': $type = 'image/gif'; break;
default:
$type = 'application/octet-stream';
}
return $type;
}
/**
* 裁剪图片
* @param string $img_file 图片原始路径
* @param string $dst 保存路径
* @param int $cut_w 裁剪后的宽
* @param int $cut_h 裁剪后的高
* @param int $cut_x $cut_y 裁剪的起点坐标
* @return int
*/
public static function crop (string $img_file, string $dst, int $cut_w, int $cut_h,
int $cut_x=0, int $cut_y=0): int
{
if (!file_exists($img_file)) {
return 2; // '裁剪图片不存在!'
}
$info = getimagesize($img_file);
if (false == $info) {
return 1;
}
// list($src_w ,$src_h) = $info;
$src_fnc = str_replace('/', 'createfrom', $info['mime']);
$src_img = $src_fnc($img_file);
$dst_img = imagecreatetruecolor($cut_w, $cut_h);
$dst_x = 0;
$dst_y = 0;
// 缩放图片
// if( $cut_w > $src_w || $cut_h > $src_h ) {
// imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $cut_x, $cut_y, $cut_w, $cut_h, $src_w, $src_h);
// } else {//裁剪
imagecopy($dst_img, $src_img, $dst_x, $dst_y, $cut_x, $cut_y, $cut_w, $cut_h);
// }
imagejpeg($dst_img ,$dst);
imagedestroy($dst_img);
imagedestroy($src_img);
return 0;
}
}