What are some best practices for optimizing image quality and file size when using the "imagejpeg" function in PHP for thumbnail generation?

When using the "imagejpeg" function in PHP for thumbnail generation, it is important to balance image quality and file size. To optimize both, you can adjust the quality parameter in the function to find the right balance between image clarity and file size. Additionally, resizing the image before generating the thumbnail can also help reduce file size without sacrificing quality.

// Set the desired quality level (0-100) for the thumbnail image
$quality = 80;

// Load the original image
$original_image = imagecreatefromjpeg('original.jpg');

// Get the dimensions of the original image
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);

// Calculate the new dimensions for the thumbnail (e.g., 200px width)
$thumbnail_width = 200;
$thumbnail_height = ($original_height / $original_width) * $thumbnail_width;

// Create a new image resource for the thumbnail
$thumbnail_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);

// Resize the original image to fit the thumbnail dimensions
imagecopyresampled($thumbnail_image, $original_image, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $original_width, $original_height);

// Output the thumbnail image with the specified quality level
imagejpeg($thumbnail_image, 'thumbnail.jpg', $quality);

// Free up memory by destroying the image resources
imagedestroy($original_image);
imagedestroy($thumbnail_image);