How To Resize Image In Laravel 10? Image Intervention Guide

Overview

Image intervention project is used to resize any image to a fixed resolution while maintaining the aspect ratio. It is generally used to make images of similar size so that the web page looks good and loads quickly as the more prominent images take time to load. In this post, we’ll learn how to resize image in Laravel(Php) with the help of the Laravel intervention/image package.

Architecture

For this project, I will be using the Laravel PHP framework as it provides a robust set of tools and features for building web applications, including image resizing. Laravel has a built-in image manipulation library called “Intervention Image” that we can use to resize and manipulate images.

To store the images, I will be saving them in the project directory itself but you can use Amazon S3, which is a scalable and secure cloud storage service. Using S3 will allow you to easily store and retrieve images without having to worry about managing your own storage infrastructure.

To handle the user interface, I will be using Bootstrap, a popular front-end framework that provides a set of pre-designed UI components that we can use to build a responsive and user-friendly interface.


Also Read: Creating Perfect Image Copies in Laravel: Resize, Center, and Save to Azure Blob!


Steps To Implement

  • Create a Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel image-resize-project
  • Install the Intervention Image package using Composer:
composer require intervention/image
  • After installation, add the Intervention Image Service Provider to your config/app.php file:
'providers' => [
    // ...
    Intervention\Image\ImageServiceProvider::class,
],

  • Add the Intervention Image facade to the aliases array in config/app.php:
'aliases' => [
    // ...
    'Image' => Intervention\Image\Facades\Image::class,
],

  • Create a controller to handle the Resize image logic using the following command:
php artisan make:controller ResizeController
  • Create a folder inside public directory named as thumbnail(in this folder we’re going to save the resized image)
  • In the ResizeController class, create 2 methods index() and resizeImage() to load the upload image form and to resize & save the image respectively:
    public function index()
    {
        return view('resize-image');
    }

    public function resizeImage(Request $request)
    {
        // Get the uploaded image from the request
        $image = $request->file('image');

        // Validate the image for acceptable image formats and max upload size(Max upto 5MB)
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:5120',
        ]);

        // Generate a unique filename for the uploaded image
        $input['image'] = time().'.'.$image->getClientOriginalExtension();
        
        // Set the path to save the resized image
        $thumbnailPath = public_path('/thumbnail');
        
        // Use the Intervention Image package to resize the image and save it to the desired directory
        $imgFile->resize(240, 240, function ($constraint) {
            $constraint->aspectRatio();
        })->save($thumbnailPath.'/'.$input['image']);

        //Send the user back to the upload page with success message and image URL in session
        return back()
            ->with('success','Image has successfully uploaded.')
            ->with('imageName',url('thumbnail/'.$input['image']));
    }

Let’s break down each part of the resizeImage() function:

  1. The resizeImage() function takes a Request object as its argument. This object contains the uploaded image that we want to resize.
  2. We get the uploaded image from the request using the file() method.
  3. We generate a unique filename for the uploaded image using the current timestamp and the original file extension.
  4. We set the path where we want to save the resized image. In this case, we save it to the public/images directory.
  5. We use the Intervention Image package to resize the image. We first create an Intervention\Image\Image object by passing the uploaded image’s path to the make() method. We then call the resize() method on the Image object and specify the desired width and height. We also use the aspectRatio() method to maintain the aspect ratio of the image. Finally, we save the resized image to the path we specified.
  6. If the image is resized successfully, we return a success message to the user.

Also Read: How To Setup Real-Time Synchronization with Laravel 11, Pusher, & Angular 18?


  • Create resize-image.blade.php file inside resources->views. Create a form to upload the image:
<div class="container mt-5" style="max-width: 550px">
    <h2 class="mb-5">Image Resize Demo</h2>
    <form action="{{route('resizeImage')}}" method="post" enctype="multipart/form-data">
        @csrf
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>

            <div class="col-md-12 mb-3">
                <strong>Resized Thumbnail Image:</strong><br/>
                <img src="{{ Session::get('imageName') }}" width="240px" />
            </div>
        @endif

        <div class="form-group row">
            <div class="col-md-12 mb-3">
                <div id="imageprev" class="mt-3"></div>
            </div>
        </div>
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <div class="custom-file">
            <input type="file" name="image" class="custom-file-input" id="chooseFile">
            <label class="custom-file-label" for="chooseFile">Select Image</label>
        </div>
        <button type="submit" name="submit" class="btn btn-outline-danger btn-block mt-4">
            Upload
        </button>
    </form>
</div>
  • Add the following routes in routes/web.php:
// Show image upload form
Route::get('/image-resize', [ResizeController::class, 'index']);
// Resize and save image in folder
Route::post('/resize', [ResizeController::class, 'resizeImage'])->name('resizeImage');
  • Run the project using the following command:
php artisan serve

This implementation will allow us to generate a newly resized image and store it in the thumbnail folder.


Also Read: How To Validate Location From IP & Zipcode Using Laravel 10?


Assumptions

  • For this project, I am assuming that the images being uploaded are not too large for the server to handle, and that we are only concerned with resizing images that are within a reasonable size range. If we need to resize very large images, we may need to consider using a distributed image processing system such as Apache Spark or Apache Flink.
  • The target server is running PHP 7.4 or higher.

Also Read: How to resolve Docker Setup Issues?


Deployment

Assuming you have a server with PHP and a web server (such as Apache or Nginx) installed, you can deploy the Image resizing project using the following steps:

  1. Copy the contents of the image-resizing directory to your server.
  2. Configure your web server to serve the contents of the public directory as the document root.
  3. Set the necessary environment variables on the server.


FAQs

Slow website due to large images? Fix it with Laravel image resizing!

Struggling with sluggish website loading times caused by bulky images? This guide unveils a quick and efficient Laravel solution for resizing images, optimizing your website speed and user experience.

Resize images on upload in Laravel – is it possible?

Yes, absolutely! This guide walks you through a step-by-step process to implement automatic image resizing during the upload process in your Laravel project.

Free image resizing tools available? Why use Laravel?

While free online image resizing tools exist, integrating resizing directly within your Laravel application offers several advantages:
Automation: Resize images automatically during upload, saving you time and effort.
Security: Maintain control over your image data within your Laravel environment.
Customization: Tailor image resizing parameters to your specific project needs.

Does image resizing affect image quality in Laravel?

Yes, image resizing can reduce quality, but with the right techniques, the impact is minimal. This guide explores various resizing methods in Laravel to achieve optimal compression with minimal quality loss.

Can I resize multiple images at once in my Laravel project?

Absolutely! The techniques outlined in this guide can be easily adapted to handle batch image resizing, saving you time when dealing with large numbers of images.

What file formats can be resized using this Laravel method?

This method supports popular image formats like JPEG, PNG, and GIF. You can potentially expand compatibility with additional formats through third-party Laravel packages.

Where are the resized images stored after processing in Laravel?

You have control over the storage location for resized images. This guide demonstrates saving them within your Laravel project directory or leveraging cloud storage solutions.

Is there a way to integrate this image resizing functionality into my existing Laravel project?

Yes! The concepts explained here can be seamlessly integrated into your current Laravel project. The guide provides clear instructions for implementation.

Looking to resize images on the client-side (user’s browser) instead of Laravel?

While this guide focuses on server-side resizing using Laravel, there are also JavaScript libraries that enable client-side image resizing for a potentially smoother user experience.

What if I need more advanced image manipulation functionalities beyond resizing in Laravel?

Laravel’s Intervention Image package offers a wide range of features beyond resizing. You can explore functionalities like cropping, watermarking, and more for comprehensive image manipulation.



TODO Next

  • Resize the image to Medium size i.e. 1024px width and use this image to further resize it to thumbnail size i.e. 240px

How to Create Hashed URL? Laravel 10 Short URL Generator

Overview

In this Laravel short URL generator project we will learn, What is URL hashing? How it is used to create unique identifiers for web pages? We will also learn how we can track the number of clicks hit on a particular hashed URL.


What is URL hashing?

