Skip to content

Instantly share code, notes, and snippets.

@azinkey
Last active January 11, 2018 12:05
Show Gist options
  • Save azinkey/6634046 to your computer and use it in GitHub Desktop.
Save azinkey/6634046 to your computer and use it in GitHub Desktop.
Crop Image as shape with alpha transparency using PHP GD
<?php
/**
* PHP GD use one image to mask another image including transparency
* @param (GD)resource $picture orignal reference image
* @param (GD)resource $mask shape black/white image
* @return (GD)resource output shape image resource
*
* http://stackoverflow.com/questions/7203160/
*
*/
private function _cropShape(&$picture, $mask) {
// Get sizes and set up new picture
$xSize = imagesx($picture);
$ySize = imagesy($picture);
$newPicture = imagecreatetruecolor($xSize, $ySize);
imagesavealpha($newPicture, true);
imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 255, 255, 255, 127));
// Resize mask if necessary
if ($xSize != imagesx($mask) || $ySize != imagesy($mask)) {
$tempPic = imagecreatetruecolor($xSize, $ySize);
imagecopyresampled($tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx($mask), imagesy($mask));
imagedestroy($mask);
$mask = $tempPic;
}
// Perform pixel-based alpha map application
for ($x = 0; $x < $xSize; $x++) {
for ($y = 0; $y < $ySize; $y++) {
$alpha = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
$alpha = 127 - floor($alpha['red'] / 2);
$color = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $alpha));
}
}
$picture = $newPicture;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment