mul14
9/7/2015 - 7:48 AM

Easy to get image from a model - Laravel

Easy to get image from a model - Laravel

<?php

namespace App;

use Gregwar\Image\Image;
use Symfony\Component\HttpFoundation\File\UploadedFile;

trait ImageTrait
{
    protected $imageWidth, $imageHeight;

    /**
     * @param string $size Available sizes: tiny, small, medium, large, huge, original
     *
     * @return string
     */
    public function imageUrl($size = 'small')
    {
        return url($this->generateImage($size));
    }

    /**
     * @param string $size Available sizes: tiny, small, medium, large, huge, original
     * @param array  $options
     *
     * @return string
     */
    public function image($size = 'small', $options = [])
    {
        $attributes = '';

        foreach ($options as $key => $value) {
            $attributes .= "$key=\"$value\" ";
        }

        $html = '<img src="%s" %s />';

        return sprintf($html,
            url($this->generateImage($size)), $attributes
        );
    }

    /**
     * @param string|array $size
     *
     * @return string
     */
    protected function generateImage($size)
    {
        $image = $this->openImage();

        if (is_array($size)) {
            $this->imageWidth = $size[0];
            $this->imageHeight = $size[1];
        }

        if ($size == 'tiny') {
            $this->imageWidth = $this->imageHeight = 25;
        }

        if ($size == 'small') {
            $this->imageWidth = $this->imageHeight = 100;
        }

        if ($size == 'medium') {
            $this->imageWidth = $this->imageHeight = 300;
        }

        if ($size == 'large') {
            $this->imageWidth = $this->imageHeight = 500;
        }

        if ($size == 'huge') {
            $this->imageWidth = $this->imageHeight = 800;
        }

        $image->zoomCrop($this->imageWidth, $this->imageHeight);

        return $image->jpeg();
    }

    /**
     * @return string
     */
    protected function imageDirectory()
    {
        if (property_exists($this, 'imageDirectory')) {
            return $this->imageDirectory;
        }

        return $this->getTable();
    }

    /**
     * @return \Gregwar\Image\Image
     */
    protected function openImage()
    {
        $directory = $this->imageDirectory();

        $file = storage_path("images/$directory/{$this->getKey()}.jpg");

        if (file_exists($file)) {
            return Image::open($file);
        }

        return Image::open(storage_path('images/no-image.png'));
    }

    /**
     * @param UploadedFile $file
     *
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile
     * @throws \Exception
     */
    public function saveImage(UploadedFile $file)
    {
        $target = storage_path("images/{$this->imageDirectory()}/{$this->getKey()}.jpg");

        Image::open($file->getPath())->save($target);

        return $file;
    }
}

ImageTrait

First, we need to integrate Gregwar\Image.

Add ImageTrait.php to app directory, then use the trait in model.

<?php

namespace App;

// ...

class User extends Model 
{
    use ImageTrait;
    
    // Optional, by default will use table name
    protected $imageDirectory;
}

Now, you have capability to fetch image related to model without create specific field on database table.

// View

<img src="{{ $user->imageUrl() }}" />

OR

{!! $user->image() !!}
// Another example

$user->image('tiny');
$user->image('small'); // default
$user->image('medium');
$user->image('large');

$user->image('huge', ['class' => 'img-responsive']);

$user->image([640, 480]); // Specific width and height

Save Image

// Example to save image

$user = User::find(1);

$file = \Input::file('image');

$user->saveImage($file);