Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :
InvestmentNovel

Latest Programming Tutorial Blog

Laravel Image Resize and Upload Tutorial With Example

/
/
/
113 Views

In this example, I will explain to you how to do Laravel Image Resize and Upload Tutorial With Example.  I have used an intervention/image package to resize the image and then save the image into the database. You can manipulate and handle image by using Intervention library which is open source. This library maintains the image quality that means you can easily resize your images without losing quality. In this example, we create a form to submit and on submit we resize an image and move them in destination folder with the original image too. We usually have the use cases like upload an avatar or upload an item image of a specific size on an e-commerce website.

Laravel Image Resize and Upload Tutorial With Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel 5.6 Project by the typing following command.

composer create-project --prefer-dist laravel/laravel imageresizeandupload

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=imageresizeandupload
DB_USERNAME=root
DB_PASSWORD=

#3: Build Model and Migration File

php artisan make:model FileResize -m

It will create the FileResize.php file and also create a create_file_resizes_table.php  migration file.

public function up()
    {
        Schema::create('file_resizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

#4: Install Intervention Image Package

Open your terminal type following command.

composer require intervention/image

Find the providers in config / app.php file and register ImageServiceProvider.

'providers' => [
        // ...
        'Intervention\Image\ImageServiceProvider',
    ]

Locate the aliases in config / app.php file and register aliases.

'aliases' => [
        // ...
        'Image' => 'Intervention\Image\Facades\Image',
    ]

#5: Create a View File

You can create a file in resources/views/resizeimage.blade.php and put this following code in it.

//resizeimage.blade.php

<html lang="en">
<head>
  <title>Laravel Image Resize and Upload Tutorial With Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  
  <div class="container">
    <h2>Laravel Image Resize and Upload Tutorial With Example</h2>
    <form method="post" action="{{url('resizeimage')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
          <input type="file" name="filename" class="form-control">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
          <button type="submit" class="btn btn-success" style="margin-top:10px">Upload Image</button>
          </div>
        </div>     
  </form>
  </div>
</body>
</html>

#6: Create one controller

php artisan make:controller ResizeImageController

It will build the controller file called ResizeImageController.php.

// ResizeImageController.php

  /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
   public function resizeImage()
    {
        return view('resizeimage');
    }

#7: Define Route

We register all route in a web.php file.

Route::get('resizeimage','ResizeImageController@resizeImage');
Route::post('resizeimage','ResizeImageController@resizeImageStore');

Laravel Image Resize and Upload Example

#8: Store data to the database

We need coding the store function in sequence to store the data in the database. We can do it programmatically to create two folders, but let us create manually two folders in the public directory called images and thumbnail.

//ResizeImageController.php

use App\FileResize;
use Image;

public function resizeImageStore(Request $request)
    {
        $originalImage= $request->file('filename');
        $thumbnailImage = Image::make($originalImage);
        $thumbnailPath = public_path().'/thumbnail/';
        $originalPath = public_path().'/images/';
        $thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
        $thumbnailImage->resize(150,150);
        $thumbnailImage->save($thumbnailPath.time().$originalImage->getClientOriginalName()); 

        $resizeimage= new FileResize();
        $resizeimage->filename=time().$originalImage->getClientOriginalName();
        $resizeimage->save();

        return back()->with('success', 'Your images has been successfully Upload');

    }

#9: Create Validation for Image

Add validation in Store function.

//ResizeImageController.php

public function resizeImageStore(Request $request)
    {
        $this->validate($request, [
            'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
         ]);
    }

Next, we pass a resize image to the blade file which we can display resize image.

//ResizeImageController.php

public function resizeImage()
    {
        $resizeimage = FileResize::latest()->first();
        return view('resizeimage', compact('resizeimage'));
    }

Final Code of ResizeImageController looks like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\FileResize;
use Image;

class ResizeImageController extends Controller
{
    public function resizeImage()
    {
        $resizeimage = FileResize::latest()->first();
        return view('resizeimage', compact('resizeimage'));
    }
    public function resizeImageStore(Request $request)
    {
        $this->validate($request, [
            'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
         ]);
        $originalImage= $request->file('filename');
        $thumbnailImage = Image::make($originalImage);
        $thumbnailPath = public_path().'/thumbnail/';
        $originalPath = public_path().'/images/';
        $thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
        $thumbnailImage->resize(150,150);
        $thumbnailImage->save($thumbnailPath.time().$originalImage->getClientOriginalName()); 

        $resizeimage= new FileResize();
        $resizeimage->filename=time().$originalImage->getClientOriginalName();
        $resizeimage->save();

        return back()->with('success', 'Your images has been successfully Upload');

    }
}

#10: Change in View File

We can display resize image in view file so add some code in view file for the display image.

<!-- resize.blade.php -->

@if($resizeimage)
   	    <div class="row">
         <div class="col-md-8">
              <strong>Original Image:</strong>
              <br/>
              <img src="/images/{{$resizeimage->filename}}" />
        </div>
        <div class="col-md-4">
            <strong>Thumbnail Image:</strong>
            <br/>
            <img src="/thumbnail/{{$resizeimage->filename}}"  />
       	 </div>
   		</div>
        @endif

Final Code of View file looks like that.

<!-- resize.blade.php -->

<html lang="en">
<head>
  <title>Laravel Image Resize and Upload Tutorial With Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  
  <div class="container">
    <h2>Laravel Image Resize and Upload Tutorial With Example</h2>
    <form method="post" action="{{url('resizeimage')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
          <input type="file" name="filename" class="form-control">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
          <button type="submit" class="btn btn-success" style="margin-top:10px">Upload Image</button>
          </div>
        </div>
        @if($resizeimage)
   	    <div class="row">
         <div class="col-md-8">
              <strong>Original Image:</strong>
              <br/>
              <img src="/images/{{$resizeimage->filename}}" />
        </div>
        <div class="col-md-4">
            <strong>Thumbnail Image:</strong>
            <br/>
            <img src="/thumbnail/{{$resizeimage->filename}}"  />
       	 </div>
   		</div>
        @endif 
  </form>
  </div>
</body>
</html>

If any validation fail it through error you can see that below screenshot.

Laravel Image Resize and Upload Using Image Intervention Package Example

When image uploaded successfully then you can see below screenshot like an image in your screen.

Laravel Image Resize and Upload Tutorial

You can see the database in below screenshot.

Laravel 5.6 Image Resize and Upload Example

At last, our Laravel Image Resize and Upload Tutorial With Example is over.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This div height required for enabling the sticky sidebar