PHP Image Class

by Lasantha Samarakoon on Saturday, February 19, 2011

Today I am going to give you something that I have created using PHP. It is a simple PHP class that can be used to manipulate images easily in an object oriented way. I created this by using basic functions in PHP GD library.


You can download the ZIP archive containing PHP classes by clicking here.


I would like to distribute this using GNU/GPL license, so you can add more functionality into it and enhance my basic product.


This class allows you to manipulate JPEG, GIF and PNG files. It allows image resizing, cropping, merging, rendering, saving and applying filters.


Open image

new Image(path-to-file)


$img = new Image('/home/user/foo.jpg');

You can specify the relative or absolute path as the parameter. Note that this method may throw FileNotFoundException, whenever the method fails to locate the file on the target location.

Resize image

resize(width, height, [unit = ‘px’, [keep-aspect-ratio = false]])


$img->resize(800, 600, 'px', true);

Resize method allows you to resize image file. Unit can be either ‘px’ or ‘%’.

Crop image

crop(x, y, width, height)


$img->crop(100, 50, 600, 500);

Crop method allows cropping the image. It takes 4 parameters x coordinate, y coordinate, width and the height.

Merge images

merge(image-object, [x = 0, [y = 0, [opacity = 100]]])


$anotherImg = new Image('/home/user/bar.jpg');
$img->merge($anotherImg, 100, 100, 75);

Merge method can be used to merge to image objects. That means this method results merger of 2 images. Again it takes 4 parameters; Image object, x coordinate, y coordinate and opacity value. Opacity ranges from 0 to 100, which 0 means transparent and 100 means full opaque.

Save image

save(destination, [file-type = ‘jpg’])


$img->save('/home/user/foo_edit.png', 'png');

This class can be used to save the resulting image on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.

Render image

render([file-type = ‘jpg’])



Render method allows rendering resulting image on the browser without saving it on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.


Available filters to apply on images are as follows.

  • negative()
  • grayscale()
  • detectEdges()
  • emboss()
  • gaussianBlur()
  • selectiveBlur()
  • brightness(value)
  • contrast(value)
  • colorize(r, g, b, [alpha = 0])
  • sketchy()
  • smooth(value)
  • sephia()