简体   繁体   中英

Crop image in PHP without mask

I'm trying to crop an image in PHP from a square into a circle. I've seen a lot of solutions online that accomplish the getting of a circular image by masking the initial image and making the corners different colors. However, this is problematic, as setting the corners to transparent merely results in the initial square image for me. For example, the below code results in a circular image with pink corners

以下代码的结果

$image_name = $_POST['filepath'];
$source_image = imagecreatefrompng($image_name);

$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$dest_imagex = $_POST['width'];
$dest_imagey = $_POST['height'];
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagealphablending($dest_image, true);
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

header("Content-Type: image/jpeg");

// create masking
$mask = imagecreatetruecolor($source_imagex, $source_imagey);
$mask = imagecreatetruecolor($dest_imagex, $dest_imagey);
$pink = imagecolorallocate($mask, 255, 0, 255);
imagefill($mask, 0, 0, $pink);
$black = imagecolorallocate($mask, 0, 0, 0);
imagecolortransparent($mask, $black);
imagefilledellipse($mask, $dest_imagex/2, $dest_imagey/2, $dest_imagex, $dest_imagey, $black);
imagecopy($dest_image, $mask, 0, 0, 0, 0, $dest_imagex, $dest_imagey);
imagecolortransparent($dest_image, $pink);
imagejpeg($dest_image, NULL);

Is there a way to crop an image in PHP such that the edges are actually removed?

You have to set your corner to transparent and save it as a png (you can use a php library like wideimage or imagemagick, it will do this easily for you). An image file is always rectangular, if it has another shape it's because the other parts are transparent.

fyi, to make it a png... first change to this:

header("Content-Type: image/png");

and then this(at the end of your code):

imagepng($dest_image, NULL);  //instead of imagejpeg()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM