laravel-paperclip icon indicating copy to clipboard operation
laravel-paperclip copied to clipboard

Manually able to trigger rotation on images

Open kimchirichie opened this issue 3 years ago • 2 comments

I briefly looked through czim/file-handler and czim/laravel-paperclip but did not find a convenient way to trigger a rotation on attachments.

  1. Is this even possible for me to extend and open a PR for it?

  2. or should I download, rotate and update the model attachment?

any guidance / starting point on the matter is greatly appreciated.

kimchirichie avatar Oct 30 '20 04:10 kimchirichie

The recommended way is to make an implementation of the Czim\FileHandling\Contracts\Variant\VariantStrategyInterface that handles the rotation as you'd like. You can then refer to this strategy in your attachment configuration on your Eloquent models (or make aliases for it, etc).

If you are going to make a sufficiently reusable rotation strategy, I'd certainly welcome a PR for it. 👍

czim avatar Oct 30 '20 17:10 czim

I did not implement a strategy. The reason is because strategy does not modify the original attachment.

Instead, I manually rotated the photo, and dispatched a task that a queue worker to reprocess the variants.

    public function rotate(Request $request, Photo $photo)
    {
        $validatedData = $request->validate([
            'theta' => 'in:90,180,270',
        ]);

        $degrees = $validatedData['theta'];
        $path = $photo->image->variantPath();

        // grab image as string and create a resource
        $original = Storage::disk('s3')->get($path);
        $temp = imagecreatefromstring($original);

        // open output buffering to prevent output
        ob_start();
        $rotated = imagerotate($temp, $degrees, 0); // rotate
        imagejpeg($rotated); // save resource as file
        $final = ob_get_contents(); // collect buffer
        ob_clean();

        // upload to s3
        Storage::disk('s3')->put($path, $final);

        ProcessVariants::dispatch($photo);

        return response()->json(['success' => 'success'], 200);
    }

In the laravel job App\Jobs\ProcessVariants i would trigger the reprocess by doing the following in the handler:

$this->photo->image->reprocess();

kimchirichie avatar Nov 09 '20 05:11 kimchirichie