PHP : Masking image with GD

February 12th, 2009

My friend : Is it possible to use PHP and GD for croping image not in rectangle?

Me : Hmm, well so far I just play with GD only for creating thumbnail or crop an image. What exactly do you mean by that?

My friend : I need to crop an image and need the result in ellipse, so there will be an ellipse showing part of the image, and outside that ellipse should be transparent.

Me : What do you need that for?

My friend : Hmm, well just for some project I’m currently handle.

Me : I promise you nothing, but I’ll give it a shoot.

After looking back PHP GD documentation, here what come in my mind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
// load the image you want to crop
$image = imagecreatefrompng('sample.png');
 
$width = imagesx($image);
$height = imagesy($image);
 
// create masking
$mask = imagecreatetruecolor($width, $height);
$transparent = imagecolorallocate($mask, 255, 0, 0);
imagecolortransparent($mask, $transparent);
imagefilledellipse($mask, $width/2, $height/2, 100, 100, $transparent);
 
imagecopy($image, $mask, 0, 0, 0, 0, $width, $height);
imagecolortransparent($image, $red);
imagefill($image,0,0, $red);
 
// output and free memory
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
imagedestroy($mask);
?>

sample
Sample image
crop
Result

OK, I know it’s not an ellipse, but hey you can change that easy.

Related posts:

  1. Showing the weather with PHP and Google Weather API
  2. 101 PHP Tutorials for PHP Programmer Wannabe
  3. PHP Tips and Tricks
  4. 10 Practical PHP Regular Expression Recipes
  5. 4 Simple PHP RSS Parser

Tags:

2 Comments