In what ways can PHP be utilized to improve the user experience when sending images as attachments through a contact form?

When sending images as attachments through a contact form, it is important to optimize the user experience by resizing the images to a reasonable size before attaching them to the email. This will help reduce the file size and ensure faster delivery of the email with attachments.

// Resize image before attaching to email
function resize_image($file, $max_width, $max_height){
    list($width, $height) = getimagesize($file);
    $ratio = $width / $height;

    if ($max_width / $max_height > $ratio) {
        $max_width = $max_height * $ratio;
    } else {
        $max_height = $max_width / $ratio;
    }

    $new_image = imagecreatetruecolor($max_width, $max_height);
    $image = imagecreatefromjpeg($file);
    imagecopyresampled($new_image, $image, 0, 0, 0, 0, $max_width, $max_height, $width, $height);

    return $new_image;
}

// Example of resizing image before attaching to email
$attachment = 'path/to/image.jpg';
$resized_image = resize_image($attachment, 800, 600);

// Attach resized image to email
$mail->AddStringAttachment($resized_image, 'resized_image.jpg', 'base64', 'image/jpeg');