Laravel Package for making thumbnails instantly

Overview

Laravel Thumbnails

Stars Downloads StyleCI Build Status Scrutinizer Code Quality CodeFactor License Laravel News MadeWithLaravel.com shield

Laravel Thumbnail Generator

Package for uploading the image and saving that image along with it's thumbnail.

What does it do ?

  • Uploads Image
  • Make its thumbnail i.e low quality, resized version of its parent image

Why use thumbnails ?

The small file size of thumbnails makes it possible for website designers to offer visitors a lot of content immediately without increasing the loading time of the page. Also why use full glory of that image if you just have to crunched it up to tiny space... Use thumbnail.

Installation

Run Composer Require Command

$ composer require drh2so4/thumbnail

Use thumbnail trait to your model

<?php

namespace App;

use drh2so4\Thumbnail\Traits\thumbnail;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use Thumbnail;

    protected $fillable = ['image'];
}

This model consists of following methods :-

  • makeThumbnail
  • thumbnail
  • uploadImage
  • hasThumbnail
  • thumbnailCount
  • imageDetail
  • hardDelete

Usages

Package utilizes it's trait method, let us guide you to use that

makeThumbnail

This method is responsible for actually uploading the image and making its thumbnail.

    public function store(Request $request)
    {
        $image = Image::create($this->validateData());
        $image->makeThumbnail('image'); //This handles uploading image and storing it's thumbnail
        return redirect('/imageUpload');
    }

Same can go with update method.

thumbnail

Well, we created our thumbnail but how to use it, let me guide through that When we uploaded image with name suppose "batman". Image is upload with name batman-current_time_instant i.e (batman-1521549.jpg).

What about thumbnail... well thumbnail uses it's parent image name followed by -size i.e batman-1521549-medium-jpg, batman-1521549-small.jpg

How to make thumbnail ?

There are the options you can have for making thumbnails :-

  • Default Option
  • Universal Custom Thumbnails
  • Specfic Custom Thumbnails

Default Option

you can just call the following and the packages will handle the rest

    $image->makeThumbnail('image'); //Here the first parameter is image attribute name saved in db

Note : if the attribute dedicated for storing image is named 'image' you don't have to pass image attribute name jusr use $image->makeThumbnail();

Universal Custom Thumbnails

here you should mention the thumbnails that you want to be applied on every case. when you publish thumbnail.php config file you will find 'thumbnails' property where you can mention your custom thumbnails

    /*
    |--------------------------------------------------------------------------
    | Custom Thumbnail Creation
    |--------------------------------------------------------------------------
    | Uncomment to create...
    */

    /*     "thumbnails" => [
        [
            "thumbnail-name" => "medium",
            "thumbnail-width" => 800,
            "thumbnail-height" => 600,
            "thumbnail-quality" => 60
        ],
        [
            "thumbnail-name" => "small",
            "thumbnail-width" => 400,
            "thumbnail-height" => 300,
            "thumbnail-quality" => 30
        ]
    ] */

Note: This will override default option

Specfic Custom Thumbnails

Suppose you have applied Universal Custom Thumbnails but need to have changes for specific image field then you can pass array of custom requirements :

        $thumbnails = [
            'storage' => 'customs/embed',
            'width' => '600',
            'height' => '400',
            'quality' => '70',
            'thumbnails' => [
                [
                    'thumbnail-name' => 'customSmall',
                    'thumbnail-width' => '300',
                    'thumbnail-height' => '200',
                    'thumbnail-quality' => '50'
                ]
            ]
        ];
        $image->makeThumbnail('image', $thumbnails);

How about multiple image uploads

If you are performing multiple image upload at once pass image key to thumbnail array. here $img is one of the image in chunk of images passed

// Controller Store Method
public function store(Request $request)
{
    $image = Image::create(['images'=>$request->images]);
    foreach($request->images as $img)
    {
        $this->multipleImageUpload($image,$img);
    }
}
// Multiple Image Upload
    private function multipleImageUpload($image, $img)
    {
        $multiple = [
            'storage' => 'custom_test/folder/another_folder/image',
            'width' => '600',
            'height' => '400',
            'quality' => '70',
            'image' => $img,
            'thumbnails' => [
                [
                    'thumbnail-name' => 'small',
                    'thumbnail-width' => '300',
                    'thumbnail-height' => '200',
                    'thumbnail-quality' => '50'
                ]
            ]
        ];
        $image->makeThumbnail('image', $multiple);
    }

How to use thumbnail ?

Just call as following

// Here the first parameter 'image' is the name of sttribute that is saved in db for image

    @foreach ($images as $image)
        <img src="{{asset($image->thumbnail('image','small'))}}"> // For small thumbnail
    <img src="{{asset($image->thumbnail('image','medium'))}}"> // For medium thumbnail
    @endforeach

if you are using custom thumbnail configured from config file just call as follows

// Here the first parameter 'image' is the name of sttribute that is saved in db for image
// Second parameter is the name of thumbnail that you gave in 'thumbnail-name' in the config file on custom thumbnail field called 'thumbnails'
    @foreach ($images as $image)
        <img src="{{asset($image->thumbnail('image','small'))}}"> // For small thumbnail
    <img src="{{asset($image->thumbnail('image','medium'))}}"> // For medium thumbnail
    @endforeach

Notice that parameter of function thumbnail is string same as value given for "thumbnail-name" in config file.

Thumbnail's image property is predefined but if you wish to change that publish it's config file thumbnail.php

php artisan vendor:publish --tag=thumbnail-config

Image Property

You can obtaing the detail image property by using method imageDetail($image,$size)

// imageDetail method takes two parameter
// Model image attribute name (Mandatory)
// If you want thumbnail property pass its size (optional)

$image->imageDetail('image'); // Parent Image Detail Property
$image->imageDetail('image','small') // Small thumbnail related to parent image

What Image Property/Detail Gives

Default Thumbnail Image Properties

Property Return Type Description Example
image string Image path stored in DB $image->imageDetail('image')->image
name string Image Stored Name (without extension) $image->imageDetail('image')->name
fullname string Image Stored Name (with extension) $image->imageDetail('image')->fullname
extension string Image Extension Name $image->imageDetail('image')->extension
path string Image Storage Path $image->imageDetail('image')->path
directory string Image Stored Directory $image->imageDetail('image')->directory
location string Image Full Location Path $image->imageDetail('image')->location
property array Image Property array $image->imageDetail('image')->property

Image Property array ($image->imageDetail('image')->property)

Property Return Type Description Example
real_name string Image Real Name (without timestamp and size label) $image->imageDetail('image')->property->name
size integer Image Storage Size $image->imageDetail('image')->property->fullname
directory string Image Stored Directory $image->imageDetail('image')->property->directory
location string Image Full Location Path $image->imageDetail('image')->property->location
has_thumbnail boolean Image's Thumbnail Check $image->imageDetail('image')->property->has_thumbnail
thumbnail_count integer Image Thumbnail Count $image->imageDetail('image')->property->thumbnail_count
thumbnails array Return all thumbnail Detail $image->imageDetail('image')->property->thumbnails

Image Thumbnail Property

Property Return Type Description
image string Thumbnail Name
real_name string Thumbnail Real Name (without timestamp and size label)
size integer Thumbnail Storage Size
created_date Carbon Thumbnail Created Date
path string Thumbnail Storage Path
directory string Thumbnail Stored Directory
location string Thumbnail Full Location Path

Check if image has thumbnail

$image->hasThumbnail('image'); // Check for any availabe thumbnail
$image->hasThumbnail('image','small'); // Second paremater is thumbnail size check

Obtain Image Thumbnail Count

$image->thumbnailCount('image');

Hard Delete Image with Thumbnails

$image->hardDelete('image'); // First parameter is db attribute name for image

Hard Delete Image with Thumbnails adn its parent

$image->hardDeleteWithParent('image'); // First parameter is db attribute name for image

Upload Only Umage

$solo_image = [
                'storage' => 'solo',
                'width' => '600',
                'height' => '300',
                'quality' => '70',
            ];
            $image->uploadImage('image', $solo_image); // Second Parameter is not necessary if default settings is to be applied
            // OR
            $image->uploadImage('image'); // Image Upload with default setting

Our config file looks like follows :-

<?php

return [


    /*
    |--------------------------------------------------------------------------
    |  Thumbnail Feature
    |--------------------------------------------------------------------------
    |
    | This option defines whether to use Package's Thumbnail feature or not
    | Default option is true
    |
    */
    'thumbnail' => true,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail Qualities
    |--------------------------------------------------------------------------
    |
    | These options are default post image and its thumbnail quality
    |
    |
    */

    'image_quality' => 80,
    'medium_thumbnail_quality' => 60,
    'small_thumbnail_quality' => 30,

    /*
    |--------------------------------------------------------------------------
    | Default Image Fit Size
    |--------------------------------------------------------------------------
    |
    | These options is default post imahe height and width fit size
    |
    |
    */

    'img_width' => 1000,
    'img_height' => 800,

    'medium_thumbnail_width' => 800,
    'medium_thumbnail_height' => 600,

    'small_thumbnail_width' => 400,
    'small_thumbnail_height' => 300,

    /*
    |--------------------------------------------------------------------------
    | Image and Thumbnail Storage Path
    |--------------------------------------------------------------------------
    |
    | Define your default image storage location along with its thumbnail
    |
    |
    */

    "storage_path" => "uploads",

    /*
    |--------------------------------------------------------------------------
    | Custom Thumbnail Creation
    |--------------------------------------------------------------------------
    | Uncomment to create...
    */

    /*     "thumbnails" => [
        [
            "thumbnail-name" => "medium",
            "thumbnail-width" => 800,
            "thumbnail-height" => 600,
            "thumbnail-quality" => 60
        ],
        [
            "thumbnail-name" => "small",
            "thumbnail-width" => 400,
            "thumbnail-height" => 300,
            "thumbnail-quality" => 30
        ],
        ] */
];

Feel free to change the values

Default Thumbnail Image Properties

Thumbnail Width Height Quality
Uploaded Image 1000 800 80
Medium Thumbnail 800 600 60
Small Thumbnail 400 300 30

Laravel Thumbnails

Todos

  • Error Handling
  • Image Caching
  • Maintainabilty

Package Used

License

MIT

DOCTYPE NEPAL || DR.H2SO4

You might also like...
get nearby location by coordinate from eloquent laravel

LARAVEL-COORDINATE get nearby location data from database with eloquent laravel Installation composer require bagusindrayana/laravel-coordinate In M

Optimize your images on the fly with Glide for Laravel.
Optimize your images on the fly with Glide for Laravel.

Glide for Laravel Optimize your images on the fly with Glide for Laravel. Support us Like our work? You can support us by purchasing one of our produc

Laravel Favicon - Create dynamic favicons based on your environment settings.
Laravel Favicon - Create dynamic favicons based on your environment settings.

Laravel Favicon Create dynamic favicons based on your environment settings. Laravel Package Development If you want to learn how to create reusable PH

This is an image manipulation REST API written in PHP Laravel Framework

Laravel Image Manipulation REST API Demo Here is fully working Demo: https://www.lobiimages.com/ You have to register first in order to generate acces

🤹‍♀️Very simple to use Gravatar implementation for Laravel
🤹‍♀️Very simple to use Gravatar implementation for Laravel

Very simple to use Gravatar implementation for Laravel. Install, Include the Facade and then generate, simple! Installation You can install the packag

Making multiple identical function calls has the same effect as making a single function call.

Making multiple identical function calls has the same effect as making a single function call.

Color-managed thumbnails for Kirby 3

ImageKit for Kirby 3 This is not directly related for ImageKit for Kirby 2, but based on the same idea of improving Kirby’s built-in image processing

Smd thumbnail - Multiple image thumbnails of arbitrary dimensions

smd_thumbnail Download | Packagist If you’re bored of one Textpattern thumbnail per image and don’t fancy using an auto-resizing script or relying on

Addon for Cockpit CMS - store thumbnails and meta data for video links

VideoLinkField Addon for Cockpit CMS Copy a url from YouTube or Vimeo, click the Button "Find Values", wait a second and in the background starts a se

Made a custom Elementor widget because i wasn't able to find any free version of a slider with thumbnails.
Made a custom Elementor widget because i wasn't able to find any free version of a slider with thumbnails.

Support my work ❤️ Buy me a coffee ☕ How to install Download - place in plugin folder - Activate under WordPress dashboard. How to use Open Elemento

Images and thumbnails.
Images and thumbnails.

Deutsch English Svenska Image 0.8.16 Images and thumbnails. How to add an image Create an [image] shortcut. The following arguments are available, all

Instantly login as user via a single button tap on dev environments.
Instantly login as user via a single button tap on dev environments.

Getting tired of always entering login details in local dev environments? This package adds a button to instantly login a user! Installation You can i

ClassicPress: The CMS for Creators. Stable. Secure. Instantly Familiar.
ClassicPress: The CMS for Creators. Stable. Secure. Instantly Familiar.

ClassicPress: The CMS for Creators. Stable. Secure. Instantly Familiar. ClassicPress is a community-led open source content management system for crea

⚓️ Easily test HTTP webhooks with this handy tool that displays requests instantly.

Webhook.site With Webhook.site, you instantly get a unique, random URL that you can use to test and debug Webhooks and HTTP requests, as well as to cr

Thirdweb-wp - A community WordPress plugin for thirdweb. Turn your WordPress website into Web3 instantly and easily with thirdweb. 💻🌏

Thirdweb WP 📢 Nominate (@WarenGonzaga) as GitHub Star. If you appreciate his hardwork and dedication to open source. A community WordPress plugin for

This Repository contains a custom Workflow for Alfred which provides the function to instantly search in the Magento 2 DevDocs
This Repository contains a custom Workflow for Alfred which provides the function to instantly search in the Magento 2 DevDocs