Hashing is a technique that involves taking a string of characters and using a cryptographic hash algorithm to create a unique numerical representation for the string. This numerical representation can then be used as a unique identifier for any webpage(particular reason) and can be used to access the webpage.


Architecture

I am implementing this URL hashing system as a REST API using the PHP Laravel framework. Laravel provides a great deal of built-in functionality for handling HTTP requests, routing, and database interactions, which will make it easier to build this application.

The core of the URL hashing system will be a hash function that takes an input URL and generates a unique, shortened hash. This hash will be stored in a database along with the original URL. When a request is made for the hashed URL, the application will look up the original URL in the database and redirect the user to it.

In order to track clicks, I will store the number of clicks for each hashed URL in the database and increment it every time the URL is accessed. I will also store the date the URL was created and when it was last clicked(accessed).


Steps To Implement

  • Create a Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel url-hashing-system
  • Create a URL model with migration using the following command:
php artisan make:model Url -m
  • In the Url model migration, add the following fields:
    • original_url: text field to store the original URL
    • hash: string field to store the hashed URL
    • clicks: integer field to store the number of clicks on the URL
  • Create a controller to handle the URL hashing logic using the following command:
php artisan make:controller UrlController
  • In the UrlController class, create a method to generate a hash for the URL and save it to the database:
public function generateHash(Request $request)
    {
        try {
            $originalUrl = $request->input('url');
            
            // Validating the URL
            $request->validate([
                'url' => 'required|url',
            ]);
            
            // Creating Hash value of URL and stripping it upto 6 characters only
            $hash = substr(hash('sha256', $originalUrl),0,6);

            $url = Url::firstOrNew(
                ['original_url' => $originalUrl],
                ['hash' => $hash]
            );
            
            // Save the URL with its Hash Value
            $url->save();

            if ($url->id) {
                return response()->json([
                    'hash' => url($hash)
                ], 201);
            } else {
                return response()->json([
                    'message' => 'Something goes wrong. Please try after sometime.'
                ], 500);
            }

        } catch (ValidationException $e) {
            // Throwing Error in case of URL is empty or not valid
            return response()->json([
                'error' => $e->getMessage(),
            ], 400);
        }
    }
  • Create a method in the controller to redirect the user to the original URL when the hashed URL is clicked:
public function redirect($hash)
    {
        // Get the Original URL on the basis of Hash.
        $url = Url::where('hash', $hash)->first();

        if (!$url) {
            return response()->json([
                'error' => 'URL not found'
            ], 404);
        }
        
        // Increase click counter By 1
        $url->update([
            'clicks' => $url->clicks + 1
        ]);
        
        // Redirect to original URL
        return redirect($url->original_url);
    }
  • Add the following routes in routes/web.php:
// Generating Hash
Route::post('/generate-hash', 'UrlController@generateHash');
// Redirection
Route::get('/{hash}', 'UrlController@redirect');
  • Run the migration using the following command:
php artisan migrate

This implementation will allow us to generate a hash for any URL and store it in the database. The hash can be used as a shortened URL that can be shared and clicked, which will redirect the user to the original URL and track the number of clicks. This implementation can also be extended to make the URLs single use only by adding a flag in the database to track if a URL has already been used.


Also Read: Setting Up and Configuring Supervisor for Process Management on AWS EC2 Ubuntu


Setups To Clone the Up and Running Project

  1. Clone the repository to your local machine
git clone https://github.com/prashant12it/url-hashing-system.git
  1. Change into the newly created directory
cd url-hashing-system
  1. Install dependencies
composer install
  1. Copy the example environment file and configure your database settings
cp .env.example .env
  1. Generate an application key
php artisan key:generate
  1. Run database migrations
php artisan migrate
  1. Start the development server
php artisan serve

Also Read: Learn How to Use the Slack API to Post Messages in Slack Channel Using Laravel


Assumptions

  • The input URL does not contain any malicious characters that would break the hash function.
  • The target server is running PHP 7.4 or higher.

API Endpoints

The following endpoints will be available for the URL hashing system:

1. Hash a URL

POST /generate-hash

Request Body

{ 
  "url": "https://www.newsatic.com/news/proposed-changes-in-new-tax-regime/"
}

Response

{ "hash": "http://127.0.0.1:8000/809efd" }

2. Redirect to Original URL

GET /{hashed_url}

Response

Redirects to the original URL associated with the given hashed_url.

3. Get Click Data

GET /get-click-report/{hash}

Response

  {
    "original_url": "https://www.newsatic.com/news/proposed-changes-in-new-tax-regime/",
    "hash_url": "http://127.0.0.1:8000/809efd",
    "total_clicks": 2,
    "last_clicked": "2023-02-03 11:27:32"
  }

Also Read: Sending messages to Microsoft Teams Channel by using Laravel


Deployment

Assuming you have a server with PHP and a web server (such as Apache or Nginx) installed, you can deploy the URL hashing system using the following steps:

  1. Copy the contents of the url-hashing-system directory to your server.
  2. Configure your web server to serve the contents of the public directory as the document root.
  3. Set the necessary environment variables, such as the database connection settings, on the server.
  4. Run the necessary database migrations.

Also Read: Laravel Image Resize Project in 10 Minutes: A Step By Step Guide


FAQs

Is there a difference between URL shortening and Hashed URLs?

Absolutely! While both shorten URLs, Hashed URLs offer additional benefits. Traditional URL shorteners generate random strings, making them unreadable and uninformative. Hashed URLs, on the other hand, create unique codes based on the original URL, maintaining some level of meaning and boosting click-through rates (CTR).

What are the benefits of using Hashed URLs over traditional Long URLs?

Long URLs can be clunky and unprofessional. Hashed URLs offer several advantages:
👉 Increased Aesthetics: Short, clean Hashed URLs enhance the visual appeal of your project.
👉 Improved Click Tracking: Track clicks more effectively with Hashed URLs compared to generic shortened links.
👉 Potential SEO Benefits: Concise URLs might be viewed more favorably by search engines (ongoing research).
👉 Enhanced Brand Recall: Shorter, memorable Hashed URLs can improve brand recognition.

Can I track clicks on Hashed URLs?

Yes! With the implementation explained in this guide, you can track clicks on your Hashed URLs. The system stores the original URL and tracks redirects, providing valuable click data.

How secure are Hashed URLs?

Hashed URLs themselves don’t inherently store sensitive information. While the hash reveals some information about the original URL length, it doesn’t expose the actual content. However, for maximum security, ensure the underlying system storing the original URL is secure.

Does this method work with other frameworks besides Laravel?

The core concept of Hashed URLs can be adapted to other frameworks. However, the specific implementation steps might vary depending on the framework’s functionalities.

What if I want to customize the Hashed URL format?

There might be limited customization options within Laravel’s base functionalities. However, exploring advanced Laravel features or third-party packages could provide more control over the Hashed URL format.

Are there any limitations to using Hashed URLs?

While beneficial, Hashed URLs have some limitations:
👉 Reduced Readability: Compared to the original URL, Hashed URLs might be less informative at first glance.
👉 Potential Confusion: Users unfamiliar with Hashed URLs might be hesitant to click.

How can I implement Hashed URLs in my project?

This guide provides a comprehensive step-by-step process for implementing Hashed URLs using Laravel. Follow the instructions and code examples to integrate this functionality into your project.



TODO Next

  • Store hashed URLs and their metadata in a separate database table with appropriate access controls to make the generated URLs privacy-aware
  • Add tests for URL hashing functionality
  • Add authentication for accessing click tracking data
  • Implement expiration for hashed URLs
  • Implement UI for generating hashed URLs
  • Validate input URL for malicious characters that would break the hash function


Conclusion

This post has explored the concept of Hashed URLs and provided a step-by-step guide on implementing them using Laravel. Hashed URLs offer several advantages over traditional long URLs, including improved aesthetics, better click tracking and potential security benefits. If you’re looking for a way to enhance your Laravel project’s functionality and user experience, then implementing Hashed URLs is a great option to consider.

Want to see more of my projects?

