Skip to content

Commit

Permalink
Merge pull request #1 from konnco/feature/auto-resize
Browse files Browse the repository at this point in the history
Feature/auto resize
  • Loading branch information
frankyso authored Jun 27, 2021
2 parents e966a9d + c00b173 commit 4aebcc5
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 6 deletions.
28 changes: 23 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

This is where your description should go. Limit it to a paragraph or two. Consider adding a small example.

## Atention!
this package is still under beta testing, do don't use it in your production.

## Installation

You can install the package via composer:
Expand Down Expand Up @@ -59,16 +62,31 @@ $user = New User();
$user->name = $request->name;
$user->avatar = $request->photo;
$user->save();

$user->refresh(); // to get compiled parameters
```

The response you get after saving the image
## Custom Size Image
In here we have added custom sized image which you can modify through the url,

first you have to modify file `App\Exceptions\Handler` and add this code inside `render` method.

```php
// path location
$user->avatar->path
use Konnco\ImageCast\ImageCastExceptionHandler;

public function render($request, Throwable $exception) {
return new ImageCastExceptionHandler($exception, request()->url(), function(){
return parent::render($request, $exception);
});
}
```

after that try to embed this script inside your blade;
```html
<img src="{{$user->avatar->filters(['w_100','h_100'])}}" alt="Image"/>
```

the `w_100` means we need to resize this image into 100px and `h_100` to set height as 100%.


## Testing

```bash
Expand Down
17 changes: 16 additions & 1 deletion config/imagecast.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,20 @@
| you can see how it used in https://github.com/woltapp/blurhash
|
*/
'blurhash' => env('IMAGECAST_BLURHASH', false)
'blurhash' => env('IMAGECAST_BLURHASH', false),

/*
|--------------------------------------------------------------------------
| Cache Support
|--------------------------------------------------------------------------
|
| This configuration make sure you only load the specific image and resize it
|
*/
'cache' => [
/**
* If the url containes this identifier mean the image should be resized
*/
'identifier' => env('IMAGECAST_CACHE_IDENTIFIER', 'caches/assets')
]
];
6 changes: 6 additions & 0 deletions src/Casts/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ public function set($model, $key, $value, $attributes)

$this->storage->put($image['path'], $image['imageManager']->encode($image['extension'], $this->quality)->__toString());

// Add identifier inside folders
$this->storage->put($image['path'].".fingerprint", json_encode([
"class" => get_class($model),
"field" => $key,
]));

$jsonResults = json_encode([
"path" => $image['path'],
"disk" => $this->disk,
Expand Down
50 changes: 50 additions & 0 deletions src/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace Konnco\ImageCast;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic as ImageIntervention;

class Image
{
public $url;
Expand All @@ -16,4 +20,50 @@ public function __construct($array)
$this->path = $array['path'];
$this->disk = $array['disk'];
}

public function filters($filters = [])
{
$filters = collect($filters)->sort();

return config('imagecast.cache.identifier')."/".$filters->join(',')."/".$this->path;
}

/**
* This function will helping to serve the resized image
* from requested url
*/
public function temporaryResize($filters = [])
{
$resize = false;
$width = null;
$height = null;

foreach ($filters as $key => $filter) {
if (Str::startsWith($filter, 'w_')) {
$resize = true;
$width = str_replace("w_", "", $filter);
}

if (Str::startsWith($filter, 'h_')) {
$resize = true;
$height = str_replace("h_", "", $filter);
}
}

if ($resize) {
$rawImage = Storage::disk($this->disk)->get($this->path);
$image = ImageIntervention::make($rawImage);

$image->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});

$filters = collect($filters);
$filters = $filters->sort();

$savePath = config('imagecast.cache.identifier')."/".implode(",", $filters->toArray())."/".$this->path;
Storage::disk('public')->put(config('imagecast.cache.identifier')."/".implode(",", $filters->toArray())."/".$this->path, $image->__toString());
}
}
}
58 changes: 58 additions & 0 deletions src/ImageCastExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace Konnco\ImageCast;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ImageCastExceptionHandler
{
public function __construct($exception, $url, $callback)
{
if ($exception instanceof NotFoundHttpException) {
if (Str::contains($url, config('imagecast.cache.identifier'))) {
// remove site url with the identifiers
$url = str_replace(config('app.url')."/".config('imagecast.cache.identifier')."/", "", $url);
$fullPath = $this->extractFileName($url);
$fingerprint = $this->extractFingerprint($fullPath);
$filters = $this->extractFilters($url);
// dd(($fingerprint['class'])::get());
// dd($fileName);
$eloquent = ($fingerprint['class'])::where($fingerprint['field'], 'like', "%".basename($fullPath)."%")->first();
if ($eloquent) {
// dd($fingerprint['field']);
$field = $fingerprint['field'];
$eloquent->$field->temporaryResize($filters);
}

return redirect($url);
}
}

return $callback();
}

private function extractFilters($url)
{
$urlArray = explode('/', $url);
$filters = explode(',', $urlArray[0]);

return $filters;
}

private function extractFileName($url)
{
$urlArray = explode('/', $url);
array_shift($urlArray);

return implode("/", $urlArray);
}

private function extractFingerprint($url)
{
$fingerprint = Storage::disk(config('imagecast.disk'))->get($url.".fingerprint");

return json_decode($fingerprint, true);
}
}
37 changes: 37 additions & 0 deletions src/Jobs/ResizeImage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ResizeImage implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;

protected $model;

/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
}

/**
* Execute the job.
*
* @return void
*/
public function handle()
{
}
}
33 changes: 33 additions & 0 deletions tests/ModelCastTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
namespace Konnco\ImageCast\Tests;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Konnco\ImageCast\ImageCastExceptionHandler;
use Konnco\ImageCast\Tests\src\Models\User;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ModelCastTest extends TestCase
{
Expand All @@ -21,4 +24,34 @@ public function model_can_save_image_image_path()

Storage::disk(config('imagecast.disk'))->assertExists($user->avatar->path);
}

/** @test */
public function check_imagecast_exceptional_handler()
{
Storage::fake(config('imagecast.disk'));

$user = new User;
$user->avatar = UploadedFile::fake()->image('photo1.jpg');
$user->save();

$user->refresh();

$url = config('imagecast.cache.identifier')."/h_100,w_100/".$user->avatar->path;

$exceptional = new ImageCastExceptionHandler(new NotFoundHttpException(), config('app.url')."/".$url, function () {
});

Storage::disk('public')->assertExists($url);



// request()->url($user->avatar->temporaryResize(['w_200','h_100']));

//

// $response = Http::get();
// dd($response);

// dd();
}
}
1 change: 1 addition & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ protected function getPackageProviders($app)
public function getEnvironmentSetUp($app)
{
config()->set('database.default', 'testing');
config()->set('app.url', url(''));

include_once __DIR__.'/../database/migrations/create_imagecast_table.php.stub';
(new \CreateImageCast())->up();
Expand Down

0 comments on commit 4aebcc5

Please sign in to comment.