Currently Browsing: Home » Manipulating Images using the PHP GD Library

Manipulating Images using the PHP GD Library

PHP is a very versatile programming language with many available libraries. A popular one, the GD Library, enables you to manipulate images. This post will take you through the process of manipulating images using the PHP GD library.

To begin any manipulation, one must access an image resource. Here are four functions to accomplish this:

  • imagecreate( int $width, int $height ) – creates a blank image resource of the specified size.
  • imagecreatefromgif( string $filename ) – creates an image resource from the specified GIF format file.
  • imagecreatefromjpeg( string $filename ) – creates an image resource from the specified JPEG format file.
  • imagecreatefrompng( string $filename ) – creates an image resource from the specified PNG format file.

All of these functions return ‘resources’, which are used in the GD Library as parameters.

Let us start off with an image called sunburst.jpg. To obtain the resource, use the following snippet:


<?php
	$img = imagecreatefromjpeg( 'sunburst.jpg' );
?>

We shall now proceed on to two more functions, imagesx( resource $image ) and imagesy( resource $image ). imagesx returns the image’s width and imagesy returns the image’s height.

sunburst.jpg has the dimensions 549×359, so the following code:


	echo imagesx( $img ), ' ', imagesy( $img );

will print 549 359.

What good would this image be if we can’t save or display it? The following functions output the resource to the browser or file:

  • imagegif( resource $image [, string $filename ] )
  • imagejpeg( resource $image [, string $filename ] )
  • imagegif( resource $image [, string $filename ] )

For example, if we were to use these functions without the optional parameter $filename:


<?php
	$image = imagecreatefromjpeg( 'sunburst.jpg' );
	header( 'Content-type: image/jpeg' );
	imagejpeg( $image );
	imagedestroy( $image );
?>

sunburst.jpg would be displayed in the browser.

On the other hand, using a $filename:


<?php
	$image = imagecreatefromjpeg( 'sunburst.jpg' );
	imagejpeg( $image, 'sunburstcopy.jpg' );
	imagedestroy( $image );
?>

would output the image to sunburstcopy.jpg.

The function imagedestroy( resource $image ) frees up memory. Remember that each pixel of an image takes up one byte in memory; having several large images open can crash a server. As such, it is always good practice to free up this space.

We can now move to more advanced manipulation:

  • imagecopy( resource $dst_im, resource $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h ) – copies an image or part of an image to another image.
  • imagecopymerge( resource $dst_im, resource $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h, int $pct ) – copies an image or part of an image to another image with transparency.
  • imagecopy( resource $dst_im, resource $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h ) – copies an image or part of an image to another image with resampling.

Here are some demonstrations of the above functions.

Imagecopy

Code:


<?php
	$src = imagecreatefromjpeg( 'sunburst.jpg' );
	$dst = imagecreatefromjpeg( 'orchid.jpg' );
	imagecopy( $dst, $src, 10, 10, 0, 0, 200, 200 );
	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $src );
	imagedestroy( $dst );
?>

This copies a 200px by 200px square from $src with the top-left corner at (0, 0) to $dst at (10, 10).

Product:

The result of using imagecopy

The result of using imagecopy

Imagecopymerge

Code:


<?php
	$src = imagecreatefromjpeg( 'sunburst.jpg' );
	$dst = imagecreatefromjpeg( 'orchid.jpg' );
	imagecopymerge( $dst, $src, 10, 10, 0, 0, 200, 200, 50 );
	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $src );
	imagedestroy( $dst );
?>

This applies the same effects as the previous example, but with 50% opacity.

Product:

The result of imagecopymerge

The result of using imagecopymerge

Imagecopyresampled

Code:


<?php
	$src = imagecreatefromjpeg( 'sunburst.jpg' );
	$dst = imagecreatefromjpeg( 'orchid.jpg' );
	imagecopyresampled( $dst, $src, 10, 10, 0, 0, 200, 200, 300, 300 );
	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $src );
	imagedestroy( $dst );
?>

This code copies a 300px by 300px square from $src with the top-left corner at (0, 0), resampled to 200px by 100px, to $dst at (10, 10).

Product:

The result of using imagecopyresampled

The result of using imagecopyresampled

Practical applications for these functions:

Imagecopy – cropped thumbnail

Let us create a 100×100 thumbnail of sunburst.jpg, cropped from the center:


<?php
	$src = imagecreatefromjpeg( 'sunburst.jpg' );
	$dst = imagecreate( 100, 100 ); # Create a blank target image

	# Calculate top-left coordinates of the source by getting the
	# center coordinates and then subtracting half the target width
	$src_x = ( imagesx( $src ) / 2 ) - 50;
	$src_y = ( imagesy( $src ) / 2 ) - 50;

	imagecopy( $dst, $src, 0, 0, $src_x, $src_y, 100, 100 );

	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $src );
	imagedestroy( $dst );
?>

The product:

Cropped Thumbnail

Cropped Thumbnail

Imagecopymerge – watermark

What if I have a logo that needs to be embedded onto my image? The following would suffice:


<?php
	$mark = imagecreatefromjpeg( 'logo.jpg' );
	$dst = imagecreatefromjpeg( 'sunburst.jpg' );

	# Calculate top-left coordinates of the destination by getting
	# getting the bottom coordinates (width, height) and subtracting
	# the width and height of the watermark
	$dst_x = imagesx( $dst ) - imagesx( $mark );
	$dst_y = imagesy( $dst ) - imagesy( $mark );

	imagecopymerge( $dst, $mark, $dst_x, $dst_y, 0, 0, imagesx( $mark ), imagesy( $mark), 50 );

	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $mark );
	imagedestroy( $dst );
?>

The product:

Watermarked image

Watermarked image

Imagecopyresampled – resampled thumbnail

This creates a thumbnail of the original image resampled to a maximum dimension of 100px. You may recognize this from Create a Simple Picture Gallery with PHP.


<?php
	$src = imagecreatefromjpeg( 'sunburst.jpg' );

	# Calculate width and height based on larger dimension
	if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
		$newW = $oldW * (100 / $oldH);
		$newH = 100;
	} else {
		$newW = 100;
		$newH = $oldH * (100 / $oldW);
	}

	# Create a blank target image
	$dst = imagecreate( $newW, $newH );

	imagecopyresampled( $dst, $src, 0, 0, 0, 0, $newW, $newH imagesx( $src ), imagesy( $src ) );

	header( 'Content-type: image/jpeg' );
	imagejpeg( $dst );
	imagedestroy( $src );
	imagedestroy( $dst );
?>

The product:

Resampled Thumbnail

Resampled Thumbnail

Cool, eh? Have fun manipulating images.

Tags: ,

This entry was posted on Tuesday, March 17th, 2009 at 05:34:35. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

11 Responses to “Manipulating Images using the PHP GD Library”

  1. Max says:

    Great tutorials on Your blog!! Thank You! Always useful!!

  2. carlo says:

    very good article! Thanks
    Carlo

  3. Deca says:

    Great tutorials!

    If been reading and trying your tutorial “Create a Simple Picture Gallery using PHP” and just like kloc i want my thumbnails to be square/cropped instead of there max height/width to be 100.

    So I think i would be wanting it like the Imagecopy, but I can’t seem to make it work in the Simple Picture Gallery, I’m not very good at PHP.

  4. Patrick Lin says:

    Hello Deca,

    The part you need to replace in Simple Picture Gallery is this:

    	if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
    		$newW = $oldW * ($max_width / $oldH);
    		$newH = $max_height;
    	} else {
    		$newW = $max_width;
    		$newH = $oldH * ($max_height / $oldW);
    	}
    	$new = imagecreatetruecolor($newW, $newH);
    	imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
    

    What you would want to replace it with is this:

    	$new = imagecreate( $max_width, $max_height ); # Create a blank target image
    
    	# Calculate top-left coordinates of the source by getting the
    	# center coordinates and then subtracting half the target width
    	$src_x = ( imagesx( $src ) / 2 ) - ( $max_width / 2 );
    	$src_y = ( imagesy( $src ) / 2 ) - ( $max_height / 2 );
    
    	imagecopy( $new, $src, 0, 0, $src_x, $src_y, $max_width, $max_height );
    
  5. Deca says:

    Great! Thanks,

    works like a charm!

  6. Justin says:

    So here is my code:

    <?php
    $src = imagecreatefromjpeg( ‘sunburst.jpg’ );

    # Calculate width and height based on larger dimension
    if ( ($oldW = imagesx($src))

    This works perfectly. Like the others Im trying to create a thumbnail exactly 100X100. When I replace what you told me to above. This is what I have now.

    I see that $dst doesnt exist anymore, so even if I get rid of those and replace with

    imagejpeg( $new );
    imagedestroy( $src );
    imagedestroy( $new );

    still does not work. do you by chance see where im going wrong.

  7. Justin says:

    I got it. the problem is. you have to set your max width and height.

  8. G says:

    After the image is resampled – using Imagecopyresampled, How do I save it to a different folder on the browser?
    Lets say initial file is upload to folder A – after the image is resampled.. how do I move it to folder B – under same parent folder..
    - This is what I have for now…
    $demoImage = getcwd().”/demo_files/”;
    $finalImage = getcwd().”/Final/”;
    $src = “demo_files/”.$_GET['pic'];
    $img_r = imagecreatefromjpeg($src);
    $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

    imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
    $targ_w,$targ_h,$_POST['w'],$_POST['h']);
    header(‘Content-type: image/jpeg’);
    imagejpeg($dst_r,null,$jpeg_quality);
    copy($dst_r, $finalImage.$_GET['pic']);

  9. OS says:

    The following works well…

    But only if this is the only object being generated by the browser.
    what if I want to show the images in a page.
    Do I have to save the file as a temp.jpg and then ?
    or is there a way to generate the file and send it to the browser without storing it on the server.

  1. 網站製作學習誌 » [Web] 連結分享

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.