PHP code example of nikocodes / picowebp

1. Go to this page and download the library: Download nikocodes/picowebp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nikocodes / picowebp example snippets




icoWebP\Vp8\ImageInput;
use PicoWebP\Vp8\Vp8LossyEncoder;

$pixels = ImageInput::pixels('photo.jpg');

$encoder = Vp8LossyEncoder::fromQuality(80);
$encoder->alphaPlane = $pixels['alpha']; // null for an opaque image
$encoder->iccProfile = $pixels['icc'];   // null when no profile is present

$result = $encoder->encode($pixels['rgb'], $pixels['w'], $pixels['h']);

if (file_put_contents('photo.webp', $result['webp']) !== strlen($result['webp'])) {
    throw new RuntimeException('Could not write photo.webp');
}



icoWebP\Vp8\Vp8LossyEncoder;

$width = 16;
$height = 16;
$rgb = str_repeat("\xff\x00\x00", $width * $height);

$encoder = Vp8LossyEncoder::fromQuality(80);
$webp = $encoder->encode($rgb, $width, $height)['webp'];

if (file_put_contents('red.webp', $webp) !== strlen($webp)) {
    throw new RuntimeException('Could not write red.webp');
}



icoWebP\Vp8\ImageInput;
use PicoWebP\Vp8\SkippedInput;

foreach (['photo.jpg', 'already.webp'] as $file) {
    try {
        $pixels = ImageInput::pixels($file);
    } catch (SkippedInput $e) {
        // $e->slug() is 'skipped_webp'; $e->reason() explains the skip.
        // $e->meta contains metadata read from the WebP header.
        continue;
    }

    // Encode or enqueue $pixels here.
}
sh
composer test
# or: php tests/run.php