December 3, 2017
Transparent Circular Crop using PHP GD
In this article, I will show how to crop an image to transparent circular image using PHP GD Library.
What is GD Library?
The GD library is a graphics drawing library that provides tools for manipulating image data. The GD library is used to process images for generating gallery preview and thumbnail size images automatically.
The image functions in PHP GD library can be used to work with the image files.
Example of PNG Creation with PHP:
<?php header("Content-type: image/png"); $string = $_GET['text']; $im = imagecreatefrompng("images/button1.png"); $orange = imagecolorallocate($im, 220, 210, 60); $px = (imagesx($im) - 7.5 * strlen($string)) / 2; imagestring($im, 3, $px, 9, $string, $orange); imagepng($im); imagedestroy($im); ?>
Transparent Circular Crop
Simple PHP Script to crop an image to transparent circular image:
<?php $filename = "images/".$_GET['image'].".jpg"; $image_s = imagecreatefromstring(file_get_contents($filename)); $width = imagesx($image_s); $height = imagesy($image_s); $newwidth = 285; $newheight = 285; $image = imagecreatetruecolor($newwidth, $newheight); imagealphablending($image, true); imagecopyresampled($image, $image_s, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); //create masking $mask = imagecreatetruecolor($newwidth, $newheight); $transparent = imagecolorallocate($mask, 255, 0, 0); imagecolortransparent($mask,$transparent); imagefilledellipse($mask, $newwidth/2, $newheight/2, $newwidth, $newheight, $transparent); $red = imagecolorallocate($mask, 0, 0, 0); imagecopymerge($image, $mask, 0, 0, 0, 0, $newwidth, $newheight, 100); imagecolortransparent($image,$red); imagefill($image, 0, 0, $red); //output, save and free memory header('Content-type: image/png'); imagepng($image); imagepng($image,'output.png'); imagedestroy($image); imagedestroy($mask);
You May Like: Image Steganography: Hiding text in images using PHP
For full instructions and code, you can follow this video:
3 Comments
Thank you.
Hi thanks for this script.
But the generated png is not transparent, if I use it in other script or open it with Photoshop, the borders are black.
Is it possible to fix that ?
Thanks