function convert_single_image_to_webp($image_path) {
// Check if the file exists
if (!file_exists($image_path)) {
return "File does not exist: $image_path";
}
// Get the file extension and MIME type
$file_info = getimagesize($image_path);
if (!$file_info) {
return "Invalid image file.";
}
$mime_type = $file_info['mime'];
// Allowed MIME types for conversion
$allowed_mime_types = ['image/jpeg', 'image/png'];
if (!in_array($mime_type, $allowed_mime_types)) {
return "Unsupported file type. Only JPEG and PNG are allowed.";
}
// Load the image based on its MIME type
$image = null;
if ($mime_type === 'image/jpeg') {
$image = imagecreatefromjpeg($image_path);
} elseif ($mime_type === 'image/png') {
$image = imagecreatefrompng($image_path);
}
if (!$image) {
return "Failed to create an image resource.";
}
// Create the WebP file path
$webp_path = $image_path . '.webp';
// Convert to WebP and save the file
if (imagewebp($image, $webp_path)) {
imagedestroy($image); // Free memory
return "Conversion successful. WebP file created at: $webp_path";
} else {
imagedestroy($image); // Free memory
return "Failed to convert the image to WebP.";
}
}
// Example Usage: Replace with the actual file path to test
$image_path = 'https://saskarc.com/en/wp-content/uploads/2024/10/InfraMOD-Banner-2.png'; // Replace with your test image path
$result = convert_single_image_to_webp($image_path);
echo $result;
Saskarc has donated $1,000 to STARS Air Ambulance. STARS is a charitable, non-profit organization, serving Saskatchewan since 2011. With STARS, those living in rural communities, working in remote areas, travelling on highways or being transported from community hospitals to major medical centers, receive the very best in critical care in helicopters staffed and outfitted as mobile ICUs.
Saskarc believes by supporting community initiatives that align with our own core values, we can all help build a stronger, healthier and safer province.