我正在使用允許用戶上傳圖片的腳本。腳本調整大小並將圖像轉換爲JPEG。如何在用透明背景調整/轉換PNG圖像爲JPEG格式時用白色替換黑色背景。
我遇到的問題是上傳帶有透明度的PNG時,得到的JPEG圖像在黑色透明處出現。
如何編輯下面的腳本來替換黑色與白色?它已經爲GIF做了這個,但不是PNG的。
// RESIZE IMAGE AND PUT IN USER DIRECTORY
switch($this->file_ext)
{
case "gif":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefromgif($this->file_tempname);
$kek=imagecolorallocate($file, 255, 255, 255);
imagefill($file,0,0,$kek);
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "bmp":
$file = imagecreatetruecolor($width, $height);
$new = $this->imagecreatefrombmp($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "jpeg":
case "jpg":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefromjpeg($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
}
chmod($photo_dest, 0777);
return true;
}
我試圖編輯的情況下「PNG」:部分以匹配的情況下「GIF」的:代碼,但所得到的JPEG完全是白色。
UPDATE:
我固定它自己。
謝謝大家,爲了貢獻!
我代替:
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
有:
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
$kek=imagecolorallocate($file, 255, 255, 255);
imagefill($file,0,0,$kek);
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
這imagecolorallocate做什麼?它爲png接收4個參數,不應該爲alpha通道接收5個參數嗎? – Andre 2011-04-16 19:27:45
我沒有寫代碼,我是小白。我不知道你的問題的答案。抱歉,我無法幫助你幫助我。 – Jeff 2011-04-16 19:43:15
實際上這些都在手冊中。 _imagecolorallocate - 返回表示由給定的RGB分量組成的顏色的顏色標識符._對於alpha透明度,您需要使用'imagecolorallocatealpha',它確實會添加第5個參數:http://php.net/manual/en/ function.imagecolorallocatealpha.php – kasimir 2012-12-06 09:57:07