laravel-admin : 添加百度编辑器图片压缩功能

景俊语
2023-12-01


app/Admin/Override/StorageManager.php

<?php


namespace App\Admin\Override;


use Codingyu\LaravelUEditor\Events\Catched;
use Codingyu\LaravelUEditor\Events\Uploaded;
use Codingyu\LaravelUEditor\Events\Uploading;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Intervention\Image\ImageManager;

class StorageManager extends \Codingyu\LaravelUEditor\StorageManager
{

    public function upload(Request $request)
    {
        Log::info('覆盖成功');
        $config = $this->getUploadConfig($request->get('action'));

        if (!$request->hasFile($config['field_name'])) {
            return $this->error('UPLOAD_ERR_NO_FILE');
        }

        $file = $request->file($config['field_name']);

        if ($error = $this->fileHasError($file, $config)) {
            return $this->error($error);
        }

        $filename = $this->getFilename($file, $config);

        if ($this->eventSupport()) {
            $modifiedFilename = event(new Uploading($file, $filename, $config), [], true);
            $filename = !is_null($modifiedFilename) ? $modifiedFilename : $filename;
        }

        Log::info('上传中事件执行了');


        $this->store($file, $filename);

        $response = [
            'state' => 'SUCCESS',
            'url' => $this->getUrl($filename),
            'title' => $filename,
            'original' => $file->getClientOriginalName(),
            'type' => $file->getExtension(),
            'size' => $file->getSize(),
        ];

        //更改图片上传逻辑, 上传的其它文件类型不作处理
        $fileType = $file->guessExtension();
        if (in_array($fileType, ['jpg', 'png', 'jpeg'])) {
            $imageManager = new ImageManager();
            $image = $imageManager->make($file);
            $width = $image->width();
            $maxWidth = app()['config']->get('ueditor.upload.imageMaxWidth', 'public');
            if ( $width > $maxWidth || in_array($fileType, ['jpg', 'jpeg'])) {
                //尺寸大于$maxWidth 1000或者是jpg才压缩
                Log::info('压缩文件');
                if ($width > $maxWidth) {
                    $image->resize($maxWidth, null, function($constraint){
                        $constraint->aspectRatio();
                    });
                }
                //$this->disk->put($filename, $image->stream());
                $this->disk->put($filename, $image->encode($fileType,80));
                Log::info('压缩文件结束');
                $response['size'] = $image->filesize();
            }
        }

        if ($this->eventSupport()) {
            event(new Uploaded($file, $response));
        }

        return response()->json($response);
    }

    /**
     * Fetch a file.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetch(Request $request)
    {
        $config = $this->getUploadConfig($request->get('action'));
        $urls = $request->get($config['field_name']);
        if (count($urls) === 0) {
            return $this->error('UPLOAD_ERR_NO_FILE');
        }
        $urls = array_unique($urls);

        $list = array();
        foreach ($urls as $key => $url) {
            $img = $this->download($url, $config);
            $item = [];
            if ($img['state'] === 'SUCCESS') {
                $file = $img['file'];
                $filename = $img['filename'];
                $this->storeContent($file, $filename);
                if ($this->eventSupport()) {
                    unset($img['file']);
                    event(new Catched($img));
                }
            }
            unset($img['file']);
            array_push($list, $img);
        }

        $response = [
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ];

        return response()->json($response);
    }

    /**
     * Download a file.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return Array $info
     */
    private function download($url, $config)
    {
        if (strpos($url, 'http') !== 0) {
            return $this->error('ERROR_HTTP_LINK');
        }
        $pathRes = parse_url($url);
        $img = new \SplFileInfo($pathRes['path']);
        $original = $img->getFilename();
        $ext = $img->getExtension();
        if (!$ext) {
            //文件名中拿不到扩展名,从mime判断扩展名
            $mimes=array(
                'image/bmp'=>'bmp',
                'image/gif'=>'gif',
                'image/jpeg'=>'jpg',
                'image/png'=>'png',
                'image/x-icon'=>'ico'
            );
            $headers=get_headers($url, 1);
            $type=$headers['Content-Type'];
            if ($headers && isset($mimes[$type])) {
                $ext = $mimes[$type];
            }
        }
        $title = md5($url) . '.' . $ext;
        $filename = $this->formatPath($config['path_format'], $title);
        $info = [
            'state' => 'SUCCESS',
            'url' => $this->getUrl($filename),
            'title' => $title,
            'original' => $original,
            'source' => $url,
            'size' => 0,
            'file' => '',
            'filename' => $filename,
        ];

        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false, // don't follow redirects
            ))
        );
        $file = fopen($url, 'r', false, $context);
        if ($file === false) {
            $info['state'] = 'ERROR';
            return $info;
        }
        $content = stream_get_contents($file);
        fclose($file);

        $info['file'] = $content;
        $info['siez'] = strlen($content);
        return $info;
    }
}

app/Providers/AppServiceProvider.php

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema; //add fixed sql
+use App\Admin\Override\StorageManager;
+use Illuminate\Support\Facades\Storage;

class AppServiceProvider extends ServiceProvider
{
@@ -15,6 +17,11 @@ class AppServiceProvider extends ServiceProvider
    public function boot()
    {
        Schema::defaultStringLength(191); //add fixed sql

        //覆写百度编辑器上传方法
        +app()->singleton('ueditor.storage', function ($app) {
            return new StorageManager(Storage::disk($app['config']->get('ueditor.disk',         'public')));
        });
    }

 composer.json

//require下

"intervention/image": "^2.5",

 config/ueditor.php

 'upload' => [
        /* 前后端通信相关的配置,注释只允许使用多行方式 */
        /* 上传图片配置项 */
        +'imageMaxWidth' => env('UEDITOR_UPLOAD_IMAGE_MAX_WIDTH', 1000), //上传图片最大宽度,超出则压缩
        'imageActionName' => 'upload-image', /* 执行上传图片的action名称 */
        'imageFieldName' => 'upfile', /* 提交的图片表单名称 */
        'imageMaxSize' => 2 * 1024 * 1024, /* 上传大小限制,单位B */

 

 类似资料: