Vaidikalaya

Image converter in Laravel


To create an image converter in Laravel, you can follow these steps. This guide will cover setting up a Laravel project, installing necessary packages, and creating a simple image converter that can handle various formats.

In this tutorial, we will use the intervention/image-laravel package.

Intervention Image is the most popular open-source PHP image processing library. It provides an easy and expressive way to edit images and supports PHP's two most common image-processing libraries GD Library and Imagick.


Requirements

To create an image converter in Laravel, your system must install either the GD or Imagick library. GD is included in most PHP installations. However, I recommend using Imagick because it is faster and more efficient, especially for processing larger images. Additionally, Imagick supports all image formats.

If Imagick is not installed on your system, you must install it first.

After installing Imagick, follow the steps below to create a converter.


Step 1: Create a Laravel Project

First, create a new Laravel project.

composer create-project laravel/laravel image-converter

Step 2: Install Intervention Image Package

Next, you need to install the Intervention Image package to help you with image manipulation.

Instead of installing the Intervention Image directly, it is only necessary to integrate the intervention/image-laravel package. The corresponding base libraries are automatically installed as well.

composer require intervention/image-laravel

Step 3: Create a Controller

You need to create a controller to handle the logic for converting images. Use the artisan command to generate a controller:

php artisan make:controller ImageConverterController

This command will create a new controller file at app/Http/Controllers/ImageConverterController.php.


Step 4: Implement the Conversion Logic

There are many ways to convert images. So here we have different methods to help you with various scenarios.

Now, open the newly created controller file and add a method that fits your scenario to handle the image conversion:

Method 1: Upload a single image then convert and download.

In this scenario, we upload a single image, convert it to a selected format, and then download it.

First import all the necessary drivers. 

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;
use Intervention\Image\Encoders\AutoEncoder;

class ImageConverterController extends Controller
{
    public function index(Request $request){

        $image=$request->image;
        $format=$request->format;
        $imageName=pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);

        $manager = new ImageManager(Driver::class);
        $readFile = $manager->read($image);
        $convertedImage = $readFile->encodeByExtension($format);

        $headers = [
            'Content-Type' => 'image/'.$format,
            'Content-Disposition' => 'attachment; filename='.$imageName.'.'. $format,
        ];

        return response($convertedImage, 200, $headers);

    }
}

Method 2: Upload multiple images and then convert and download.

In this scenario, we upload multiple images, read them, convert them, and download them in a zip file.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;
use Intervention\Image\Encoders\AutoEncoder;
use Illuminate\Support\Facades\Storage;
use ZipArchive;

class ImageConverterController extends Controller
{
    public function index(Request $request){
       
        $manager = new ImageManager(Driver::class);

        /* save images and format in variables */
        $images=$request->images;
        $format=$request->format;

        /* make temporary directory where we storage converted images */
        $tempDir = 'converted_images_' . uniqid();
        Storage::makeDirectory($tempDir);

        /*
            read all images one by one and convert to selected format and
            save in temporary directory
        */
        foreach($images as $image){
            $imageName=pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
            $readImage = $manager->read($image);
            $convertedImage = $readImage->encodeByExtension($format);
            Storage::put($tempDir.'/'.$imageName.'.'.$format, $convertedImage);
        }

        $zip = new ZipArchive;
        $zipPath = storage_path('app/' . $tempDir . '.zip');

        if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
           
            $files = Storage::files($tempDir);
            foreach ($files as $file) {
                $zip->addFile(storage_path('app/' . $file), basename($file));
            }
            $zip->close();

            // Delete temporary directory
            Storage::deleteDirectory($tempDir);

            //Return the zip file as a download response
            return response()->download($zipPath, 'converted_images.zip')->deleteFileAfterSend(true);
        }
    }
}

Step 5: Create a view file

Create a simple view file to upload images and select the desired format. Create a new file at resources/views/welcome.blade.php if this file already exists then edit it.

resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Image Extension Converter</title>
   
   
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

    <div class="container">
        <div class="card mt-5">
            <div class="card-header">Upload Images</div>
            <div class="card-body">
                <form action="{{route('image-converter')}}" method="post" enctype="multipart/form-data">
                    @csrf
                    <div class="mb-3">
                        <label class="form-label">Images</label>

                        <!--For Multiple images upload-->
                        <input type="file" name="images[]" multiple class="form-control">
                       
                        <!--For Single image upload--> <!-- <input type="file" name="image" class="form-control"> -->
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Format (Convert to)</label>
                        <select name="format" class="form-select">
                            <option value="png">PNG</option>
                            <option value="jpg">JPG</option>
                            <option value="jpeg">JPEG</option>
                            <option value="gif">GIF</option>
                        </select>
                    div>
                    <div class="mb-3">
                        <button class="btn btn-primary mt-2">Convert</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
</html>



Step 6: Define a Route

Now you need to define a route to handle requests to your image converter. Open routes/web.php and add:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageConverterController;

Route::get('/', function () {
    return view('welcome');
});
Route::post('/convert-images',[ImageConverterController::class,'index'])->name('image-converter');

Step 7: Testing

Serve your Laravel application using the artisan command:

php artisan serve

Visit http://localhost:8000 in your browser. You should see the form to upload an image and select the format. When you submit the form, the image will be converted to the chosen format and downloaded to your computer.

See Screenshots

Single Image



Multiple Images


Download Project From Gitub:
Link: 
Laravel Image Converter