Top Related Projects
Manipulate images with an expressive API
PHP Object Oriented image manipulation library
A PHP class that makes working with images and GD as simple as possible.
Quick Overview
Gregwar/Image is a PHP library for image handling and manipulation. It provides a simple and intuitive interface for common image operations such as resizing, cropping, and applying filters. The library is designed to be lightweight and easy to use, making it suitable for various web development projects.
Pros
- Simple and intuitive API for image manipulation
- Supports various image formats (JPEG, PNG, GIF, etc.)
- Includes caching mechanisms for improved performance
- Chainable methods for concise and readable code
Cons
- Limited advanced image processing features compared to more comprehensive libraries
- Requires GD or Imagick extension to be installed on the server
- Documentation could be more extensive and up-to-date
- May not be suitable for projects requiring complex image processing tasks
Code Examples
- Resizing an image:
<?php
use Gregwar\Image\Image;
$image = Image::open('input.jpg')
->resize(300, 200)
->save('output.jpg');
- Applying a filter and cropping:
<?php
use Gregwar\Image\Image;
$image = Image::open('input.jpg')
->sepia()
->crop(100, 100, 300, 200)
->save('output.jpg');
- Creating a thumbnail with caching:
<?php
use Gregwar\Image\Image;
$image = Image::open('input.jpg')
->cropResize(150, 150)
->jpeg(85)
->useCacheFile('cache/thumbnail.jpg')
->save('output.jpg');
Getting Started
To use Gregwar/Image in your PHP project, follow these steps:
-
Install the library using Composer:
composer require gregwar/image
-
Include the Composer autoloader in your PHP file:
<?php require 'vendor/autoload.php';
-
Use the library in your code:
<?php use Gregwar\Image\Image; $image = Image::open('input.jpg') ->resize(300, 200) ->save('output.jpg');
Now you can start manipulating images using the Gregwar/Image library in your PHP project.
Competitor Comparisons
Manipulate images with an expressive API
Pros of Image (spatie)
- More modern PHP support (PHP 8.0+)
- Extensive documentation and clear API
- Active development and maintenance
Cons of Image (spatie)
- Fewer built-in filters and effects
- Steeper learning curve for beginners
- Requires Imagick or GD extension
Code Comparison
Image (Gregwar):
$image = Image::open('input.jpg')
->resize(100, 100)
->negate()
->save('output.jpg');
Image (spatie):
$image = Image::load('input.jpg')
->width(100)
->height(100)
->negative()
->save('output.jpg');
Key Differences
- Image (spatie) offers a more fluent interface
- Image (Gregwar) provides more built-in filters
- Image (spatie) has stricter type hinting and return types
- Image (Gregwar) supports older PHP versions (5.3+)
Use Cases
- Image (spatie): Modern PHP projects with complex image manipulation needs
- Image (Gregwar): Legacy projects or simple image processing tasks
Both libraries provide powerful image manipulation capabilities, but Image (spatie) is better suited for modern PHP development, while Image (Gregwar) offers broader compatibility and simpler usage for basic tasks.
PHP Object Oriented image manipulation library
Pros of Imagine
- More comprehensive and feature-rich image manipulation library
- Better documentation and community support
- Supports a wider range of image formats and operations
Cons of Imagine
- Larger footprint and potentially slower for simple operations
- Steeper learning curve due to more complex API
- May be overkill for projects with basic image processing needs
Code Comparison
Image (Gregwar):
$image = Image::open('input.jpg')
->resize(100, 100)
->negate()
->save('output.jpg');
Imagine:
$imagine = new Imagine\Gd\Imagine();
$image = $imagine->open('input.jpg')
->resize(new Box(100, 100))
->effects()->negative()
->save('output.jpg');
Both libraries offer similar functionality, but Imagine's API is more verbose and object-oriented. Image provides a more straightforward, fluent interface for basic operations, while Imagine offers greater flexibility and advanced features at the cost of increased complexity.
A PHP class that makes working with images and GD as simple as possible.
Pros of SimpleImage
- More lightweight and focused on basic image manipulation tasks
- Easier to use with a simpler API
- Better documentation and examples for quick implementation
Cons of SimpleImage
- Less feature-rich compared to Image
- Limited support for advanced image processing operations
- Fewer options for image optimization and compression
Code Comparison
SimpleImage:
$image = new \claviska\SimpleImage();
$image
->fromFile('image.jpg')
->resize(300, 200)
->toFile('resized.jpg');
Image:
$image = Image::open('image.jpg')
->resize(300, 200)
->save('resized.jpg');
Key Differences
- SimpleImage focuses on simplicity and ease of use, while Image offers more advanced features
- Image provides more flexibility in terms of image processing and manipulation options
- SimpleImage has a more straightforward API, making it easier for beginners to get started
- Image offers better performance for complex image processing tasks
Use Cases
- SimpleImage: Quick image resizing, cropping, and basic manipulations
- Image: Advanced image processing, effects, and optimizations for more complex projects
Both libraries have their strengths, and the choice between them depends on the specific requirements of your project and your level of expertise in image manipulation.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Gregwar's Image class
The Gregwar\Image
class purpose is to provide a simple object-oriented images handling and caching API.
Installation
With composer :
{
...
"require": {
"gregwar/image": "2.*"
}
}
Usage
Basic handling
Using methods chaining, you can open, transform and save a file in a single line:
<?php use Gregwar\Image\Image;
Image::open('in.png')
->resize(100, 100)
->negate()
->save('out.jpg');
Here are the resize methods:
resize($width, $height, $background)
: resizes the image, will preserve scale and never enlarge it (background isred
in order to understand what happens):
scaleResize($width, $height, $background)
: resizes the image, will preserve scale, can enlarge it (background isred
in order to understand what happens):
forceResize($width, $height, $background)
: resizes the image forcing it to be exactly$width
by$height
cropResize($width, $height, $background)
: resizes the image preserving scale (just likeresize()
) and croping the whitespaces:
zoomCrop($width, $height, $background, $xPos, $yPos)
: resize and crop the image to fit to given dimensions:
- In
zoomCrop()
, You can change the position of the resized image using the$xPos
(center, left or right) and$yPos
(center, top or bottom):
The other methods available are:
-
crop($x, $y, $w, $h)
: crops the image to a box located on coordinates $x,y and which size is $w by $h -
negate()
: negates the image colors -
brighness($b)
: applies a brightness effect to the image (from -255 to +255) -
contrast($c)
: applies a contrast effect to the image (from -100 to +100) -
grayscale()
: converts the image to grayscale -
emboss()
: emboss the image -
smooth($p)
: smooth the image -
sharp()
: applies a mean removal filter on the image -
edge()
: applies an edge effect on the image -
colorize($red, $green, $blue)
: colorize the image (from -255 to +255 for each color) -
sepia()
: applies a sepia effect -
merge($image, $x, $y, $width, $height)
: merges two images -
fill($color, $x, $y)
: fills the image with the given color -
write($font, $text, $x, $y, $size, $angle, $color, $position)
: writes text over image, $position can be any of 'left', 'right', or 'center' -
rectangle($x1, $y1, $x2, $y2, $color, $filled=false)
: draws a rectangle -
rotate($angle, $background = 0xffffff)
: rotate the image to given angle -
roundedRectangle($x1, $y1, $x2, $y2, $radius, $color, $filled=false)
: draws a rounded rectangle ($radius can be anything from 0) -
line($x1, $y1, $x2, $y2, $color)
: draws a line -
ellipse($cx, $cy, $width, $height, $color, $filled=false)
: draws an ellipse -
circle($cx, $cy, $r, $color, $filled=false)
: draws a circle -
fillBackground($bg=0xffffff)
: fills the background of a transparent image to the 'bg' color -
fixOrientation()
: return the image rotated and flipped using image exif information -
applyExifOrientation(int $exif_rotation_value)
: return the image rotated and flipped using an exif rotation value -
html($title = '', $type = 'jpg')
: return the<img ... />
tag with the cache image -
flip($flipVertical, $flipHorizontal)
: flips the image in the given directions. Both params are boolean and at least one must be true. -
inline($type = 'jpg')
: returns the HTML inlinable base64 string (seedemo/inline.php
)
You can also create image from scratch using:
<?php
Image::create(200, 100);
Where 200 is the width and 100 the height
Saving the image
You can save the image to an explicit file using save($file, $type = 'jpg', $quality = 80)
:
<?php
// ...
$image->save('output.jpg', 'jpg', 85);
You can also get the contents of the image using get($type = 'jpg', $quality = 80)
, which will return the binary contents of the image
Using cache
Each operation above is not actually applied on the opened image, but added in an operations
array. This operation array, the name, type and modification time of file are hashed using
sha1()
and the hash is used to look up for a cache file.
Once the cache directory configured, you can call the following methods:
-
jpeg($quality = 80)
: lookup or create a jpeg cache file on-the-fly -
gif()
: lookup or create a gif cache file on-the-fly -
png()
: lookup or create a png cache file on-the-fly -
guess($quality = 80)
: guesses the type (use the same as input) and lookup or create a cache file on-the-fly -
setPrettyName($prettyName, $prefix = true)
: sets a "pretty" name suffix for the file, if you want it to be more SEO-friendly. for instance, if you call it "Fancy Image", the cache will look like something/something-fancy-image.jpg. If$prefix
is passed tofalse
(defaulttrue
), the pretty name won't have any hash prefix. If you want to use non-latin1 pretty names, behat/transliterator package must be installed.
For instance:
<?php use Gregwar\Image\Image;
echo Image::open('test.png')
->sepia()
->jpeg();
//Outputs: cache/images/1/8/6/9/c/86e4532dbd9c073075ef08e9751fc9bc0f4.jpg
If the original file and operations do not change, the hashed value will be the same and the cache will not be generated again.
You can use this directly in an HTML document:
<?php use Gregwar\Image\Image;
// ...
<img src="<?php echo Image::open('image.jpg')->resize(150, 150)->jpeg(); ?>" />
// ...
This is powerful since if you change the original image or any of your code the cached hash will change and the file will be regenerated.
Writing image
You can also create your own image on-the-fly using drawing functions:
<?php
$img_src = Image::create(300, 300)
->fill(0xffaaaa) // Filling with a light red
->rectangle(0xff3333, 0, 100, 300, 200, true) // Drawing a red rectangle
// Writing "Hello $username !" on the picture using a custom TTF font file
->write('./fonts/CaviarDreams.ttf', 'Hello '.$username.'!', 150, 150, 20, 0, 'white', 'center')
->jpeg();
?>
<img src="<?= $img_src ?>" />
Using fallback image
If the image file doesn't exist, you can configure a fallback image that will be used by the class (note that this requires the cache directory to be available).
A default "error" image which is used is in images/error.jpg
, you can change it with:
<?php
$img->setFallback('/path/to/my/fallback.jpg');
Garbage Collect
To prevent the cache from growing forever, you can use the provided GarbageCollect class as below:
<?php use Gregwar\Image\GarbageCollect;
// This could be a cron called each day @3:00AM for instance
// Removes all the files from ../cache that are more than 30 days
// old. A verbose output will explain which files are deleted
GarbageCollect::dropOldFiles(__DIR__.'/../cache', 30, true);
Development
Gregwar\Image
is using PHP metaprogramming paradigms that makes it easy to enhance.
Each function that handles the image is implemented in an Adapter, this is where all the specific actions take place.
The Common
adapter is design to contain common abstract actions, while the
specific adapters (like GD
) are designed to contain actions specific to the low
level layer.
You can add your own methods by adding it in the corresponding adapter.
<?php
// In the adapter
private function myFilter()
{
$this->negate();
$this->sepia();
}
Which could be used on the Image
<?php
$image->myFilter();
You can also write your own adapter which could extend one of this repository and use it by calling setAdapter()
:
<?php
$image->setAdapter(new MyCustomAdapter);
License
Gregwar\Image
is under MIT License, please read the LICENSE file for further details.
Do not hesitate to fork this repository and customize it !
Top Related Projects
Manipulate images with an expressive API
PHP Object Oriented image manipulation library
A PHP class that makes working with images and GD as simple as possible.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot