PHP library to resize, scale and crop images.

Overview

php-image-resize

PHP library to resize, scale and crop images.

Build Status Latest Stable Version Monthly Downloads Coverage Status

Cloud Solution

If you don't want to crop, resize and store images on your server, Gumlet.com is a free service which can process images in real-time and serve worldwide through CDN.


Setup

This package is available through Packagist with the vendor and package identifier the same as this repo.

If using Composer, in your composer.json file add:

{
    "require": {
        "gumlet/php-image-resize": "1.9.*"
    }
}

If you are still using PHP 5.3, please install version 1.7.0 and if you are using PHP 5.4, please install version 1.8.0 of this library.

WebP support is added with PHP 5.6.0 and current version of library supports that. If you are facing issues, please use 1.9.2 version of this library.

Otherwise:

include '/path/to/ImageResize.php';

Because this class uses namespacing, when instantiating the object, you need to either use the fully qualified namespace:

$image = new \Gumlet\ImageResize();

Or alias it:

use \Gumlet\ImageResize;

$image = new ImageResize();

Note: This library uses GD class which do not support resizing animated gif files


Resize

To scale an image, in this case to half it's size (scaling is percentage based):

$image = new ImageResize('image.jpg');
$image->scale(50);
$image->save('image2.jpg')

To resize an image according to one dimension (keeping aspect ratio):

$image = new ImageResize('image.jpg');
$image->resizeToHeight(500);
$image->save('image2.jpg');

$image = new ImageResize('image.jpg');
$image->resizeToWidth(300);
$image->save('image2.jpg');

To resize an image according to a given measure regardingless its orientation (keeping aspect ratio):

$image = new ImageResize('image.jpg');
$image->resizeToLongSide(500);
$image->save('image2.jpg');

$image = new ImageResize('image.jpg');
$image->resizeToShortSide(300);
$image->save('image2.jpg');

To resize an image to best fit a given set of dimensions (keeping aspet ratio):

$image = new ImageResize('image.jpg');
$image->resizeToBestFit(500, 300);
$image->save('image2.jpg');

All resize functions have $allow_enlarge option which is set to false by default. You can enable by passing true to any resize function:

$image = new ImageResize('image.jpg');
$image->resize(500, 300, $allow_enlarge = True);
$image->save('image2.jpg');

If you are happy to handle aspect ratios yourself, you can resize directly:

$image = new ImageResize('image.jpg');
$image->resize(800, 600);
$image->save('image2.jpg');

This will cause your image to skew if you do not use the same width/height ratio as the source image.

Crop

To to crop an image:

$image = new ImageResize('image.jpg');
$image->crop(200, 200);
$image->save('image2.jpg');

This will scale the image to as close as it can to the passed dimensions, and then crop and center the rest.

In the case of the example above, an image of 400px × 600px will be resized down to 200px × 300px, and then 50px will be taken off the top and bottom, leaving you with 200px × 200px.

Crop modes:

Few crop mode options are available in order for you to choose how you want to handle the eventual exceeding width or height after resizing down your image. The default crop mode used is the CROPCENTER. As a result those pieces of code are equivalent:

$image = new ImageResize('image.jpg');
$image->crop(200, 200);
$image->save('image2.jpg');
$image = new ImageResize('image.jpg');
$image->crop(200, 200, true, ImageResize::CROPCENTER);
$image->save('image2.jpg');

In the case you have an image of 400px × 600px and you want to crop it to 200px × 200px the image will be resized down to 200px × 300px, then you can indicate how you want to handle those 100px exceeding passing the value of the crop mode you want to use.

For instance passing the crop mode CROPTOP will result as 100px taken off the bottom leaving you with 200px × 200px.

$image = new ImageResize('image.jpg');
$image->crop(200, 200, true, ImageResize::CROPTOP);
$image->save('image2.jpg');

On the contrary passing the crop mode CROPBOTTOM will result as 100px taken off the top leaving you with 200px × 200px.

$image = new ImageResize('image.jpg');
$image->crop(200, 200, true, ImageResize::CROPBOTTOM);
$image->save('image2.jpg');

Freecrop:

There is also a way to define custom crop position. You can define $x and $y in freecrop method:

$image = new ImageResize('image.jpg');
$image->freecrop(200, 200, $x =  20, $y = 20);
$image->save('image2.jpg');

Loading and saving images from string

To load an image from a string:

$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->scale(50);
$image->save('image.jpg');

You can also return the result as a string:

$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->scale(50);
echo $image->getImageAsString();

Magic __toString() is also supported:

$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->resize(10, 10);
echo (string)$image;

Displaying

As seen above, you can call $image->save('image.jpg');

To render the image directly into the browser, you can call $image->output();

Image Types

When saving to disk or outputting into the browser, the script assumes the same output type as input.

If you would like to save/output in a different image type, you need to pass a (supported) PHP IMAGETYPE_* constant:

  • IMAGETYPE_GIF
  • IMAGETYPE_JPEG
  • IMAGETYPE_PNG

This allows you to save in a different type to the source:

$image = new ImageResize('image.jpg');
$image->resize(800, 600);
$image->save('image.png', IMAGETYPE_PNG);

Quality

The properties $quality_jpg and $quality_png are available for you to configure:

$image = new ImageResize('image.jpg');
$image->quality_jpg = 100;
$image->resize(800, 600);
$image->save('image2.jpg');

By default they are set to 85 and 6 respectively. See the manual entries for imagejpeg() and imagepng() for more info.

You can also pass the quality directly to the save(), output() and getImageAsString() methods:

$image = new ImageResize('image.jpg');
$image->crop(200, 200);
$image->save('image2.jpg', null, 100);

$image = new ImageResize('image.jpg');
$image->resizeToWidth(300);
$image->output(IMAGETYPE_PNG, 4);

$image = new ImageResize('image.jpg');
$image->scale(50);
$result = $image->getImageAsString(IMAGETYPE_PNG, 4);

We're passing null for the image type in the example above to skip over it and provide the quality. In this case, the image type is assumed to be the same as the input.

Interlacing

By default, image interlacing is turned on. It can be disabled by setting $interlace to 0:

$image = new ImageResize('image.jpg');
$image->scale(50);
$image->interlace = 0;
$image->save('image2.jpg');

Chaining

When performing operations, the original image is retained, so that you can chain operations without excessive destruction.

This is useful for creating multiple sizes:

$image = new ImageResize('image.jpg');
$image
    ->scale(50)
    ->save('image2.jpg')

    ->resizeToWidth(300)
    ->save('image3.jpg')

    ->crop(100, 100)
    ->save('image4.jpg')
;

Exceptions

ImageResize throws ImageResizeException for it's own for errors. You can catch that or catch the general \Exception which it's extending.

It is not to be expected, but should anything go horribly wrong mid way then notice or warning Errors could be shown from the PHP GD and Image Functions (http://php.net/manual/en/ref.image.php)

getMessage(); } ">
try{
    $image = new ImageResize(null);
    echo "This line will not be printed";
} catch (ImageResizeException $e) {
    echo "Something went wrong" . $e->getMessage();
}

Filters

You can apply special effects for new image like blur or add banner.

$image = new ImageResize('image.jpg');

// Add blure
$image->addFilter(function ($imageDesc) {
    imagefilter($imageDesc, IMG_FILTER_GAUSSIAN_BLUR);
});

// Add banner on bottom left corner
$image18Plus = 'banner.png'
$image->addFilter(function ($imageDesc) use ($image18Plus) {
    $logo = imagecreatefrompng($image18Plus);
    $logo_width = imagesx($logo);
    $logo_height = imagesy($logo);
    $image_width = imagesx($imageDesc);
    $image_height = imagesy($imageDesc);
    $image_x = $image_width - $logo_width - 10;
    $image_y = $image_height - $logo_height - 10;
    imagecopy($imageDesc, $logo, $image_x, $image_y, 0, 0, $logo_width, $logo_height);
});

Flip

Flips an image using a given mode and this method is only for PHP version 5.4.

$flip = new ImageResize('image.png');
$image = imagecreatetruecolor(200, 100);

$flip->imageFlip($image, 0);

Both functions will be used in the order in which they were added.

Gamma color correction

You can disable the gamma color correction enabled by default.

$image = new ImageResize('image.png');
$image->gamma(false);

API Doc

https://gumlet.github.io/php-image-resize/index.html


Maintainer

This library is maintained by Gumlet.com

