人氣 374°c

修正PHP產生ICO源碼png和webp圖片背景透明

PHP的Favicon產生ICO圖標,在網上找到的PHP源碼文件,大部份代碼如出一轍,很多都帶有相同一個BUG,用PNG或WEBP圖片產生出來的 .ico 網頁圖示,都不是透明底,是黑色背景。

經過查閱大量的資料,多次嘗試(因為技術太烏,只能一遍遍的調試)最終解決了這個問題,將解決方法過程記錄如下:請看圖片▼

ICO 透明製作!

原來的 2 行代碼:

$tmp = imagecreatetruecolor($newwidth,$newheight); //創建新畫布
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height); //處理圖片到新尺寸

需要將以上兩行代碼修改。

找:

$tmp = imagecreatetruecolor($newwidth,$newheight);

修改為:

/* --- 用以處理縮放gif和png圖透明背景變黑色問題 開始 --- */
$tmp = imagecreatetruecolor($newwidth,$newheight);
$color = imagecolorallocatealpha($tmp,0, 0, 0, 127);
imagecolortransparent($tmp,$color);
imagefill($tmp,0,0,$color);
/* --- 用以處理縮放gif和png圖透明背景變黑色問題 結束 --- */

找:

imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);

修改為:

imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
imagesavealpha($tmp, true); //注意這裡還有一句!

高潮來了!!在網上找到的都是這些教程!!,我按照位置放上去了,竟然沒用!!黑色背景是消失了,但是生成的又是白色背景的圖標,仍然不是透明的!!

後來才發現下面還有一個函數:

imagejpeg($tmp,$directory.$filename,100)

這個是生成 .jpeg 的怎麽可能會透明!!

所以改成了:

imagepng($tmp,$directory.$filename,100)

TNND竟然直接報錯!!

imagepng(): gd-png: fatal libpng error: Incompatible libpng version in application and library

原因:JPEG圖像產生的圖像的質量的是一個範圍從0(最低質量,最小的文件大小)到100(最高質量,最大文件大小)。而出現這一錯誤的原因是 ImagePNG 生成圖像的質量範圍從 0 至 9 的,傳入的這個範圍以外的參數則該函數不會工作。

所以簡單地將值更改為 0 到 9 之間,錯誤會自行消失。

最終將此函數改為如下即可正常產生背景透明 ICO圖標了。

imagepng($tmp,$directory.$filename,9)

花了我整整一個上午的時間。需要的請拿走!

共修改 3 個地方,最終效果如下:

if($image){
list($width,$height) = getimagesize($postvars["image_tmp"]);
$newwidth = $postvars["image_dimensions"];
$newheight = $postvars["image_dimensions"];
$tmp = imagecreatetruecolor($newwidth,$newheight);

/* --- 用以處理縮放gif和png圖透明背景變黑色問題 開始 --- */
$color = imagecolorallocatealpha($tmp,0, 0, 0, 127);
imagecolortransparent($tmp,$color);
imagefill($tmp,0,0,$color);
/* --- 用以處理縮放gif和png圖透明背景變黑色問題 結束 --- */
	
// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
imagesavealpha($tmp, true); //注意這裡還有一句!
			
// Create image file with 100% quality.
if(is_dir($directory)){
if(is_writable($directory)){
imagepng($tmp,$directory.$filename,9) or die('Could not make image file');
if(file_exists($directory.$filename)){	
// Image created, now rename it to its
$ext_pos = strpos($rand.$postvars["image"],"." . $ext);
$strip_ext = substr($rand.$postvars["image"],0,$ext_pos);
// Rename image to .ico file
rename($directory.$filename,$directory.$strip_ext.".ico");

請看圖片:

線上Favicon產生器:ifreesite.com/favicon

標籤: