2011-12-08 176 views
8

圖像如何創建GDlib的圖像與透明背景?如何創建帶有透明背景

header('content-type: image/png'); 

$image = imagecreatetruecolor(900, 350); 

imagealphablending($image, true); 
imagesavealpha($image, true); 

$text_color = imagecolorallocate($image, 0, 51, 102); 
imagestring($image,2,4,4,'Test',$text_color); 

imagepng($image); 
imagedestroy($image); 

這裏的背景是黑色

+0

你必須使用'imagefill'並填寫與分配的顏色(imagecolorallocatealpha)有一個Alpha設置爲0。 –

+0

@noice,創建答案..它的工作原理 – clarkk

+0

@NoICE:分配的顏色是沒有必要的,它是一個真實的彩色圖像。 – mvds

回答

7

你必須使用imagefill()並填寫與分配的顏色(imagecolorallocatealpha())作爲@mvds說,已經設置透明度爲0。

,「分配是沒有必要的」,如果是真彩色圖像(24或32位),它僅僅是一個整數,這樣你就可以直接進入imagefill()該整數。

PHP的確會在後臺運行的真彩色圖像當你調用imagecolorallocate()是同樣的事情 - 它只是返回計算的整數。

21

imagestring之前添加一行

imagefill($image,0,0,0x7fff0000); 

的地方,這將是透明的。

0x7fff0000分解成:

alpha = 0x7f 
red = 0xff 
green = 0x00 
blue = 0x00 

這是完全透明的。

+0

你讓我的一天:)謝謝! –

8

事情是這樣的......

$im = @imagecreatetruecolor(100, 25); 
# important part one 
imagesavealpha($im, true); 
imagealphablending($im, false); 
# important part two 
$white = imagecolorallocatealpha($im, 255, 255, 255, 127); 
imagefill($im, 0, 0, $white); 
# do whatever you want with transparent image 
$lime = imagecolorallocate($im, 204, 255, 51); 
imagettftext($im, $font, 0, 0, $font - 3, $lime, "captcha.ttf", $string); 
header("Content-type: image/png"); 
imagepng($im); 
imagedestroy($im); 
+0

這使我的透明背景的白色而不是黑色:(因爲他們不爲未來的讀者多的信息請提供一些解釋,你所寫的內容 – Bolas

1

有時你不會得到透明圖像由於PNG圖像的問題。圖像應採用以下推薦格式之一:

PNG-8 (recommended) 
Colors: 256 or less 
Transparency: On/Off 
GIF 
Colors: 256 or less 
Transparency: On/Off 
JPEG 
Colors: True color 
Transparency: n/a 

imagecopymerge函數無法正確處理PNG-24圖像;因此不推薦。

如果您在使用Adobe Photoshop創建水印圖像,建議您使用以下設置「另存爲網頁」命令:

File Format: PNG-8, non-interlaced 
Color Reduction: Selective, 256 colors 
Dithering: Diffusion, 88% 
Transparency: On, Matte: None 
Transparency Dither: Diffusion Transparency Dither, 100% 
6

這應該工作:

$img = imagecreatetruecolor(900, 350); 

$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back 
imagefill($img, 0, 0, $color); 
imagesavealpha($img, true); 
4

這應該工作。它爲我工作。

$thumb = imagecreatetruecolor($newwidth,$newheight); 
$transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127); 
imagefill($thumb, 0, 0, $transparent); 
imagesavealpha($thumb, true); 
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
imagepng($thumb, $output_dir); 
+0

唯一代碼的答案的arent鼓勵'救了我的一天。文件說, :'將該標誌設置爲試圖保存完整的alpha通道信息(相對於單一顏色透明度)保存PNG images'時 – WhatsThePoint

+0

功能'imagesavealpha() –