Comments
  •  How to output() correctly?

    How to output() correctly?

    This works:

    <?php
    
    include 'ImageResize.php';
    include 'ImageResizeException.php';
    
    $image = new \Gumlet\ImageResize('img/test.jpg');
    
    $image->resizeToWidth(170);
    $image->output();
    
    ?>
    

    This does not:

    <?php
    
    include 'ImageResize.php';
    include 'ImageResizeException.php';
    
    $image = new \Gumlet\ImageResize('img/test.jpg');
    
    $image->resizeToWidth(170);
    
    ?>
    
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Hello, world!</title>
      </head>
      <body>
      	<img src="<?php $image->output()?>"> or just <?php $image->output()?>
      </body>
    </html>
    

    The screen just gets black...

    opened by mike0liveira 24
  • V.2 Candidate

    V.2 Candidate

    • [+] More exceptions and error messages
    • [+] Added ImageResizeInterface
    • [*] Reorder and optimize code
    • [*] GammaCorrection disabled by default (issue #162)
    • [*] Reformat code
    • [*] Tests: updated
    • [*] Fixes: composer.json
    • [*] Fixes: README.md
    bug feature 
    opened by KarelWintersky 15
  • Fatal error: Call to undefined function Eventviva\exif_read_data()

    Fatal error: Call to undefined function Eventviva\exif_read_data()

    when I upload a picture I get the following error

    Fatal error: Call to undefined function Eventviva\exif_read_data()

    ../vendor/eventviva/php-image-resize/src/ImageResize.php on line 106

    opened by juanpablocs 15
  • Recognize WEBP image format on `php-5.x` version

    Recognize WEBP image format on `php-5.x` version

    Actually, this package still requires the php-5.5 and php-5.6 versions.

    And it should find the way to be compatible with php-5.5 and php-5.6 versions.

    Please take look at the detailed comments on issue #135.

    If we drop the php-5.x versions, this issue will be resolved.

    opened by peter279k 12
  • must be install ext: fileinfo?

    must be install ext: fileinfo?

    PHP Fatal error:  Call to undefined function Gumlet\finfo_open()
    
    [spider@ns543625 coupons_deals]$    php -m | grep fileinfo
    [spider@ns543625 coupons_deals]$
    
    opened by qiuyuhome 10
  • Convert from PNG to JPG - or any format

    Convert from PNG to JPG - or any format

    $image = new ImageResize('image.png');
    $image->convert('jpg');
    $image->crop(200, 200);
    $image->save('image2.jpg');
    

    An alternative to the above would be to check if the input extension is different from the output extension and then force a convert in those cases.

    opened by jenstornell 9
  • Add additional parameter to

    Add additional parameter to "resizeToBestFit" that allows to return an image with exact size, requested in parameters.

    Now, when I call the "resizeToBestFit" method it creates an image with the same ratio but different size. Sometimes you need this, but the other time, you get into the cases where you need in return an image that has exact width and height you've put into the parameters. The image shouldn't be scaled, but the rest of it should be filled with transparent\blanc\given color.

    Ex.: public function resizeToBestFit($max_width, $max_height, $allow_enlarge = false, $fill_color = false){}

    opened by glebavladimir 9
  • Improve saving to string

    Improve saving to string

    The function getImageAsString saves the image to a temporary file on disk, just to read it again. This is not optimal. You can get the result in a string by using output buffering.

    <?php
    ob_start();
    imagepng($image);
    $image_data = ob_get_contents();
    ob_end_clean();
    
    opened by michaelarnauts 9
  • Multiple operations on a single image does not work

    Multiple operations on a single image does not work

    $image = new ImageResize($file);
    $image->resizeToWidth(100);
    $image->crop(100, 100, true);
    $image->save($smallFile);
    

    Expected: expected

    What I get: test_3177788617

    opened by dmromanov 9
  • PHP 8.1 Deprecation warnings for float to int conversions

    PHP 8.1 Deprecation warnings for float to int conversions

    Using version 2.0.0 PHP Version 8.1.0

    The following deprecation warnings are triggered:

    Deprecated: Implicit conversion from float 177.09977827050997 to int loses precision in ImageResize.php on line 283
    Deprecated: Implicit conversion from float 177.09977827050997 to int loses precision in ImageResize.php on line 323
    
    opened by madhancock 8
  • resize is adding a black and white background

    resize is adding a black and white background

    Hello , im using image reisze to resize images, it's working properly in my local , but in production, the resize is adding a black and white backgrounds on resized images.

    Any solution ?

    question 
    opened by ziiko10 8
  • Square images are not resized correctly

    Square images are not resized correctly

    Resizing perfectly square image using methods resizeToWidth(), resizeToHeight(), resizeToBestFit(), resizeToShortSide() and resizeToLongSide() is supposed to always produce image with the same width and height, but its not always the case because one of the size values is ratio scaled and then rounded down to lowest integer value via (int) cast conversion.

    The easiest solution is to round scaled float value to closest integer value before type conversion. Ideally ratio scaling should be skipped completely when source width and height values are equal.

    opened by ecrider 1
  • round corners

    round corners

    I use the lib to convert my images, I would like to know if I can round the corners of the image with it. I didn't see anything in the documentation about this? Thanks

    opened by alissonrodrigo 0
  • imageFlip() function removed in v2.0.1 but still referenced in Readme.

    imageFlip() function removed in v2.0.1 but still referenced in Readme.

    https://github.com/gumlet/php-image-resize/compare/2.0.0...2.0.1

    But it's still in readme: https://github.com/gumlet/php-image-resize#flip

    It's also still in the API docs linked from the readme: https://gumlet.github.io/php-image-resize/class-Gumlet.ImageResize.html

    Is it the intention that this function should still be supported / available?

    opened by jarofgreen 1
  • Corrupt JPEG data

    Corrupt JPEG data

    I am receiving "corrupt JPEG" errors when I POST a base64 payload to the server. The bizarre thing is that I can paste the same base64 string into a script, performing the same logic and it works just fine.

    Here is my code:

                preg_match('/(data:.*;base64,)(.*)/', $imageBase64, $output_array);
    
                if (isset($output_array[1]) && isset($output_array[2])) {
    
                    ini_set("gd.jpeg_ignore_warning", 1);
                    $imageType = $output_array[1]; // data:image/jpeg;base64,
    //                $output_array[2]; // base64 data
    
    // fails here
                    $image = ImageResize::createFromString(base64_decode($output_array[2]));
                    $w = $image->getSourceWidth();
                    $h = $image->getSourceHeight();
    
                    if ($w > 100 || $h > 100) {
                        $image->resize(100, 100);
                    }
    
                    $resized = base64_encode( $image->getImageAsString() );
                }
    

    So I am stripping out data:image/jpeg;base64, before processing, then I receive this error.

    PHP Warning: getimagesize(): Corrupt JPEG data: 214 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 214 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 7 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 7 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 103 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 103 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 327 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: getimagesize(): Corrupt JPEG data: 327 extraneous bytes before marker in /H:/path/ImageResize.php on line 126
    PHP Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: Unsupported marker type 0x68 in /H:/path/ImageResize.php on line 179
    PHP Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: Unsupported marker type 0x68 in /H:/path/ImageResize.php on line 179
    PHP Warning: imagecreatefromjpeg(): &quot;data://application/octet-stream;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wB.....9KmcrRsRJpH/9g==&quot; is not a valid JPEG file in /H:/path/ImageResize.php on line 179
    PHP Warning: imagecreatefromjpeg(): &quot;data://application/octet-stream;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wB.....9KmcrRsRJpH/9g==&quot; is not a valid JPEG file in /H:/path/ImageResize.php on line 179
    PHP Fatal error: Uncaught TypeError: imagesx(): Argument #1 ($image) must be of type GdImage, bool given in /H:/path/ImageResize.php on line 149
    PHP Fatal error: Uncaught TypeError: imagesx(): Argument #1 ($image) must be of type GdImage, bool given in /H:/path/ImageResize.php on line 149
    

    The length of the base64 payload is the same if I copy directly into a script or if I POST it, so it isn't a truncation issue, and I have no problems creating image from a string and resizing when the base64 is pasted in. Any ideas of what could be going on?

    Server stats

    PHP Version 8.0.13
    
    PHP API | 20200930
    PHP Extension	| 20200930
    
    [gd]
    GD Version | bundled (2.1.0 compatible)
    FreeType Support | enabled
    FreeType Linkage | with freetype
    FreeType Version | 2.9.1
    GIF Read Support | enabled
    GIF Create Support | enabled
    JPEG Support | enabled
    libJPEG Version | 9 compatible
    PNG Support | enabled
    libPNG Version | 1.6.34
    WBMP Support | enabled
    XPM Support | enabled
    libXpm Version | 30512
    XBM Support | enabled
    WebP Support | enabled
    BMP Support | enabled
    TGA Read Support | enabled
    
    opened by failingbirthrate 1
  • How can I get Resized Image With

    How can I get Resized Image With

    I use php-image-resize via composer.

    I have a crop action wich a bit special for my script.

    At some point, I need to know the result of resizeToHeight action as image sizes. But the method does not keep the width result on properties or return as a result.

    Here is my example.

    <?php
    
    //load composer
    require_once './vendor/autoload.php';
    
    use \Gumlet\ImageResize;
    
    $sourceFilename = 'test.jpg';
    $destFilename = 'result.jpg';
    $imageCropWidth = 202;
    $imageCropHeight = 267;
    
    $image = new ImageResize($sourceFilename);
    
    $image->resizeToHeight($imageCropHeight);
    if ( $image->getSourceWidth() >= $image->getSourceHeight() )
    {
        $image->crop($imageCropWidth, $imageCropHeight);
    }
    else
    {
        //ALERT
        //in this part, I need to know resized image Width
        //$resizedWith = $image->getResizedImageWidth();
        if( $resizedWith > $imageCropWidth )
        {
            $image->crop($imageCropWidth, $imageCropHeight);
        }
    }
    
    $image->save($destFilename, IMAGETYPE_JPEG);
    
    opened by sabriunal 2
Releases(2.0.3)
Owner
Gumlet
Image resize and delivery made simple
Gumlet
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
Image Resize Middleware for Slim Framework

Image Resize Middleware for Slim This middleware implements automatic image resizing based on image filename. Install You can install latest version u

Mika Tuupola 61 Apr 12, 2022
ImageWorkshop is a PHP5.3+ library that helps you to manage images based on GD library

================================ ImageWorkshop class ================================ Summary and features Really flexible and easy-to-use PHP class t

Clément Guillemain 853 Dec 27, 2022
The Tinify API allows you to compress and optimize WebP, JPEG and PNG images.

The Tinify API allows you to compress and optimize WebP, JPEG and PNG images. It is designed as a REST service. The client libraries in various languages make it very easy to interact with the Tinify API.

Devscast 10 May 13, 2022
A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API.

A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API. This enables you to build cool little tricks, like showing your latest followers or sponsors, latest content creted, a qrcode to something, a progress bar for some goal, and whathever you can think of.

Erika Heidi 172 Jan 5, 2023
The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API

Gregwar's Image class The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API. Installation With compos

Grégoire Passault 958 Dec 29, 2022
Simple, fast and secure archive for images

Slim Image Archive Simple*, fast and secure archive for images: Create multiple categories with multiple albums with multiple images! Manage multiple

KS 24 Oct 23, 2021
GifCreator is a PHP class that creates animated GIF from multiple images

================================ GifCreator ================================ GifCreator is a PHP class to create animated GIF from multiple images For

Clément Guillemain 320 Dec 15, 2022
Inline Images Protocol implementation for PHP.

Imgecho Echo the image on iTerm App using Inline Images Protocol. Installation Use Composer to install. composer require mileschou/imgecho Usage Use

MilesChou 4 May 30, 2022
Create images with embedded text using advanced typography

Image with Text This class makes it super easy to render images with multiple, independently styled text blocks. You can control each text block's ali

New Media Campaigns 144 Sep 7, 2022
Easily convert images with Glide

Easily convert images with Glide This package provides an easy to use class to manipulate images. Under the hood it leverages Glide to perform the man

Spatie 374 Dec 30, 2022
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

Flowframe 53 Oct 17, 2022
Upload SVG images in Magento 2.x

Upload SVG images in Magento 2.x This extension for Magento 2 allows uploading SVG images in the following sections: wysiwyg editor in static blocks a

Magegadgets 6 Dec 23, 2022
The image server plugin allows you to add responsive images via config without extra elements

Grav image server plugin adds picture tag with loading, responsive, high density images

catchIT 7 Dec 30, 2022
Create beautiful generative background images from a string. Based on jasonlong/geo_pattern

GeoPattern This is a PHP port of jasonlong/geo_pattern. Generate beautiful tiling SVG patterns from a string. The string is converted into a SHA and a

Redeye Group 106 Aug 17, 2022
Contao extension to provide the possibility of defining alternative images to be used on different output devices.

Contao Image Alternatives This extensions expands the capabilities of using responsive images with art direction in Contao. You will have the possibil

inspiredminds 6 May 30, 2022
PHP Exif Library - library for reading and writing Exif headers in JPEG and TIFF files using PHP.

PEL: PHP Exif Library README file for PEL: PHP Exif Library. A library with support for reading and writing Exif headers in JPEG and TIFF images using

null 264 Dec 4, 2022
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Image Optimizer This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more librarie

Piotr Śliwa 879 Dec 30, 2022
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

Bulat Shakirzyanov 4.3k Jan 6, 2023