How can PHP be used to determine the size of an image and prevent table distortion in a forum?
When users upload images to a forum, their sizes can vary, potentially causing distortion within tables where the images are displayed. To prevent this, PHP can be used to determine the size of the uploaded image and resize it accordingly before displaying it in the forum. This can be achieved by using PHP's GD library functions to get the dimensions of the image and then resizing it proportionally to fit within a specified width or height.
// Get the uploaded image file
$image = $_FILES['image']['tmp_name'];
// Get the dimensions of the image
list($width, $height) = getimagesize($image);
// Specify the maximum width for the resized image
$max_width = 500;
// Calculate the new height based on the aspect ratio
$new_height = ($max_width / $width) * $height;
// Create a new image resource from the uploaded image
$source = imagecreatefromjpeg($image);
// Create a new image resource for the resized image
$dest = imagecreatetruecolor($max_width, $new_height);
// Resize the image
imagecopyresized($dest, $source, 0, 0, 0, 0, $max_width, $new_height, $width, $height);
// Output the resized image
header('Content-Type: image/jpeg');
imagejpeg($dest);
// Free up memory
imagedestroy($source);
imagedestroy($dest);