により元の幅と高さを掛けここで私はGDを使用してサムネイルを生成するために書いた機能です。最大幅または高さ、または両方を渡すことができます(ゼロの場合は制限なしを意味します)、サムネイルは比率がそのままの状態で$dest
(+ファイル拡張子)にスケーリングされます。また、透過画像でも動作します。残りの余分なスペースは完全に透明でなければなりません。別の背景が必要な場合は、imagecopyresampled()
の前に$img
を変更してください。
function picThumb($src, $dest, $width = 0, $height = 0, $quality = 100)
{
$srcType = exif_imagetype($src);
if (!$width && !$height)
{
$ext = image_type_to_extension($srcType, false);
copy($src, $dest . '.' . $ext);
return $ext;
}
ini_set('memory_limit', '134217728');
try
{
switch ($srcType)
{
case IMAGETYPE_JPEG:
$srcImg = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$srcImg = imagecreatefrompng($src);
break;
case IMAGETYPE_GIF:
$srcImg = imagecreatefromgif($src);
break;
default:
throw new Exception();
}
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
if (!$srcWidth || !$srcHeight)
{
throw new Exception();
}
if ($width && $height)
{
$ratio = min($srcWidth/$width, $srcHeight/$height);
$areaWidth = round($width * $ratio);
$areaHeight = round($height * $ratio);
$areaX = round(($srcWidth - $areaWidth)/2);
$areaY = round(($srcHeight - $areaHeight)/2);
}
else // if (!$width || !$height)
{
if ($width)
{
$height = round($width/$srcWidth * $srcHeight);
}
else // if ($height)
{
$width = round($height/$srcHeight * $srcWidth);
}
$areaWidth = $srcWidth;
$areaHeight = $srcHeight;
$areaX = 0;
$areaY = 0;
}
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagecopyresampled($img, $srcImg, 0, 0, $areaX, $areaY, $width, $height, $areaWidth, $areaHeight);
switch ($srcType)
{
case IMAGETYPE_JPEG:
$ext = 'jpg';
imagejpeg($img, $dest . '.' . $ext, $quality);
break;
case IMAGETYPE_PNG:
case IMAGETYPE_GIF:
$ext = 'png';
imagesavealpha($img, true);
imagepng($img, $dest . '.' . $ext, 9);
break;
default:
throw new Exception();
}
imagedestroy($srcImg);
imagedestroy($img);
}
catch (Exception $e)
{
ini_restore('memory_limit');
throw $e;
}
ini_restore('memory_limit');
return $ext;
}
これは非常に明確ではありません。必要なものを書き直したり、いくつかの視覚的な例や他のものを与えてください。 – JakeParis
@JMCが言ったことは、特に、どのように比率を扱うべきかと言いました。 – Trufa