...

Evolutionizing Image Manipulation: Unleashing the Power of Intervention Image in PHP

Introducing Intervention Image, a game-changing open-source PHP library designed to streamline image handling and manipulation. Say goodbye to cumbersome processes and hello to a world of effortless image editing.

How to install image intervention package in Laravel ?

"intervention/image": "^2.7",


Image intervation  package steps:
* Image intervention package link 
* 1st step
-----------------------------------------
composer require intervention/image
-----------------------------------------
* open config app.php file open  scroll page in package serveice provider area

* 2nd step
-----------------------------------------
Intervention\Image\ImageServiceProvider::class,
-----------------------------------------

* Add the facade of this package to the $aliases array.

* 3rd step
-----------------------------------------
'Image' => Intervention\Image\Facades\Image::class
-----------------------------------------
* then Save & publish image intervation in project

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

Image Upload Helper:

<?php

namespace App\Http\Traits;

use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Image;
// use Intervention\Image\Facades\Image;

use Tinify\Tinify;

trait ImageUploadTrait
{

    public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public')
    {
        // Generate a unique name for the image
        $currentMonth = date('m');
        $currentYear = date('Y');
        $filetype   =  $uploadedFile->getMimeType();
        $file_name =   $currentMonth  . '_' . $currentYear . '_' . strtoupper(uniqid()) . '.' . $uploadedFile->getClientOriginalExtension();
        $new_file_name =   $currentMonth  . '_' . $currentYear . '_' . strtoupper(uniqid()) . '.' . 'webp';

        try {
            // Set the API key
            // $apiKey = config('services.tinify.key');
            // Set the API key config('services.tinify.key')
            $apiKey = '';
            $originalSize =0;
            $compressedSize =0;
             // Check if Tinify API key is valid
            if ($apiKey ) {
                Tinify::setKey($apiKey);
                 \Tinify\validate();
                  // Get original image size
                $originalSize = filesize($uploadedFile->path());
                // Compress the image
                $filePath =  Storage::path('public/' . $folder . '/' . $file_name);
                $source = \Tinify\fromFile($uploadedFile->path());
                // $copyrighted = $source->preserve("copyright", "creation");
                $source->toFile($filePath);
                $compressedSize = filesize($filePath);
                $file_size =   'Image compressed successfully! Original size: ' . number_format($originalSize, 0, '.', ',') . ' bytes, Compressed size: ' . number_format($compressedSize, 0, '.', ',') . ' bytes';
                Log::info($file_size);
            }
            else {
                  // If Tinify API key is not provided or invalid, save the image without compression
                $file_size =   'Tinify API key is not provided or invalid';
                Log::info($file_size);
                // $uploadedFile->storeAs($folder, $file_name, $disk);
                $image = Image::make($uploadedFile)->orientate()->encode('webp');
                $filePath = $folder ? $folder . '/' . $new_file_name : $new_file_name;
                Storage::disk($disk)->put($filePath, $image->stream());
            }
        } catch (\Exception $e) {
              // Log compression errors
              Log::error('Tinify Error: ' . $e->getMessage());
        }

        $filePathOnly = $folder;
        // Get the path where you want to save the image and thumbnail
        $directory = storage_path('app/public/' . $folder);
        // Check if the directory exists, if not, create it
        if (!File::exists($directory)) {
            File::makeDirectory($directory, 0755, true, true);
        }
        $image = Image::make($uploadedFile);
         $image->orientate();
        Log::info('Original Image width & height: ' . $image->width() . 'x' . $image->height());
       $thumbnail = Image::make($uploadedFile)->fit(100, 75)
            ->blur(10)->orientate()->encode('webp');
        // ======== Text on image =======
        $thumbnail->text('Thumbnail Image', $thumbnail->width() / 2, $thumbnail->height() / 2, function ($font) {
            $font->file(public_path('font/font.ttf'));
            // $font->color([255, 0, 0]); // Red color
            $font->color([255, 255, 255, 0.5]);
            $font->size(12);
            $font->align('center'); // Align text to center
            $font->valign('middle'); // Vertically align text to the middle
            $font->angle(33); // Angle of text (33 degrees)
        });
        // ======== Text on image =======
        Log::info('Resized Image  width & height: ' . $thumbnail->width() . 'x' . $thumbnail->height());
        $thumbnailName = 'thumb_' . $new_file_name;
        $thumbnail->save($directory . '/' . $thumbnailName);
        return [
            'file_name' => $new_file_name,
            'thumbnail_name' => $thumbnailName,
            'filepath' => $filePathOnly, // This will contain the path relative to the storage disk
            'filetype' => $filetype,
            'originalSize' => number_format($originalSize, 0, '.', ',') ,
            'compressSize' => number_format($compressedSize, 0, '.', ',')

            

        ];
    }

    public function deleteImage($filename, $folder = null, $disk = 'public')
    {
        // Delete the original image
        $filePath = $folder ? $folder . '/' . $filename : $filename;
        Storage::disk($disk)->delete($filePath);

        // Delete the thumbnail
        $thumbnailName = 'thumb_' . $filename;
        $thumbnailPath = 'uploads/thumbnail/' . $thumbnailName;
        if (File::exists(public_path($thumbnailPath))) {
            File::delete(public_path($thumbnailPath));
        }
    }
    // Now, if you want to delete the image and its thumbnail:
    // $this->deleteImage($imageInfo['file_name'], $imageInfo['filepath'], $disk);

    public function unlinkBlogImage($model, $imageField = 'image', $thumbnailField = 'thumbnail', $folder)
    
    {
        $imagePath = Storage::path('public/' . $folder . '/' . $model->$imageField);
        if (File::exists($imagePath) && isset($model->$imageField)) {
            unlink($imagePath);
            Log::info('main  Image Deleted');
        }

        $thumbnailpath = Storage::path('public/' . $folder . '/' . $model->$thumbnailField);
        if (File::exists($thumbnailpath) && isset($model->$thumbnailField)) {
            unlink($thumbnailpath);
            Log::info('thumbnail Image Deleted');
        }
    }

    public function unlinkImage($model, $imageField = 'image', $folder)
    
    {
        $imagePath = Storage::path('public/' . $folder . '/' . $model->$imageField);
        if (File::exists($imagePath) && isset($model->$imageField)) {
            unlink($imagePath);
            Log::info('Page  Image Deleted');
        }
        $thumbnailpath = Storage::path('public/' . $folder . '/' . 'thumb_'.$model->$imageField);
        if (File::exists($thumbnailpath) && isset($model->$imageField)) {
            unlink($thumbnailpath);
            Log::info('thumbnail Image Deleted');
        }
    
    }
    // in livewire method area can use below method 
    // $model = BlogPost::find($this->blog_id );
    // $folder = '/blogimages';
    // $this->unlinkBlogImage($model, 'image', 'thumbnail' ,$folder);

    public function myAlert($notification)
    {
        $this->dispatch('showToastMesssage', $notification);
    }

    public function myConfirm($title, $message, $event)
    {

        $this->dispatch(
            'swal:confirm',
            icon: "warning",
            text: "{$title}",
            message: "{$message}",
            confirmEvent: "{$event}",
            successMessage: 'Record deleted successfully !',
        );
    }

    
    public function convertToWebP($imagePath, $outputPath)
    {

        try {
            // Open the image using Intervention Image
            $image = Image::make($imagePath);
            // Convert the image to WebP format and remove EXIF data
            $image->orientate()->encode('webp', 75);
            // Save the converted image
            Storage::put($outputPath, $image->stream());
            // Unlink (delete) the original image file
            unlink($imagePath);
            return $outputPath;
        } catch (\Exception $e) {
            // Handle any exceptions
            Log::error('Image conversion error: ' . $e->getMessage());
            return null;
        }
    }
}

in image internvation 3

use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;

// create image manager with desired driver
$manager = new ImageManager(new Driver());


public function StoreCategory(Request $request){

    if ($request->file('image')) {
        $manager = new ImageManager(new Driver());
        $name_gen = hexdec(uniqid()) . '.' . $request->file('image')->getClientOriginalExtension();
        $img = $manager->read($request->file('image'));
        $img = $img->resize(370, 246);

        $img->toJpeg(80)->save(base_path('public/upload/category/' . $name_gen));
        $imageUrl ='upload/category/' . $name_gen

    }}

William Anderson

I am a versatile Full-Stack Web Developer with a strong focus on Laravel, Livewire, Vue.js, and Tailwind CSS. With extensive experience in backend development, I specialize in building scalable, efficient, and high-performance web applications.