claviska / SimpleImage

A PHP class that makes working with images and GD as simple as possible.
MIT License
1.38k stars 383 forks source link
gd image-processing php

SimpleImage

A PHP class that makes working with images as simple as possible.

Developed and maintained by Cory LaViska.

If this project has you loving PHP image manipulation again, please consider sponsoring me to support its development.


Overview

<?php
try {
  // Create a new SimpleImage object
  $image = new \claviska\SimpleImage();

  // Magic! ✨
  $image
    ->fromFile('image.jpg')                     // load image.jpg
    ->autoOrient()                              // adjust orientation based on exif data
    ->resize(320, 200)                          // resize to 320x200 pixels
    ->flip('x')                                 // flip horizontally
    ->colorize('DarkBlue')                      // tint dark blue
    ->border('black', 10)                       // add a 10 pixel black border
    ->overlay('watermark.png', 'bottom right')  // add a watermark image
    ->toFile('new-image.png', 'image/png')      // convert to PNG and save a copy to new-image.png
    ->toScreen();                               // output to the screen

  // And much more! 💪
} catch(Exception $err) {
  // Handle errors
  echo $err->getMessage();
}

Requirements

Features

Installation

Install with Composer:

composer require claviska/simpleimage

Or include the library manually:

<?php
require 'src/claviska/SimpleImage.php';

About

SimpleImage is developed and maintained by Cory LaViska. Copyright A Beautiful Site, LLC.

If you enjoy using SimpleImage, especially in commercial applications, please consider sponsoring me to support its development.

Thanks! 🙌

License

Licensed under the MIT license.

API

Order of awesomeness:

  1. Load an image
  2. Manipulate the image
  3. Save/output the image

API tips:

Loaders

fromDataUri($uri)

Loads an image from a data URI.

Returns a SimpleImage object.

fromFile($file)

Loads an image from a file.

Returns a SimpleImage object.

fromNew($width, $height, $color)

Creates a new image.

Returns a SimpleImage object.

fromString($string)

Creates a new image from a string.

Returns a SimpleImage object.

Savers

toDataUri($mimeType, $options)

Generates a data URI.

Returns a string containing a data URI.

toDownload($filename, $mimeType, $options)

Forces the image to be downloaded to the clients machine. Must be called before any output is sent to the screen.

Returns a SimpleImage object.

toFile($file, $mimeType, $options)

Writes the image to a file.

Returns a SimpleImage object.

toScreen($mimeType, $options)

Outputs the image to the screen. Must be called before any output is sent to the screen.

Returns a SimpleImage object.

toString($mimeType, $options)

Generates an image string.

Returns a SimpleImage object.

generate($mimeType, $options)

Generates an image.

Returns an array: [mimeType, data]

Options array

Instead of providing the quality as an integer as the last function parameter you can also set various options depending on the targeted Mime type using an associative array.

$image->toFile($file, 'image/avif', [
    // JPG, WEBP, AVIF (default 100)
    'quality' => 100,

    // AVIF (default -1 which is 6)
    // range of slow and small file 0 to 10 fast but big file
    'speed' => -1,
]);
$image->toFile($file, 'image/bmp', [
    // BMP: boolean (default true)
    'compression' => true,

    // BMP, JPG (default null, keep the same)
    'interlace' => null,
]);
$image->toFile($file, 'image/gif', [
    // GIF, PNG (default true)
    'alpha' => true,
]);
$image->toFile($file, 'image/jpeg', [
    // BMP, JPG (default null, keep the same)
    'interlace' => null,

    // JPG, WEBP, AVIF (default 100)
    'quality' => 100,
]);
$image->toFile($file, 'image/png', [
    // GIF, PNG (default true)
    'alpha' => true,

    // PNG: 0-10, defaults to zlib (default 6)
    'compression' => -1,

    // PNG (default -1)
    'filters' => -1,

    // has no effect on PNG images, since the format is lossless
    // 'quality' => 100,
]);
$image->toFile($file, 'image/webp', [
    // JPG, WEBP, AVIF (default 100)
    'quality' => 100,
]);

