Crop or mask an image into a circle
What is the best way to crop or mask an image into a circular shape, using either ImageMagick or GD libraries? (Note, solution exists on "other" Q&A sites, but not StackOverflow)
Solution 1:
Here is one way with ImageMagick that will acomplish this without using a mask:
convert -size 200x200 xc:none -fill walter.jpg -draw "circle 100,100 100,1" circle_thumb.png
Solution 2:
For those who need to do this in pure PHP using Imagick, you will need to refer to this question : circularize an image with imagick
Hope this will help.
J.
Solution 3:
For those who wants a solution in PHP, providing the picture already cropped into a circle:
// convert the picture
$w = 640; $h=480; // original size
$original_path="/location/of/your/original-picture.jpg";
$dest_path="/location/of/your/picture-crop-transp.png";
$src = imagecreatefromstring(file_get_contents($original_path));
$newpic = imagecreatetruecolor($w,$h);
imagealphablending($newpic,false);
$transparent = imagecolorallocatealpha($newpic, 0, 0, 0, 127);
$r=$w/2;
for($x=0;$x<$w;$x++)
for($y=0;$y<$h;$y++){
$c = imagecolorat($src,$x,$y);
$_x = $x - $w/2;
$_y = $y - $h/2;
if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
imagesetpixel($newpic,$x,$y,$c);
}else{
imagesetpixel($newpic,$x,$y,$transparent);
}
}
imagesavealpha($newpic, true);
imagepng($newpic, $dest_path);
imagedestroy($newpic);
imagedestroy($src);