rosell-dk/webp-convert-and-serve

使用PHP将jpeg/png转换为webp(如果可能的话)

0.4.0 2018-08-27 18:30 UTC

This package is auto-updated.

Last update: 2024-09-10 21:25:53 UTC


README

这个库现在是WebP Convert的一部分,因此已经过时!

Build Status

此库可用于将WebP图像转换为jpeg/png,而不是jpeg/png。它基于WebPConvert,该库负责转换。除此之外,它还增加了一个方法来以处理转换失败选项的方式提供转换后的图像。

提供服务的任务本身实际上相当小。它可以像这样用几行代码实现

try {
    $success = WebPConvert::convert($source, $destination, $options);
    if ($success) {
        header('Content-type: image/webp');
        readfile($destination);        
    }
}

但是,接下来是错误处理。

如果转换失败,则可以有意义地提供源图像(如果存在的话)。为此,我们需要检查扩展以提供正确的Content-type头。我们还想添加告诉浏览器不要缓存的头。如果源文件甚至不可用怎么办?这也应该得到处理。这是繁琐的事情,这个库会处理。

API

WebPConvertAndServe::convertAndServe($source, $destination, $options)

注意:此方法是在0.4.0版本中添加的。旧的方法convertAndServeImage()仍然有效,但已弃用。

参数$options

选项参数是一个命名数组。WebPConvertAndServe只有两个可用的选项(failcritical-fail)。然而,这些选项将被传递给WebPConvert。所以这里可以使用webp-convert中的任何选项。

fail

在正常转换失败的情况下指示要提供的内容。默认值:"original"

除了字符串值(例如 "original"),您还可以使用以下常量:WebPConvertAndServe::$ORIGINALWebPConvertAndServe::$HTTP_404WebPConvertAndServe::$REPORT_AS_IMAGEWebPConvertAndServe::$REPORT

critical-fail

可能的值:与上面相同,除了"original"不是选项。默认值:"404"

返回值

指示已提供内容的数字。在失败或关键失败的情况下,值将是以下常量之一:以下常量WebPConvertAndServe::$ORIGINALWebPConvertAndServe::$HTTP_404WebPConvertAndServe::$REPORT_AS_IMAGEWebPConvertAndServe::$REPORT。在成功的情况下,它将是WebPConvertAndServe::$CONVERTED_IMAGE。所有失败常量都是负数。成功常量是正数——因此您可以使用if ($returnValue > 0)来测试成功。

示例

require 'vendor/autoload.php';

use WebPConvertAndServe\WebPConvertAndServe;

$source = __DIR__ . '/logo.jpg';
$destination = $source . '.webp';
$options = [
    'fail' => 'original',
    'critical-fail' => '404',

    // You can specify any WebPConvert option here - such as defining a converters array, which
    // is needed, if you need to use a cloud converter
    'converters' => [
        [
            'converter' => 'ewww',
            'options' => [
                'key' => 'blah',
            ],
        ],
        'cwebp',
        'gd'
    ];

$status = WebPConvertAndServe::convertAndServe($source, $destination, $options);

安装

composer require rosell-dk/webp-convert-and-serve