1
我有一个函数,我正在使用接受用户上传的图像,按比例缩放到最大宽度/高度为4,000px,并且还生成400px和800px缩略图。它需要能够处理透明的PNG并应用白色背景。PHP GD调整大小导致工件
我的当前代码执行所有这些操作,但是,它会添加不常见的非JPEG文件。他们是垂直的条纹,看起来像一个非常黯淡的条码,当看近处(400%缩放屏幕截图)。这种情况甚至发生在原始图片上,并且以其缩放的尺寸上传。它似乎更加流行透明的PNG,但也发生在JPEG的白色区域。 JPEG文件被保存质量80
function resize_image($file, $w, $h, $strict = false, $crop = false, $path = null, $thumbnail = false)
{
// Check for Valid Image + Calculate Ratio
list($width, $height) = getimagesize($file);
if (empty($width) || empty($height))
{
echo json_encode(['result' => 'error', 'error' => 'file_format_invalid']);
http_response_code(405);
exit;
}
$r = $width/$height;
if (!$strict)
{
$w = min($w, $width);
$h = min($h, $height);
}
$wTa = min($w, 400);
$hTa = min($h, 400);
$wTb = min($w, 800);
$hTb = min($h, 800);
// Apply Crop Constraint
if ($crop)
{
if ($width > $height)
{
$width = ceil($width - ($width * abs($r - $w/$h)));
$widthTa = ceil($width - ($width * abs($r - $wTa/$hTa)));
$widthTb = ceil($width - ($width * abs($r - $wTb/$hTb)));
}
else
{
$height = ceil($height - ($height * abs($r - $w/$h)));
$heightTa = ceil($height - ($height * abs($r - $wTa/$hTa)));
$heightTb = ceil($height - ($height * abs($r - $wTa/$hTb)));
}
$newWidth = $w;
$newHeight = $h;
}
else
{
if ($w/$h > $r || $r < 1)
{
$newWidth = $h * $r;
$newWidthTa = $hTa * $r;
$newWidthTb = $hTb * $r;
$newHeight = $h;
$newHeightTa = $hTa;
$newHeightTb = $hTb;
}
else
{
$newHeight = $w/$r;
$newHeightTa = $wTa/$r;
$newHeightTb = $wTb/$r;
$newWidth = $w;
$newWidthTa = $wTa;
$newWidthTb = $wTb;
}
}
// Create, Resample + Return Image
$src = imagecreatefromstring(file_get_contents($file));
$dst = imagecreatetruecolor($newWidth, $newHeight);
$fff = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $fff);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (!is_null($path))
{
imagejpeg($dst, $path, 80);
if ($thumbnail)
{
$dstThumbA = imagecreatetruecolor($newWidthTa, $newHeightTa);
$dstThumbB = imagecreatetruecolor($newWidthTb, $newHeightTb);
$fffThumbA = imagecolorallocate($dstThumbA, 255, 255, 255);
$fffThumbB = imagecolorallocate($dstThumbB, 255, 255, 255);
imagefill($dstThumbA, 0, 0, $fffThumbA);
imagefill($dstThumbB, 0, 0, $fffThumbB);
imagecopyresampled($dstThumbA, $src, 0, 0, 0, 0, $newWidthTa, $newHeightTa, $width, $height);
imagecopyresampled($dstThumbB, $src, 0, 0, 0, 0, $newWidthTb, $newHeightTb, $width, $height);
imagejpeg($dstThumbA, str_replace('.jpg', '-thumb.jpg', $path), 80);
imagejpeg($dstThumbB, str_replace('.jpg', '[email protected]', $path), 80);
}
}
return $dst;
}
我想说的尝试使用'imagecopyresized'代替'imagecopyresampled' - 也许这也有帮助http://stackoverflow.com/questions/23200823/gd-quality-issue-with-transparent -pngs || http://stackoverflow.com/questions/23993901/imagecopyresampled-introduces-artifacts-in-transparent-png –
嗯,好的想法,'imagecopyresized'确实能够工作,没有那个伪像,尽管它引入了太多的别名来被接受。我注意到这些症状出现在Ubuntu下的PHP 7.1.3上,但在开发中的Windows下不在PHP 7.0.1上。也许配置相关? –