gpt4 book ai didi

php - 如何允许使用 php 上传透明 gif 或 png

转载 作者:行者123 更新时间:2023-12-04 14:30:24 25 4
gpt4 key购买 nike

我在下面有这个功能,可以让我调整上传图片的大小,

function resize_image($image,$width,$height,$scale) 
{
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);

switch($imageType)
{
case "image/gif":
$source = imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($image);
break;
}

imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);

switch($imageType)
{
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}

chmod($image, 0777);
return $image;
}

但是这个函数有一个问题,就是当我有一个透明背景的png或gif时,它不能创建透明度。

如何修复此功能以允许 php 透明化?

最佳答案

这是我的答案,

# This is the resizing/resampling/transparency-preserving magic
if ( ($imageType == "image/gif") || ($imageType == "image/png") )
{
$transindex = imagecolortransparent($source);

if($transindex >= 0)
{
$transcol = imagecolorsforindex($source, $transindex);
$transindex = imagecolorallocatealpha($newImage, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
imagefill($newImage, 0, 0, $transindex);
imagecolortransparent($newImage, $transindex);
}

elseif ($imageType == "image/png" || $imageType == "image/x-png")
{
imagealphablending($newImage, false);
$color = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
imagefill($newImage, 0, 0, $color);
imagesavealpha($newImage, true);
}
}

而且工作得很好

关于php - 如何允许使用 php 上传透明 gif 或 png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6819822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com