<?php
namespace App\Services;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Exceptions\ImageUploadException;
use Image;
use Auth;
class ImageUpload
{
protected $file;
protected $allowed_extensions = ["png", "jpg", "gif", 'jpeg'];
protected $height_arr = [];
public function __construct()
{
$this->height_arr = [
'big' => getSetting('upload_picture_thumbnail_max'),
'middle' => getSetting('upload_picture_thumbnail_middle'),
'small' => getSetting('upload_picture_thumbnail_small')
];
}
public function uploadImage(UploadedFile $file)
{
$this->file = $file;
$this->checkAllowedExtensionsOrFail();
$local_image = $this->saveImageToLocal('topic', getSetting('upload_picture_mix'));
return ['filename' => $local_image];
}
protected function checkAllowedExtensionsOrFail()
{
$extension = strtolower($this->file->getClientOriginalExtension());
if ($extension && !in_array($extension, $this->allowed_extensions)) {
throw new ImageUploadException('你只能上传以下格式的图片:' . implode($this->allowed_extensions, ','));
}
}
protected function saveImageToLocal($type, $resize, $filename = '')
{
$year_mouth = date("Ym", time());
$folderName = ($type == 'avatar')
? 'upload/avatars'
: 'upload/images/' . $year_mouth .'/'.date("d", time()) .'/'. Auth::user()->id;
$destinationPath = public_path() . '/' . $folderName;
$extension = $this->file->getClientOriginalExtension() ?: 'png';
$filename = $filename ? :date("YmdHis", time()).'_'.str_random(2);
$safeName = $filename . '.' . $extension;
$this->file->move($destinationPath, $safeName);
$files['original'] = $folderName .'/'. $safeName;
$files['extension'] = $extension;
$files['filename'] = $filename;
$files['year_month'] = $year_mouth;
if ($this->file->getClientOriginalExtension() != 'gif') {
$img = Image::make($destinationPath . '/' . $safeName);
$img->resize($resize, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save();
foreach ($this->height_arr as $key => $height) {
if ($height == 0) {
continue;
}
if ($key == 'small') {
$img->fit($height / 3 * 5, $height);
} else {
$img->resize(null, $height, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
$safeName = $filename.'_'.$key.'.'.$extension;
$img->save($destinationPath.'/'.$safeName);
$files[$key] = $folderName .'/'.$safeName;
}
}
return $files;
}
}