What are the best practices for handling image resizing and renaming in PHP?
When handling image resizing and renaming in PHP, it's important to maintain the aspect ratio of the image to prevent distortion. To resize an image, you can use the GD library functions like `imagecreatefromjpeg()` and `imagecopyresampled()`. When renaming an image, make sure to generate a unique filename to avoid overwriting existing files.
// Example code for resizing and renaming an image
$sourceFile = 'original.jpg';
$targetFile = 'resized.jpg';
list($width, $height) = getimagesize($sourceFile);
$newWidth = 100; // New width for the resized image
$newHeight = ($height / $width) * $newWidth;
$source = imagecreatefromjpeg($sourceFile);
$target = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($target, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($target, $targetFile);
// Rename the resized image
$newFileName = 'new_image_' . uniqid() . '.jpg';
rename($targetFile, $newFileName);