Skip to content

Latest commit

 

History

History
407 lines (264 loc) · 17.5 KB

README.md

File metadata and controls

407 lines (264 loc) · 17.5 KB

PHP ImageResize

ImageResize is a simple PHP class that can be used to resize images on the fly using PHP's native GD library. The library is also able to add watermarks and text overlays to your images automatically.

The only dependency for this Class is that the GD library be installed on your server. You must be running PHP >= 5.6.

Latest Version Software License

Table of Contents:

  1. Version History
  2. Installation
  3. Getting Started
  4. Image Method Reference
  5. Text Method Reference
  6. Watermark Method Reference
  7. Requirements
  8. Bugs & Features
  9. License

1. Version History:

  • Version 1.1.0 (2018-05-13)

    • Added text overlay support
    • Added watermark support
    • Added getAverageColor() method to Image.
    • Minor bug fixes
  • Version 1.0.0 (2018-05-09)

    • The library was officially launched and added to Github, Packagist and Composer.

2. Installation:

The easiest way to install the library is using Composer:

$ composer require benmajor/php-image-resize

Or simply download the PHP package from the src/ directory in this repository.

3. Getting Started:

To get started, call the constructor, and pass a path to a valid image to it:

<?php

use BenMajor\ImageResize\Image;

$image = new Image('http://example.com/image.jpg');

Note: In order to use a remote URL, your PHP configuration must have the allow_url_fopen directive enable. If this is disabled, a fatal error will be thrown from the constructor stating that the source image does not exist.

Once you have created a new ImageResize object, it is possible to perform functions on the image (these functions are listed in Section 4). After applying functions and resize methods to the image, you are then able to output the generated image file to the browser, or force it to download to the user's computer by using the output() and download() methods respectively.

To learn more about the usage of the library, please see the examples directory in this repository.

4. Image Method Reference:

Note: The order in which methods are called is generally irrelevent, but you should always call the output(*) or download(*) functions last in order to avoid unexpected behaviour.

The following is a list of the various methods that may be called on an ImageResize object. For more information and example usage, please see the examples posted in the examples directory of this repository.

Please note that some methods only affect certain resize techniques. When this is the case, a note has been added to the method reference below.

Resize methods:

resize( $width, $height ):
Resizes the image to the specified dimensions, ignoring aspect ratio. If $height is null, a square image will be generated, using $width for both the width and height of the output.

resizeWidth( $width ):
Resizes the image to $width pixels wide, and calculates the height of the generated image in order to maintain the original aspect ratio.

resizeHeight( $height ):
Resizes the image to $height pixels tall, and calculates the width of the generated image in order to maintain the original aspect ratio.

resizeCrop( $width, $height ):
Resizes and automatically crops the image to the specified dimensions. This is particularly useful for generating thumbnails and smaller versions of images where the output size is constrained, but the aspect ratio of the original image should be maintained.
If $height is null, a square image will be generated, using $width for both the width and height of the output.

contain( $width, $height ):
Creates a canvas $width × $height pixels in size, and resizes the image proportionally to ensure the entire image fits onto the canvas and centers the resized image. If $height is null, a square image will be generated, using $width for both the width and height of the output.


Output methods:

output( $cache = false):
Outputs the image using its original mime type.
$cache can be used as a directory pointer. If $cache is specified as a string, the resized image is written to the specified directory contained in $cache, rather than output to the buffer.

outputJPEG( $cache = false):
Outputs the image as a JPEG.
$cache can be used as a directory pointer. If $cache is specified as a string, the resized image is written to the specified directory contained in $cache, rather than output to the buffer.

outputPNG( $cache = false ):
Outputs the image as a PNG.
$cache can be used as a directory pointer. If $cache is specified as a string, the resized image is written to the specified directory contained in $cache, rather than output to the buffer.

outputGIF( $cache = false ):
Outputs the image as a GIF.
$cache can be used as a directory pointer. If $cache is specified as a string, the resized image is written to the specified directory contained in $cache, rather than output to the buffer.

outputHTML( bool $tag, string $alt, string $title, bool $echo ):
Produces the necessary markup for an <img /> element, and Base64 encodes the resized image. Accepts the following (optional) parameters:

  • $tag: include the HTML tag. If false, only the Base 64 URL will be returned.
    Default: true.
  • $alt: string containing the value for the alt attribute of the generated element.
    Default: null.
  • $title: string containing the value to be used in the title attribute of the generated element.
    Default: null.
  • $echo: boolean indicating whether the tag should be echoed (output) as well as returned. Default: true.

Download methods:

download( $filename = null ):
Force the image to be downloaded by the browser (rather than displayed inline) using its original mime type.
If $filename is null, the original filename will be used, or pass a string to force a different filename in the download dialog. The extension is not required.

downloadJPEG( $filename = null ):
Force the image to be downloaded by the browser as a JPEG image.
If $filename is null, the original filename will be used, or pass a string to force a different filename in the download dialog. The extension is not required.

downloadPNG( $filename = null ):
Force the image to be downloaded by the browser as a PNG image.
If $filename is null, the original filename will be used, or pass a string to force a different filename in the download dialog. The extension is not required.

downloadGIF( $filename = null ):
Force the image to be downloaded by the browser as a GIF image.
If $filename is null, the original filename will be used, or pass a string to force a different filename in the download dialog. The extension is not required.


Editing methods:

setPadding( $padding ):
Set the padding that should be used (in pixels) when using the contain() resize method.

setTransparency( bool $transparency ):
Set whether the image resizer should maintain transparency (only valid for transparent PNG or GIF source images).

disableRename():
Do not automatically rename cached images when saving the resized image to the server.

enableRename():
Enables automatic renaming of cached images when saving to the server.

setTmpDir():
Set the temporary directory for working. By default, the temporary directory is the value returned by sys_get_temp_dir().

setQuality():
Set the output quality of the generated image. The integer should be a value out of 100. The default value is 100.

setBackgroundColor( string $bg ):
Set the background colour that should be used for contain() or other methods. It should be passed as a hex-color string. If transparency is disabled, transparent GIFs or PNGs will have this as the background colour.

setBorder( $width, $color ):
Add a border to the generated image. $width should be an integer representing the pixel width of the border. $color should be a hex string.

setBorderWidth( $width ):
Sets the width of the border. $width should be an integer representing the pixel width of the border.

setBorderColor( $color ):
Sets the color of the generated border. $color should be a string containing a hex value (e.g. #000).


Filter methods:

In addition to resizing images, this library also offers basic editing and filter capabilities for the image. This reference shows all of the currently supported filter methods:

greyscale():
Convert the image to greyscale (black and white).

invert():
Invert the colors of the image.

setBrightness( int $brightness ):
Change the brightness of the image (accepts any valid integer value). Uses PHP's IMG_FILTER_BRIGHTNESS constant.

setContrast( int $contrast ):
Changes the contrast of the image (accepts any valid integer value). Use's PHP's IMG_FILTER_CONTRAST constant.

setSaturation( float $saturation ):
Increase or descrease the image's saturation. Since GD does not offer a built-in method for changing saturation, the only way we can achieve this is to manually set the colour value of each pixel in an image.
Note: if you're not caching images, this function may cause images to render slowly, especially larger images.

colorize( $color ):
Colorize the image using the specified $color. $color should be a string containing a valid hex color definition.


Get methods:

getBorder():
Get the current settings for the image's border (returns an object containing width and color properties.

getBorderWidth():
Gets the current width (in pixels) of the image's border.

getBorderColor():
Gets the current color (as an array) of the image's border.

getTmpDir():
Returns a string representing the current working directory.

getQuality():
Get the current quality setting.

getTransparency():
Check whether transparency is currently enabled.

getPadding():
Get the current pixel value of the padding.

getOutputWidth():
Get the width of the generated image.
Note: this must be called after a resize function has been called.

getOutputHeight():
Get the height of the generated image.
Note: this must be called after a resize function has been called.

getImgTagAttributes():
Returns a string containing the size attributes of the resized image to be used for <img /> tags (e.g. width="x" height="x"). Note: this must be called after a resize function has been called.

getAverageColor():
Returns the average colour of the image as a hex string (e.g. #ff00ff).

5. Text Method Reference:

In addition to offering resize functions, the library also allows the writing of text (including an optional bounding box) to the image before or after resizing. Text is defined using the Text class as follows:

<?php

$image = new Image('image_src');
$text  = new Text('My String');

$image->addText( $text );
$image->output();

For more information and demos, please check out the examples directory in the Github repo.

The following is a list of the methods supported for Text objects:


Set methods:

setText( string $text ):
Set the text to be rendered.

setFont( string $src ):
Set the URL of a TTF font to be used for the rendered text.
Must point to a valid TTF font file -- can be remote.

setColor( string $hex ):
Set the foreground colour of the text using a valid hex string.

setBackgroundColor( string $hex ):
Set the background colour of the bounding box using a valid hex string.

setBackgroundOpacity( int $opacity ):
Set the % of the background's opacity.

setPadding( int $padding ):
Set the padding (in px) of the bounding box.

setPosition( mixed $position ):
Set the position of the text on the image. Accepts physical pixel co-ordinates (as an array indexed by x and y respectively), or one of the following string values:

  • t - centered, top
  • tr - top right corner
  • r - centered, right
  • br - bottom right corner
  • b - centered, bottom
  • bl - bottom left corner
  • l - centered, left
  • tl - top left corner
  • c - fully centered

setWidth( mixed $width ):
Set the width of the bounding box. Either 'auto', or an integer representing a % width of the image. Auto will automatically size the bounding box to fit the content.

setTextAlign( string $align ):
Set the text alignment within the bounding box. Accepts a string containing left, center or right.


Get methods:

getText():
Returns the text to be rendered in a string.

getFont():
Gets the URL of the font currently being used. (Default: https://github.com/CartoDB/cartodb/blob/master/app/assets/fonts/helvetica.ttf?raw=true).

getFontSize():
Get the current font size used for the text (in Points).

getColor():
Get the currently assigned foreground color. (Returns an array of RGB color values).

getBackgroundColor():
Get the background colour currently being used for the text's bounding box.

getPadding():
Get the bounding box padding.

getPosition():
Get the position for the text to be rendered on the original imafe.

getWidth():
Get the width of the bounding box.

getTextAlign():
Get the alignment of the text within the bounding box.

6. Watermark Method Reference:

Watermarks are useful for securing your images or making it difficult for unscrupulous web users to simply rip you off. Hower, manually adding watermarks to images can be laborious, and if you decide on a new logo or watermark, you need to do it all over again! This is the reason I decided to add watermark support to the library.

Adding watermarks is easy; just specify the URL to use for the watermark logo, and add it to the image:

<?php

$image     = new Image('image_src');
$watermark = new Watermark('watermark_src');

$image->addWatermark( $watermark );
$image->output();

For best results, it is recommended to use a transparent PNG image for your watermark's source.

For more information and demos, please check out the examples directory in the Github repo.

The following is a list of the methods supported for Watermark objects:


Set methods:

setMargin( int $margin ):
Set the margin to be used for the watermark.

setOpacity( int $opacity ):
Set the percentage of opacity to be used for the watermark.

setPosition( mixed $position ):
Set the position of the watermark on the image. Accepts physical pixel co-ordinates (as an array indexed by x and y respectively), or one of the following string values:

  • t - centered, top
  • tr - top right corner
  • r - centered, right
  • br - bottom right corner
  • b - centered, bottom
  • bl - bottom left corner
  • l - centered, left
  • tl - top left corner
  • c - fully centered

setWidth( int $width, bool $constrain = true ):
Set the resized width of the watermark, and optionally constrain its proportions.

setHeight( int $height, bool $constrain = true ):
Set the resized height of the watermark, and optionally constrain its proportions.


Get methods:

getMargin():
Get the pixel value of the margin for the watermark.

getOpacity():
Get the opacity percentage of the watermark.

getPosition():
Get the position of the watermark.

getWidth():
Get the resized width of the watermark. May be useful if you are constraining the resize.

getHeight():
Get the resized height of the watermark. May be useful if you are constraining the resize.

7. Requirements:

The library requires PHP >= 5.6 and the PHP GD extension to be installed and enabled on the target server.

8. Bugs & Features:

If you have spotted any bugs, or would like to request additional features from the library, please file an issue via the Issue Tracker on the project's Github page: https://github.com/benmajor/PHP-Image-Resize/issues.

9. License:

Licensed under the MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.