PHP'nin GD kütüphanesi, resimleri otomatik olarak yeniden boyutlandırmak için kullanılabilir. Bu yöntem, web sitenizdeki resimleri otomatik olarak boyutlandırmak için idealdir. Aşağıdaki kod, bir resmi belirli boyutlarda yeniden boyutlandırmak için örnek bir PHP fonksiyonudur:
function resize_image($file, $width, $height) {
list($w, $h) = getimagesize($file);
$aspect_ratio = $w / $h;
if ($width / $height > $aspect_ratio) {
$width = $height * $aspect_ratio;
} else {
$height = $width / $aspect_ratio;
}
$img = imagecreatetruecolor($width, $height);
$src = imagecreatefromstring(file_get_contents($file));
imagecopyresampled($img, $src, 0, 0, 0, 0, $width, $height, $w, $h);
return $img;
}Bu fonksiyonu kullanarak, bir resmi yeniden boyutlandırmak için aşağıdaki gibi bir kod bloğu yazabilirsiniz:
// Resmi yeniden boyutlandır
$resized_img = resize_image('path/to/image.jpg', 300, 150);
// Yeniden boyutlandırılmış resmi kaydet
imagejpeg($resized_img, 'path/to/resized_image.jpg', 90);
// Bellekten resmi serbest bırak
imagedestroy($resized_img);