emsifa/random-image

Store random image from Unsplash to your Laravel application

v1.0.0 2023-02-18 09:48 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Random Image is a Laravel helper to get random image and store it in your application. It is designed to be used in model factory to seed dummy data.

Currently we have 3 random image provider you can choose:

  1. LoremFlickr (default)
  2. Unsplash
  3. LoremPicsum (doesn't support search query)

Please see their website for the license information.

Features

  • Get random image URL with search terms support.
  • Store random image to filesystem.
  • Manipulate downloaded image.
  • Copy downloaded image and manipulate it (for thumbnail/placeholder image generation).

Installation

You can install the package via composer:

composer require emsifa/random-image --dev

Remove --dev flag if you are planned to use this library in production

After that, you may want to publish the config file with:

php artisan vendor:publish --tag="random-image-config"

It will generate config/random-image.php file in your project directory.

Usage Example

Get Random Image URL

If you just want to get image url from provider, you can use url method like an example below:

use Emsifa\RandomImage\RandomImage;

RandomImage::make()->url();

It will return https://loremflickr.com/600/400/ which will resulting different image if you use it in <img/> tag.

You can also specify size and search terms inside make method like this:

RandomImage::make(200)->url();                  // "https://loremflickr.com/200/200/"
RandomImage::make(300, 200)->url();             // "https://loremflickr.com/300/200/"
RandomImage::make(300, 200, 'cat,dog')->url();  // "https://loremflickr.com/300/200/cat,dog"
RandomImage::make(query: 'cats')->url();        // "https://loremflickr.com/600/400/cats"

The URL returned will be different for every provider. For example, if you use Unsplash provider, the URL generated would be like this:

RandomImage::make(200)->url();                  // "https://source.unsplash.com/random/200x200/"
RandomImage::make(300, 200)->url();             // "https://source.unsplash.com/random/300x200/"
RandomImage::make(300, 200, 'cat,dog')->url();  // "https://source.unsplash.com/random/300x200/?cat,dog"
RandomImage::make(query: 'cats')->url();        // "https://source.unsplash.com/random/?cats"

You can change provider in config/random-image.php file.

Store Image

You can use store or storeAs method to download and store image into your filesystem disk.

RandomImage::make()->store();           // "{random-hash-name}.jpg"
RandomImage::make()->store('images');   // "images/{random-hash-name}.jpg"

You can specify disk by defining disk parameter:

RandomImage::make()->store('images', 's3'); // "images/{random-hash-name}.jpg"
RandomImage::make()->store(disk: 's3');     // "{random-hash-name}.jpg"

Use storeAs if you want to specify filename:

RandomImage::make()->storeAs('', 'my-image.jpg');       // "my-image.jpg"
RandomImage::make()->storeAs('images', 'my-image.jpg'); // "images/my-image.jpg"

You can also get stored URL just by chaining it with url() method like example below:

RandomImage::make()->store()->url();            // "http://your-app.test/storage/{random-hash-name}.jpg"
RandomImage::make()->store('images')->url();    // "http://your-app.test/storage/images/{random-hash-name}.jpg"

RandomImage::make()->storeAs('', 'my-image.jpg')->url();       // "http://your-app.test/storage/my-image.jpg"
RandomImage::make()->storeAs('images', 'my-image.jpg')->url(); // "http://your-app.test/storage/images/my-image.jpg"

Or if you want to get the filename only, you can chain it with name() method.

RandomImage::make()->store()->name();            // "{random-hash-name}.jpg"
RandomImage::make()->store('images')->name();    // "{random-hash-name}.jpg"

RandomImage::make()->storeAs('', 'my-image.jpg')->name();        // "my-image.jpg"
RandomImage::make()->storeAs('images', 'my-image.jpg')->name();  // "my-image.jpg"

Usage Example in Model Factory

This package is designed to be used in the model factory, which is why methods above return a string of image path/url so you can just store it in the database. To use it in the model factory, you can just call the method in the example above in your model factory like this:

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Emsifa\RandomImage\RandomImage;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->words(5, true),
            'body' => $this->faker->paragraphs(5, true),
            'image' => RandomImage::make(600, 400)->store('posts', 'public'),
        ];
    }
}

When you seed posts data using factory above, you can use Storage::disk('public')->url($post->image) to get the url.

Copy and Manipulate Downloaded Image

In most case you may want to create a thumbnail version of the same image. We wrap some APIs from intervention/image to do that kind of stuff.

For example, in Post factory above, we want to define thumbnail field that contain a path for 300x200px version of the image:

public function definition()
{
    $image = RandomImage::make(600, 400)->store('posts', 'public');
    $thumbnail = $image->copy()->fit(300, 200);

    // Resize to 300x200px and make it greyscale
    // $thumbnail = $image->copy()->fit(300, 200)->greyscale();

    // Use copyAs if you want to specify filename 
    // $thumbnail = $image->copyAs('posts', 'my-thumb.jpg')->fit(300, 200);

    return [
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(5, true),
        'image' => $image,
        'thumbnail' => $thumbnail,
    ];
}

NEW: You can use previous method to do the same thing as example above, but much simpler.

public function definition()
{
    return [
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(5, true),
        'image' => RandomImage::make(600, 400)->store('posts', 'public'),
        'thumbnail' => RandomImage::previous()->copy()->fit(300, 200),
    ];
}

Here is a list of manipulation methods you can use:

  • resize(width, height): Resizes current image based on given width and/or height. (intervention docs)
  • crop(width, height, x, y): Cut out a rectangular part of the current image with given width and height. (intervention docs)
  • fit(width, height): Combine cropping and resizing to format image in a smart way. (intervention docs)
  • widen(width): Resizes the current image to new width, constraining aspect ratio. (intervention docs)
  • heighten(height): Resizes the current image to new height, constraining aspect ratio. (intervention docs)
  • greyscale(): Turns image into a greyscale version. (intervention docs).
  • grayscale(): An alias of greyscale.
  • blur(): Apply a gaussian blur filter with a optional amount on the current image. (intervention docs)

All methods above is available on the ImageResult instance which is returned from store method. So you can use it not only to copied image. But the original stored image too.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.