一種不同的方式來獲得類似的效果是PNG文件具有獨特的背景顏色粘貼到一個新的形象,以暫時刪除的透明度,並設置透明改爲將png圖像的顏色改爲黑色圓圈顏色。然後,當您將它放在jpeg圖像上時,將新的透明顏色設置爲蒙版的顏色。
// Load the Black Circle PNG image
$png = imagecreatefrompng('mask.png');
$width = imagesx($png);
$height = imagesy($png);
// Create a mask image
$mask = imagecreatetruecolor($width, $height);
// We'll use Magenta as our new transparent colour - set it as the solid background colour.
$magenta = imagecolorallocate($mask, 255, 0, 255);
imagefill($mask, 0, 0, $magenta);
// Copy the png image onto the mask. Destroy it to free up memory.
imagecopyresampled($mask, $png, 0, 0, 0, 0, $width, $height, $width, $height);
imagedestroy($png);
// Set the black portion of the mask to transparent.
$black = imagecolorallocate($mask, 0, 0, 0);
imagecolortransparent($mask, $black);
// Load JPEG image.
$jpg = imagecreatefromjpeg('image.jpg');
$j_width = imagesx($jpg);
$j_height = imagesx($jpg);
// Enable alpha blending and copy the png image
imagealphablending($jpg, true);
imagecopyresampled($jpg, $mask, 0, 0, 0, 0, $j_width, $j_height, $width, $height);
imagedestroy($mask);
// Set the new transparent colour and output new image to browser as a png.
$magenta = imagecolorallocate($jpg, 255, 0, 255);
imagecolortransparent($jpg, $magenta);
imagepng($jpg);
如果再採樣或半透明像素越來越你下來,而不是使用一個PNG作爲掩模,則可以禁用共混和繪製的透明形狀到$mask
圖像來代替。
// Load JPEG Image.
$jpg = imagecreatefromjpeg('image.jpg');
$width = imagesx($jpg);
$height = imagesx($jpg);
// Create mask at same size with an opaque background.
$mask = imagecreatetruecolor($width, $height);
$magenta = imagecolorallocate($mask, 255, 0, 255);
imagefill($mask, 0, 0, $magenta);
// Disable alpha blending and draw a transparent shape onto the mask.
$transparent = imagecolorallocatealpha($mask, 255, 255, 255, 127);
imagealphablending($mask, false);
imagefilledellipse($mask, round($width/2), round($height/2), $width, $height, $transparent);
// Paste the mask onto the original image and set the new transparent colour.
imagealphablending($jpg, true);
imagecopyresampled($jpg, $mask, 0, 0, 0, 0, $width, $height, $width, $height);
imagedestroy($mask);
$magenta = imagecolorallocate($jpg, 255, 0, 255);
imagecolortransparent($jpg, $magenta);
// Output new image to browser as a png.
imagepng($jpg);
注意:上面的代碼沒有經過測試,但應該有希望做你需要的。
謝謝,這真的有幫助 – Matt
我知道這篇文章已經關閉了一段時間,但運行時看起來像是什麼時候你們運行這個腳本?它平均需要20秒左右...我的源代碼/面具圖像是250 x 170px ...是關於你們正在得到什麼? –
無視,不知道我做錯了什麼,但它現在很好用:P謝謝你們! –