WebP Image Conversion in PHP: Why Make the Switch and How
⧉ Category: Programing | 📅 Date: 27 Mar 2024 | अ🉀 Translation:

$ds = DIRECTORY_SEPARATOR;
$file_path = realpath(dirname(__FILE__));
$image_url = $file_path . $ds . "XPYdpuo9VbMGaVK0gp6ri.png";
Here, `DIRECTORY_SEPARATOR` ensures that we use the correct directory separator for the current environment, whether it's a forward slash ("/") or a backward slash ("\").
Next, we define a function `convertToWebp()` to handle the conversion process. This function checks if the image file exists and if it's a valid image using `file_exists()` and `getimagesize()`.
function convertToWebp($image_url) {
$file = 0;
if (file_exists($image_url) && getimagesize($image_url)) {
$file = 1; // Image file confirmed
}
// Rest of the code goes here...
}
If the image file is confirmed, we extract its MIME type, width, and height using `getimagesize()`. Then, we create a true-color image resource using `imagecreatetruecolor()` and load the source image using `imagecreatefrompng()` or `imagecreatefromjpeg()` based on the MIME type.
$image_data = getimagesize($image_url);
$image_type = "";
$image_width = 100; // Default width
$image_height = 100; // Default height
if (is_array($image_data) && isset($image_data['mime'])) {
$image_type = $image_data['mime'];
$image_width = $image_data[0];
$image_height = $image_data[1];
}
$dst_image = imagecreatetruecolor($image_width, $image_height);
if ($image_type === "image/png") {
$src_image = imagecreatefrompng($image_url);
} elseif ($image_type === "image/jpeg") {
$src_image = imagecreatefromjpeg($image_url);
}
Now that we have the source image loaded, we copy it to the destination image resource using `imagecopy()`. Finally, we use `imagewebp()` to output the WebP image directly to the browser.
if (isset($src_image)) {
header("Content-Type: image/webp");
imagecopy($dst_image, $src_image, 0, 0, 0, 0, $image_width, $image_height);
imagewebp($dst_image, null, 90);
imagedestroy($dst_image);
}
And that's it! We've successfully converted an existing image to WebP format directly in PHP. Just remember, this function doesn't save the converted file. it displays the WebP image directly in the browser.«[Previous Post] Top 10 Martial Arts Manga/Webtoons That Pack a Pun..Summer heat in India [Next Post]»
Comments
Please solve above captcha based on the hint given..