2014-10-02 79 views
0

我試圖在PHP中將圖像從一個正方形裁剪成一個圓。我在網上看到很多解決方案,通過掩蓋初始圖像並使角落變成不同的顏色來完成獲取圓形圖像。但是,這是有問題的,因爲將角設置爲透明僅僅會導致我的初始方形圖像。例如,下面的代碼的結果的圓形圖像與粉紅色的角落在沒有蒙版的情況下在PHP中裁剪圖像

result of below code

$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); 

有一種方法以裁剪,使得邊緣被實際刪除在PHP的圖像?

+0

這有什麼錯用CSS爲了這? '邊界半徑:50%'應該達到你所需要的。 – BenM 2014-10-02 22:41:06

+0

我與iOS接口,所以我只需要返回圓形圖像 – user3781236 2014-10-02 22:45:13

+0

然後有什麼問題:'cell.yourImageView.layer.cornerRadius = cell.yourImageView.frame.size.height/2; cell.yourImageView.layer.masksToBounds = YES; cell.yourImageView.layer.borderWidth = 0;'? – BenM 2014-10-02 22:46:12

回答

0

你必須將你的角落設置爲透明並將其保存爲PNG(你可以使用像wideimage或imagemagick這樣的php庫,它會爲你輕鬆做到這一點)。一個圖像文件總是矩形的,如果它具有另一種形狀,那是因爲其他部分是透明的。

0

僅供參考,以使它成爲一個PNG ... 第一改成這樣:

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

,然後這個(在你的代碼的末尾):

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