markdown 不仅编辑文本,还要上传图片。laravel 服务端怎么搞呢。
使用 intervention/image
来处理图片吧。
官网:http://image.intervention.io/
github https://github.com/Intervention/image
操作一波
# 先安装
composer require intervention/image
新建一个 utils 工具包,里边放一个 ImageUpload。
app/Utils/ImageUpload.php
<?php
namespace App\Utils;
use Image;
class ImageUpload
{
// 保存二进制
public function saveBinaryImage($file, $folder, $name, $max_width = false)
{
}
// 保存 input file
public function saveFileImage($file, $folder, $name, $max_width = false)
{
}
public function saveBase64Image($file, $folder, $name, $max_width = false)
{
$upload_path = public_path() . '/' . $folder;
// 创建文件夹
if (!file_exists($upload_path))
{
mkdir($upload_path, 0777, true);
}
if(stripos($file, 'data:image/jpeg;base64,') === 0)
{
$img = base64_decode(str_replace('data:image/jpeg;base64,', '', $file));
}
else if(stripos($file, 'data:image/png;base64,') === 0)
{
$img = base64_decode(str_replace('data:image/png;base64,', '', $file));
}
else
{
return array('error' => '非图片文件');
}
$result = file_put_contents($upload_path . $name, $img); //返回的是字节数
if($result == FALSE)
{
return array('error' => '写入文件失败,可能没有权限');
}
// 如果限制了图片宽度,就进行裁剪
if ($max_width && $max_width > 0)
{
// 此类中封装的函数,用于裁剪图片
$this->reduceSize($upload_path . $name, $max_width);
}
return array('code' => 0, 'url' => $folder . $name);
}
private function reduceSize($file_path, $max_width, $new_path = null)
{
// 先实例化,传参是文件的磁盘物理路径
$image = Image::make($file_path);
// 进行大小调整的操作
$image->resize($max_width, null, function ($constraint) {
// 设定宽度是 $max_width,高度等比例双方缩放
$constraint->aspectRatio();
// 防止裁图时图片尺寸变大
$constraint->upsize();
});
// 对图片修改后进行保存
if ($new_path) {
$image->save($new_path);
} else {
$image->save();
}
}
}
然后新建一个 controller
php artisan make:controller ImageController
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Utils\ImageUpload;
class ImageController extends Controller
{
public function store(Request $request)
{
$request->validate([
'info' => 'sometimes|string',
'file' => 'required|string'
],[],[
'info' => '图片信息',
'file' => '图片文件'
]);
$user = $request->user();
$folder = sprintf('storage/upload/image/topic/%s/', date('Ymd', time()));
$name = $user->id . '_' . date('Ymdhis') . randStr(6) . '.jpg';
$res = app(ImageUpload::class)->saveBase64Image($request->file, $folder, $name, 1920);
if ($res && isset($res['error'])) {
Log::channel('error')->error($res);
}
$path = $res['url'];
return response()->json($path, 200);
}
}
就这样吧,卡死 jpg 后缀。