溫馨提示×

如何在PHP中實現(xiàn)WebP圖片的轉換

PHP
小樊
84
2024-09-04 22:01:28
欄目: 編程語言

要在 PHP 中將其他格式的圖片轉換為 WebP 格式,您可以使用 GD 庫或 ImageMagick

方法1:使用 GD 庫

  1. 首先確保您的服務器安裝了 GD 庫和 WebP 支持。創(chuàng)建一個 phpinfo 文件(例如 info.php),并添加以下代碼:
<?php
phpinfo();
?>

訪問此文件,查看是否已啟用 GD 庫和 WebP 支持。

  1. 使用以下示例代碼將 JPEG/PNG 圖像轉換為 WebP:
<?php
function convertToWebP($source, $destination, $quality = 80) {
    if (!file_exists($source)) {
        echo "Source image not found.";
        return false;
    }

    // 獲取源圖像的類型
    $imageType = exif_imagetype($source);

    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($source);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($source);
            break;
        default:
            echo "Unsupported image type.";
            return false;
    }

    // 將源圖像保存為 WebP 格式
    $success = imagewebp($image, $destination, $quality);
    imagedestroy($image);

    if ($success) {
        echo "Image successfully converted to WebP.";
    } else {
        echo "Error converting image to WebP.";
    }

    return $success;
}

$sourceImage = 'path/to/your/input/image.jpg';
$destinationImage = 'path/to/your/output/image.webp';
$quality = 80; // 設置 WebP 圖像的質量,范圍從 0(最差)到 100(最好)

convertToWebP($sourceImage, $destinationImage, $quality);
?>

$sourceImage$destinationImage 變量更改為您的輸入和輸出圖像路徑。

方法2:使用 ImageMagick

  1. 首先確保您的服務器安裝了 ImageMagick 和 WebP 支持。在命令行中運行以下命令:
convert -version

查看是否已啟用 WebP 支持。

  1. 使用以下示例代碼將 JPEG/PNG 圖像轉換為 WebP:
<?php
function convertToWebP($source, $destination, $quality = 80) {
    if (!file_exists($source)) {
        echo "Source image not found.";
        return false;
    }

    // 使用 ImageMagick 將源圖像轉換為 WebP
    $command = "convert \"{$source}\" -quality {$quality} \"{$destination}\"";
    $output = [];
    $result = null;
    exec($command, $output, $result);

    if ($result === 0) {
        echo "Image successfully converted to WebP.";
    } else {
        echo "Error converting image to WebP.";
    }

    return $result === 0;
}

$sourceImage = 'path/to/your/input/image.jpg';
$destinationImage = 'path/to/your/output/image.webp';
$quality = 80; // 設置 WebP 圖像的質量,范圍從 0(最差)到 100(最好)

convertToWebP($sourceImage, $destinationImage, $quality);
?>

$sourceImage$destinationImage 變量更改為您的輸入和輸出圖像路徑。

這兩種方法都可以將 JPEG 和 PNG 圖像轉換為 WebP 格式。根據(jù)您的需求和服務器配置選擇合適的方法。

0