O'Reilly

Image Manipulation with PHP and the GD Library

By on  
David Walsh Sepia

Yeah, I'm a Photoshop wizard. I rock the selection tool. I crop like a farmer. I dominate the bucket tool. Hell, I even went as far as wielding the wizard wand selection tool once.

...OK I'm rubbish when it comes to Photoshop. I avoid opening the memory pig whenever possible. Many times I even need to automate image manipulation on customer websites. Luckily for a nerd like me, PHP's GD library allows me to systematically execute basic image manipulations without the need for Photoshop, GIMP, or other desktop tools.

The PHP -- Color to Greyscale

//to black and white
if(!file_exists('dw-bw.png')) {
	$img = imagecreatefrompng('dw-manipulate-me.png');
	imagefilter($img,IMG_FILTER_GRAYSCALE);
	imagepng($img,'db-bw.png');
	imagedestroy($img);
}

The PHP -- Color to Negative

//to negative
if(!file_exists('dw-negative.png')) {
	$img = imagecreatefrompng('dw-manipulate-me.png');
	imagefilter($img,IMG_FILTER_NEGATE);
	imagepng($img,'db-negative.png');
	imagedestroy($img);
}

The PHP -- Color to Sepia

//to black and white, then sepia
if(!file_exists('dw-sepia.png')) {
	$img = imagecreatefrompng('dw-manipulate-me.png');
	imagefilter($img,IMG_FILTER_GRAYSCALE);
	imagefilter($img,IMG_FILTER_COLORIZE,100,50,0);
	imagepng($img,'db-sepia.png');
	imagedestroy($img);
}

As you can see, PHP's GD library is a very competent, useful library. Though image libraries like ImageMagick get more credit than GD, GD is more than enough for the majority of designers and developers. Be sure to check out PHP image filters -- you can emboss images, fade images, and much more!

Track.js Error Reporting

Recent Features

  • LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • 5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

Incredible Demos

  • iPad Detection Using JavaScript or PHP

    The hottest device out there right now seems to be the iPad. iPad this, iPad that, iPod your mom. I'm underwhelmed with the device but that doesn't mean I shouldn't try to account for such devices on the websites I create. In Apple's...

  • Form Element AJAX Spinner Attachment Using MooTools

    Many times you'll see a form dynamically change available values based on the value of a form field. For example, a "State" field will change based on which Country a user selects. What annoys me about these forms is that they'll often do an...

Discussion

  1. M

    PHP + GD is powerful stuff indeed! Big ups for your blog, David, love your posts, especially the mootools-related stuff. Has helped me a lot.

  2. What a coincidence I also crop like a farmer ;)

  3. On a more serious note… the only issue I have with GD is that it can’t resize or handle animated gifs correctly…that’s a really big disadvantage… if you can teach me to resize an animated gif with php, I’ll sure bow down low ;)

  4. Hey, your Sepia-Logo looks really nice!
    You could use it in the case you make a redesign ;)

  5. Case for IMagick/et al:
    – same function to opens all image formats
    – memory management (helpful for very large images)

    //to black and white, then sepia
    if(!file_exists('dw-sepia.png')) {
        $img = Imagick('dw-manipulate-me.png');
        $img->setImageColorspace(GRAYColorspace);
        $img->sepiaToneImage(80);
        $img->writeImage('db-sepia.png');
        $img->destroy();
    }
    
  6. Hey David,

    Great stuff, I’m a huge fan of using the GD library to help achieve certain effects with images. I hope you don’t think I’m link whoring, but I wrote a 2 part article for ThemeForest on exactly this topic and thought you might find it interesting:

    http://blog.themeforest.net/tutorials/fun-with-the-php-gd-library-part-2/

    Keep up the great work!

    -Drew

  7. I’ve been wondering, but not enough to investigate, how to make images with rounded corners, like facebook — any idea how?

  8. I’ve used GD in the beginning, but as you go along with larger images, or other file formats, it’s better to leave GD alone and use ImageMagick. GD can also be a memory pig and the use for it is limited.
    With IMagick (in response to EmEhRKay) you can use masks to cut out your images (to make rounded corners). You can rotate, flip, flop, convert, resize, etc. within the blink of an eye. You can even create thumbnails of 500MB Illustrator documents if you want (not that that’s recommended) :-)

  9. Awesome Drew!

  10. Nice fast way to deal with simple changes to images. Thanks.

  11. Do you know how to create “Virtual Product Samples” with any PHP script? are you aware of any such script which helps in creating 3D samples of various images and finally combined as one virtual sample.

  12. this looks great but you should check out my site, there so much easier way to achieve the same!

  13. Hi,

    Nice codes here, but i want to block the adult images from my site http://www.neatstat.com and only want to display the good, clean images. How do I block these adult images?

    Do you have any image filter to do that like bad words filter?

    Any help will be much appreciated.

    Thanks
    Pummy

  14. Thanks! I was looking for a way to convert a captured image to sepia using the GD library, and you had the perfect answer for me.

  15. Post seems like too old to ask a question. But how can I use it for jpg files.
    I tried this

    if(!file_exists('source.jpg')) {
    $img = imagecreatefromjpeg('source.jpg');
    imagefilter($img,IMG_FILTER_GRAYSCALE);
    imagefilter($img,IMG_FILTER_COLORIZE,100,50,0);
    imagejpeg($img,'output.jpg');
    imagedestroy($img);
    }

    its not working.
    I want to use this for jpg images, should I convert png files before using

    imagefilter($img,IMG_FILTER_GRAYSCALE);

    ?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...

  • Copy a Directory from Command Line

    Copying a directory for the sake of backup is something I do often, especially when I'm trying to figure out why something isn't working when I use an external library.  I'll copy the directory structure as a backup, mess around with the original source until I find a solution,...