【问题标题】:Png black background when upload and resize image上传和调整图像大小时的PNG黑色背景
【发布时间】:2012-07-07 00:40:24
【问题描述】:

你能帮我写一下我的 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);


}

}

}

?>

【问题讨论】:

  • 研究imagepng()和imagesavealpaha()...

标签: php html image upload


【解决方案1】:

我认为此链接将回答您的问题: 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之前粘贴这个。

【讨论】:

  • 我试过这个,但没有用。 :(我什么都试过了。你能帮我改一下代码吗?我真的不知道如何解决它。:-/
  • 你帮助变形图片并使线条更硬。
  • 是的!它的工作,我将 imagejpeg 更改为 imagepng($tmp,$filename,9);谢谢。 :)
  • 哦,最后我没注意到:)。对你有好处
【解决方案2】:

如果您确实想保存为 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,但背景颜色将是白色而不是黑色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多