Introduction Add the custom search to your Alfred Workflow and have a quicker access to the Magento 2 DevDocs. Installation Just download the alfredwo

Instantly connects the Subtext text messaging service with Paid Memberships Pro.

INSTANTLY CONNECTS AND INTEGRATES THE SUBTEXT TEXT MESSAGING SERVICE WITH PAID MEMBERSHIPS PRO. This plugin instantly and easily connects, and integra

A Laravel package making a diagram of your models, relations and the ability to build them with it
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.
This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.

Laravel Mobile Verification Introduction Many web applications require users to verify their mobile phone numbers before using the application. Rather

Comments
  • Errors when image field is not correctly formatted or empty

    Errors when image field is not correctly formatted or empty

    I installed the plugin into an existing project which already has some images set in the tables. When I call $image->thumbnail('image','small') it throws an error ErrorException Undefined offset: 1 on line 197 of drh2so4\thumbnail\src\Traits\Thumbnail.php

    this is to be expected of course because there's no check after the explode on "-" character if the length is actually higher than 1. So calling [1] on the split will fail.

    I tried to prevent the error by using hasThumbnail but this is using the exact same function so not resolved. When I clear the image column for that particular row, it also doesn't work when calling "hasThumbnail".

    Again because there's no check if result of this search is null

    Code:

    public function hasThumbnail($fieldname = 'image', $size = null)
    {
        return $this->imageDetail($fieldname, $size)->property->has_thumbnail;
    }
    

    I can get around it for now by checking the column value on the model. Maybe if I have time I'll see if I can push a fix but not a lot of time at the moment.

    UPDATE Apparently the issue is because some file in my uploads didn;t follow the correct naming (older upload before adding the library). Still consider this a bug. Also wonder how performant this is but that's another discussion :-)

    It's fixed when you add the following to drh2so4\thumbnail\src\Traits\Thumbnail.php (line 197)

    if (!isset($image_partition[1])) {
     continue;
    };
    
    opened by Alwyn-RM 1
Releases(v1.0.9)
Owner
DRH2SO4
DRH2SO4
Laravel Optical Character Reader(OCR) package using ocr engines like Tesseract

LaraOCR Laravel Optical Character Reader(OCR) package using ocr engines like Tesseract under the hood. Features Read text from image using WebUI/Progr

Al Imran Ahmed 100 Jan 4, 2023
Picasso is a Laravel Image Management and Optimization Package

Picasso is a Laravel Image Management and Optimization Package. Define image dimensions and options, store uploaded image in multiple dimensions with or without a watermark and retrieve optimized images on your website when needed.

Laravelista 82 Nov 24, 2022
A Laravel Gravatar package for retrieving gravatar image URLs or checking the existance of an image.

Gravatar for Laravel 5.x, 6, 7 and 8 Installation First, pull in the package through Composer via the command line: composer require creativeorange/gr

Creativeorange 477 Dec 1, 2022
Laravel package a helper to Generate the QR code and signed it for ZATCA E-invoicing

Laravel ZATCA E-invoicing Introduction Laravel package a helper to Generate the QR code and signed it for ZATCA E-invoicing Installation To get the la

Ayman Alaiwah 8 Aug 17, 2022
An unofficial package maintained by Salla to help developers to implement ZATCA (Fatoora) QR code easily which required for e-invoicing

ZATCA (Fatoora) QR-Code Implementation An unofficial package maintained by Salla to help developers to implement ZATCA (Fatoora) QR code easily which

Salla 96 Dec 25, 2022
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
Laragram is a simple instagram "clone" built with Laravel and Tailwind CSS

Laragram is a simple instagram "clone" built with Laravel and Tailwind CSS that gives to the users the ability to create or edit their own profiles (including profile image and description), upload images and share them among friends

null 0 Jul 24, 2021
Laravel Qcloud Content Security T-Sec 腾讯云内容安全(文字图片内容审核)服务

Laravel Qcloud Content Security T-Sec 天御内容安全服务使用了深度学习技术,识别文本/图片中出现的可能令人反感、不安全或不适宜内容,支持用户配置词库/图片黑名单,识别自定义的识别类型。

安正超 34 Jun 20, 2022
An open source image hosting service powered by Laravel

Limg An open source image hosting service powered by Laravel Features Upload your image via file, url or ShareX ! Manage your image (custom title, pub

Thomas 56 Dec 16, 2022
An easy-to-use PHP QrCode generator with first-party support for Laravel.

An easy-to-use PHP QrCode generator with first-party support for Laravel.

Simple Software LLC 2.2k Jan 5, 2023