Check out my portfolio for a wider range of my web development work: Prashant Web Developer

How to Save Money on Website Development Without Sacrificing Quality?

Introduction

Any business, regardless of size, needs a website. However, creating a website from the ground up may be expensive, particularly for small business owners. Thankfully, there are ways to reduce expenses without compromising the calibre of your website. In this article, we’ll provide you some advice on how to design websites on a budget without losing quality.

Set Specific Website Goals

It’s crucial to establish your goals before you begin developing your website. This will assist you in choosing the features and website design you require. Do you require a straightforward website to notify people about your company, or one that is more complicated and includes both an online store and a blog? You may build a roadmap for your website’s development and prevent expensive adjustments in the future by clearly outlining your aims.

Use a Website Builder

website development 2
low-cost Website Development

Using a website builder is one of the most economical ways to create a website. Without having any technical experience, you can design a website using website builders, which are online platforms. They include pre-designed templates, drag-and-drop capability, and a number of other features that make it simple to build a website that looks professional. They are also far less expensive than employing a web developer to create a website from scratch.

Also Read: Future of Website Development: 10 Cutting-Edge Trends That Will Rule 2023

Select a reasonably priced web hosting company.

The price and the features a web hosting company offers should be taken into account when making your decision. There are numerous reasonably priced web hosting companies that provide essential functionality for small enterprises. However, you could have to pay extra if you require more sophisticated capabilities, like limitless bandwidth or a dedicated server. Make sure to compare your options before selecting a web hosting company, then pick the one that best suits your requirements at a price you can afford.

Use Free Resources

You can save money on website building by using the many free resources that are readily available online. For instance, you can save money by using free stock images on your website rather than hiring a photographer. To improve the appearance and feel of your website, you can also use free icons, fonts, and layouts. Before using any free resources, just make sure to read the licence agreements because some can have limitations.

Also Read: Maximizing User Experience in Website Development: A Comprehensive Guide

Consider DIY Design

You can think about conducting the design work yourself if you have some design expertise. This will enable you to avoid spending money on a professional designer and give you more control over the appearance and feel of your website. However, bear in mind that more than simply solid design abilities are needed for a website to appear professional. Additionally, you’ll need to be well-versed in website design, navigation, and user experience.

Hire a Freelance Web Developer

hire freelance website developer 1
Hire Affordable Freelance Website Developer

Consider hiring a freelance web developer if you need a more complex website but don’t want to spend a lot of money on one. You may get a high-quality website from independent web developers for less money than you would pay a web development company. Additionally, since you and the developer will be in closer contact, your website will be more likely to fulfil your demands and objectives.

Frequently Asked Questions

What is the most cost-effective way to build a website?

Using a website builder is the most economical approach to create a website. Without having any programming experience, you may make a website using website builders, which are significantly less expensive than paying a web developer to build one from the ground up.

What should I consider when choosing a web hosting provider?

The price and the features a web hosting company offers should be taken into account when making your decision. Select a cheap web host that delivers the capabilities you need and can accommodate

Can I use free resources for my website?

Yes, you can save money on website development by using the many free online resources that are available, such as free stock images, icons, fonts, and themes. Before using any free resources, though, make sure to read the licence agreements as some can have limitations.

Is it possible for me to design my own website?

You can think about conducting the design work yourself if you have some design expertise. This will enable you to avoid spending money on a professional designer and give you more control over the appearance and feel of your website. However, bear in mind that more than simply solid design abilities are needed for a website to appear professional.

Should I work with an independent web developer?

Consider hiring a freelance web developer if you need a more complex website but don’t want to spend a lot of money on one. You may get a high-quality website from independent web developers for less money than you would pay a web development company.

Conclusion

Finally, there are a number of strategies to reduce the cost of website construction without compromising quality. You may establish a professional-looking website for your company at a reasonable price by defining your website goals, using a website builder, selecting a cheap web hosting provider, utilising free resources, contemplating DIY design, or engaging a freelance web developer. When creating your website, keep in mind that quality and functionality should always take precedence over price because a well-designed website will help you expand your company and improve your internet presence.