What are some best practices for handling image manipulation and saving in PHP?
When handling image manipulation and saving in PHP, it is important to use proper functions and libraries to ensure the images are processed correctly and efficiently. One best practice is to use the GD library for image manipulation tasks such as resizing, cropping, and adding watermarks. Additionally, always sanitize and validate user input to prevent security vulnerabilities.
// Example of resizing an image using the GD library
$source = 'image.jpg';
$destination = 'resized_image.jpg';
$newWidth = 200;
$newHeight = 150;
list($width, $height) = getimagesize($source);
$ratio = $width / $height;
if ($newWidth / $newHeight > $ratio) {
$newWidth = $newHeight * $ratio;
} else {
$newHeight = $newWidth / $ratio;
}
$src = imagecreatefromjpeg($source);
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($dst, $destination, 100);
imagedestroy($src);
imagedestroy($dst);