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上。也許配置相關? –