簡體   English   中英

上傳和調整圖片大小時PNG黑色背景

[英]Png black background when upload and resize image

您可以用我的PHP代碼幫助我嗎?

我不知道如何使我的圖片透明。 上傳后背景為黑色。 我在這里有代碼。 (以及一些小帖子和內容的文字)

謝謝你

<?php
function zmensi_obrazok($image_max_width, $image_max_height, $obrazok, $obrazok_tmp, $obrazok_size, $filename){

$postvars          = array(
"image"            => $obrazok,
"image_tmp"        => $obrazok_tmp,
"image_size"       => $obrazok_size,
"image_max_width"  => $image_max_width,
"image_max_height" => $image_max_height
);

$valid_exts = array("jpg","jpeg","png");
$ext = end(explode(".",strtolower($obrazok)));
if($postvars["image_size"] <= 1024000){


if(in_array($ext,$valid_exts)){




if($ext == "jpg" || $ext == "jpeg"){
$image = imagecreatefromjpeg($postvars["image_tmp"]);
}
else if($ext == "png"){
$image = imagecreatefrompng($postvars["image_tmp"]);
}


list($width,$height) = getimagesize($postvars["image_tmp"]);


$old_width      = imagesx($image);
$old_height     = imagesy($image);
$scale          = min($postvars["image_max_width"]/$old_width, $postvars["image_max_height"]/$old_height);
$new_width      = ceil($scale*$old_width);
$new_height     = ceil($scale*$old_height);


$tmp = imagecreatetruecolor($new_width,$new_height);

imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);


imagejpeg($tmp,$filename,100);
return "";
imagedestroy($image);
imagedestroy($tmp);


}

}

}

?>

我認為此鏈接將回答您的問題: http : //www.php.net/manual/pl/function.imagecopyresampled.php#104028

在您的代碼中,答案將類似於:

// preserve transparency
  if($ext == "gif" or $ext == "png"){
    imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
  }

在執行imagecopyresampled之前粘貼此內容。

如果您確實想保存為JPEG而不是保存為PNG,則可以在復制之前將目標圖像的背景色更改為白色:

$tmp = imagecreatetruecolor($new_width,$new_height);
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);

然后,您將得到沒有任何透明度的JPEG,但是背景顏色將是白色而不是黑色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM