我在使用PHP調整圖片大小時發生問題,特別是使用帶有透明背景的PNG文件,而不是保留透明背景,將其變成黑色背景。我怎樣才能解決這個問題?如何在使用PHP調整大小時在PNG上保留透明背景?
這是調整腳本:
<?php
class resize{
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if($this->image_type == IMAGETYPE_JPEG) {
$this->image = imagecreatefromjpeg($filename);
} elseif($this->image_type == IMAGETYPE_GIF) {
$this->image = imagecreatefromgif($filename);
} elseif($this->image_type == IMAGETYPE_PNG) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=85, $permissions=null) {
if($image_type == IMAGETYPE_JPEG) {
imagejpeg($this->image,$filename,$compression);
} elseif($image_type == IMAGETYPE_GIF) {
imagegif($this->image,$filename);
} elseif($image_type == IMAGETYPE_PNG) {
imagepng($this->image,$filename);
}
if($permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if($image_type == IMAGETYPE_JPEG) {
imagejpeg($this->image);
} elseif($image_type == IMAGETYPE_GIF) {
imagegif($this->image);
} elseif($image_type == IMAGETYPE_PNG) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height/$this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width/$this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
這是我怎麼稱呼它:
$picture_directory="images/" . $_FILES["file"]["name"];
include('arqinc/resizing.php');
$image = new resize();
$image->load($picture_directory);
$image->resize(660,780);
$image->save($picture_directory);
編輯:
香港專業教育學院改變了我的大小調整功能,這一點:
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
$transparent=imagefill($new_image, 0, 0, imagecolorallocatealpha($new_image, 255, 255, 255, 127));
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
但現在它保持背景爲白色,不透明。
編輯2:
解決,這個調整大小功能壞了,這一個完美的作品:
http://mediumexposure.com/smart-image-resizing-while-preserving-transparency-php-and-gd-library/
感謝 Tahir Yasin用於連接它:d
嘿感謝aswner; 但我認爲我做錯了什麼,或者把它放在錯誤的路線上,你能告訴我我要把它放在哪裏嗎? – user1773801
請把它放在imagecolorallocatealpha()函數之前。 –
我的上帝我很生氣,我嘗試過所有的東西,沒有任何工作:@ – user1773801