rosell-dk / webp-convert

Convert jpeg/png to webp with PHP (if at all possible)
MIT License
576 stars 101 forks source link

Convert jpeg or png to webp with php #348

Open shortcodegreece opened 1 year ago

shortcodegreece commented 1 year ago

<?php if (isset($_POST['submit'])) { $allowedFormats = ['image/jpeg', 'image/png']; $imageFile = $_FILES['image'];

if (in_array($imageFile['type'], $allowedFormats)) {
    $sourceImagePath = $imageFile['tmp_name'];

    $image = imagecreatefromstring(file_get_contents($sourceImagePath));
    $destinationImagePath = 'converted_image.webp';

    imagewebp($image, $destinationImagePath);

    imagedestroy($image);

    // Send the converted image to the browser for download
    header('Content-Type: image/webp');
    header('Content-Disposition: attachment; filename="converted_image.webp"');
    readfile($destinationImagePath);

    // Clean up temporary files
    unlink($destinationImagePath);
    exit();
} else {
    echo 'Invalid image format. Only JPEG and PNG images are allowed.';
}

} ?>