Utilities

getAspectRatio()

Gets the image's current aspect ratio.

Returns the aspect ratio as a float.

getExif()

Gets the image's exif data.

Returns an array of exif data or null if no data is available.

getHeight()

Gets the image's current height.

Returns the height as an integer.

getMimeType()

Gets the mime type of the loaded image.

Returns a mime type string.

getOrientation()

Gets the image's current orientation.

Returns a string: 'landscape', 'portrait', or 'square'

getResolution()

Gets the image's current resolution in DPI.

Returns an array of integers: [0 => 96, 1 => 96]

getWidth()

Gets the image's current width.

Returns the width as an integer.

hasImage()

Checks if the SimpleImage object has loaded an image.

Returns a boolean.

reset()

Destroys the image resource.

Returns a SimpleImage object.

Manipulation

autoOrient()

Rotates an image so the orientation will be correct based on its exif data. It is safe to call this method on images that don't have exif data (no changes will be made). Returns a SimpleImage object.

bestFit($maxWidth, $maxHeight)

Proportionally resize the image to fit inside a specific width and height.

Returns a SimpleImage object.

crop($x1, $y1, $x2, $y2)

Crop the image.

Returns a SimpleImage object.

fitToHeight($height) (DEPRECATED)

Proportionally resize the image to a specific height.

This method was deprecated in version 3.2.2 and will be removed in version 4.0. Please use resize(null, $height) instead.

Returns a SimpleImage object.

fitToWidth($width) (DEPRECATED)

Proportionally resize the image to a specific width.

This method was deprecated in version 3.2.2 and will be removed in version 4.0. Please use resize($width, null) instead.

Returns a SimpleImage object.

flip($direction)

Flip the image horizontally or vertically.

Returns a SimpleImage object.

maxColors($max, $dither)

Reduces the image to a maximum number of colors.

Returns a SimpleImage object.

overlay($overlay, $anchor, $opacity, $xOffset, $yOffset)

Place an image on top of the current image.

Returns a SimpleImage object.

resize($width, $height)

Resize an image to the specified dimensions. If only one dimension is specified, the image will be resized proportionally.

Returns a SimpleImage object.

resolution($res_x, $res_y)

Changes the resolution (DPI) of an image.

Returns a SimpleImage object.

rotate($angle, $backgroundColor)

Rotates the image.

Returns a SimpleImage object.

text($text, $options, &$boundary)

Adds text to the image.

Returns a SimpleImage object.

thumbnail($width, $height, $anchor)

Creates a thumbnail image. This function attempts to get the image as close to the provided dimensions as possible, then crops the remaining overflow to force the desired size. Useful for generating thumbnail images.

Returns a SimpleImage object.

Drawing

arc($x, $y, $width, $height, $start, $end, $color, $thickness)

Draws an arc.

Returns a SimpleImage object.

border($color, $thickness)

Draws a border around the image.

Returns a SimpleImage object.

dot($x, $y, $color)

Draws a single pixel dot.

Returns a SimpleImage object.

ellipse($x, $y, $width, $height, $color, $thickness)

Draws an ellipse.

Returns a SimpleImage object.

fill($color)

Fills the image with a solid color.

Returns a SimpleImage object.

line($x1, $y1, $x2, $y2, $color, $thickness)

Draws a line.

Returns a SimpleImage object.

polygon($vertices, $color, $thickness)

Draws a polygon.

Returns a SimpleImage object.

rectangle($x1, $y1, $x2, $y2, $color, $thickness)

Draws a rectangle.

Returns a SimpleImage object.

roundedRectangle($x1, $y1, $x2, $y2, $radius, $color, $thickness)

Draws a rounded rectangle.

Returns a SimpleImage object.

Filters

blur($type, $passes)

Applies the blur filter.

Returns a SimpleImage object.

brighten($percentage)

Applies the brightness filter to brighten the image.

