php改變圖像大小png背景變黑,php – 當將透明背景的PNG影象調整大小/轉換為JPEG時,如何用白色取代黑色背景…

我正在使用一個腳本,讓使用者上傳影象。腳本調整大小並將影象轉換為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是完全白色的。

更新:

我自己修好了

謝謝大家,貢獻!

我換了

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;