GD库实现webp转换jpg的PHP程序
Sure, here is an example of how to use the GD library to convert a WebP image to a JPG image in PHP:
PHP
<?php
$webpPath = 'input.webp'; // Path to the WebP image
$jpgPath = 'output.jpg'; // Path to save the converted JPG image
// Check if the WebP image file exists
if (!file_exists($webpPath)) {
die('WebP image file does not exist: ' . $webpPath);
}
// Create a GD image resource from the WebP image
$image = imagecreatefromwebp($webpPath);
// Check if the GD image resource was created successfully
if (!$image) {
die('Failed to create GD image resource from WebP image');
}
// Convert the GD image to JPG format
$result = imagejpeg($image, $jpgPath);
// Destroy the GD image resource
imagedestroy($image);
// Check if the JPG image was saved successfully
if (!$result) {
die('Failed to save JPG image');
}
echo 'WebP image converted to JPG successfully: ' . $jpgPath;
Explanation:
Include GD library: The script starts by including the GD library using the require
statement. This is necessary to use the GD functions for image manipulation.
Define paths: The paths to the input WebP image ($webpPath
) and the output JPG image ($jpgPath
) are defined. Make sure to replace these paths with the actual locations of your files.
Check WebP file existence: The file_exists()
function is used to check if the WebP image file exists. If it doesn't exist, an error message is displayed and the script terminates.
Create GD image resource: The imagecreatefromwebp()
function is used to create a GD image resource from the WebP image file. This function returns the GD image resource on success or false
on failure.
Check GD image creation: The script checks if the GD image resource was created successfully using an if
statement. If the resource is not created, an error message is displayed and the script terminates.
Convert to JPG: The imagejpeg()
function is used to convert the GD image resource to JPG format. The function takes the GD image resource and the output JPG file path as arguments. It returns true
on success or false
on failure.
Destroy GD image: The imagedestroy()
function is used to destroy the GD image resource, releasing the associated memory.
Check JPG saving: The script checks if the JPG image was saved successfully using an if
statement. If the image is not saved, an error message is displayed and the script terminates.
Success message: If the conversion and saving are successful, a message indicating the successful conversion is displayed.
Additional notes:
imagejpeg()
function. The value should be between 0 (lowest quality) and 100 (highest quality).