Returns a SimpleImage object.

colorize($color)

Applies the colorize filter.

Returns a SimpleImage object.

contrast($percentage)

Applies the contrast filter.

Returns a SimpleImage object.

darken($percentage)

Applies the brightness filter to darken the image.

Returns a SimpleImage object.

desaturate()

Applies the desaturate (grayscale) filter.

Returns a SimpleImage object.

duotone($lightColor, $darkColor)

Applies the duotone filter to the image.

Returns a SimpleImage object.

edgeDetect()

Applies the edge detect filter.

Returns a SimpleImage object.

emboss()

Applies the emboss filter.

Returns a SimpleImage object.

invert()

Inverts the image's colors.

Returns a SimpleImage object.

opacity()

Changes the image's opacity level.

Returns a SimpleImage object.

pixelate($size)

Applies the pixelate filter.

Returns a SimpleImage object.

sepia()

Simulates a sepia effect by desaturating the image and applying a sepia tone.

Returns a SimpleImage object.

sharpen($amount)

Sharpens the image.

Returns a SimpleImage object.

sketch()

Applies the mean remove filter to produce a sketch effect.

Returns a SimpleImage object.

Color utilities

(static) adjustColor($color, $red, $green, $blue, $alpha)

Adjusts a color by increasing/decreasing red/green/blue/alpha values independently.

Returns an RGBA color array.

(static) darkenColor($color, $amount)

Darkens a color.

Returns an RGBA color array.

extractColors($count = 10, $backgroundColor = null)

Extracts colors from an image like a human would do.™ This method requires the third-party library \League\ColorExtractor. If you're using Composer, it will be installed for you automatically.

Returns an array of RGBA colors arrays.

getColorAt($x, $y)

Gets the RGBA value of a single pixel.

Returns an RGBA color array or false if the x/y position is off the canvas.

(static) lightenColor($color, $amount)

Lightens a color.

Returns an RGBA color array.

(static) normalizeColor($color)

Normalizes a hex or array color value to a well-formatted RGBA array.

You can pipe alpha transparency through hex strings and color names. For example:

fff|0.50 <-- 50% white

red|0.25 <-- 25% red

Returns an array: [red, green, blue, alpha]

Exceptions

SimpleImage throws standard exceptions when things go wrong. You should always use a try/catch block around your code to properly handle them.

<?php
try {
  $image = new \claviska\SimpleImage('image.jpeg')
  // ...
} catch(Exception $err) {
  echo $err->getMessage();
}

To check for specific errors, compare $err->getCode() to the defined error constants.

<?php
try {
  $image = new \claviska\SimpleImage('image.jpeg')
  // ...
} catch(Exception $err) {
  if($err->getCode() === $image::ERR_FILE_NOT_FOUND) {
    echo 'File not found!';
  } else {
    echo $err->getMessage();
  }
}

As a best practice, always use the defined constants instead of their integers values. The values will likely change in future versions, and WILL NOT be considered a breaking change.

Useful Things To Know

Instance flags

Tweak the behavior of a SimpleImage instance by setting instance flag values with the setFlag($key, $value) method.

$image = new \claviska\SimpleImage('image.jpeg')->setFlag("foo", "bar");

You can also pass an associative array to the SimpleImage constructor to set instance flags.

$image = new \claviska\SimpleImage('image.jpeg', ['foo' => 'bar']);
// .. or without an $image
$image = new \claviska\SimpleImage(flags: ['foo' => 'bar']);

Note: setFlag() throws an ERR_INVALID_FLAG exception if the key does not exist (no default value).

sslVerify

Setting sslVerify to false (defaults to true) will make all images loaded over HTTPS forgo certificate peer validation. This is especially usefull for self-signed certificates.

$image = new \claviska\SimpleImage('https://localhost/image.jpeg', ['sslVerify' => false]);
// Would normally throw an OpenSSL exception, but is ignored with the sslVerify flag set to false.

Differences from SimpleImage 2.x