Basic image copying

int imagecopy ( resource dest_image, resource source_image, int dest_x, int dest_y, int source_x, int source_y, int source_width, int source_height)

int imagecopymerge ( resource dest_image, resource source_image, int dest_x, int dest_y, int source_x, int source_y, int source_width, int source_height, int merge_percentage)

These two functions are both quite similar in that they copy one picture into another. Both of their first eight parameters are identical:

  • The destination image you're copying to

  • The source image you're copying from

  • The X co-ordinate you want to copy to

  • The Y co-ordinate you want to copy to

  • The X co-ordinate you want to copy from

  • The y co-ordinate you want to copy from

  • The width in pixels of the source image you want to copy

  • The height in pixels of the source image you want to copy

Parameters three and four allow you to position the source image where you want it on the destination image, and parameters five, six, seven, and eight allow you to define the rectangular area of the source image that you want to copy. Most of the time you will want to leave parameters five and six at 0 (copy from the top-left hand corner of the image), and parameters seven and eight at the width of the source image (the bottom-right corner of it) so that it copies the entire source image.

The way these functions differ is in the last parameter: imagecopy() always overwrites all the pixels in the destination with those of the source, whereas imagecopymerge() merges the destination pixels with the source pixels by the amount specified in the extra parameter: 0 means "keep the source picture fully", 100 means "overwrite with the source picture fully", and 50 means "mix the source and destination pixel colours equally". The imagecopy() function is therefore equivalent to calling imagecopymerge() and passing in 100 as the last parameter.

To get started, find two pictures to work with. In my example, I'll use stars.png and gradient.png. To get those two to merge we need a script like this one:

<?php
  $stars = imagecreatefrompng("stars.png");
  $gradient = imagecreatefrompng("gradient.png");
  imagecopymerge($stars, $gradient, 0, 0, 0, 0, 256, 256, 60);
  header('Content-type: image/png');
  imagepng($stars);
  imagedestroy($stars);
  imagedestroy($gradient);
?>

That merges the two at 60%, which gives slightly more prominence to the gradient.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Scaling and rotating >>

Previous chapter: Using brushes

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.