Created
January 31, 2024 18:46
-
-
Save erdum/f9ac2f9ddd0afd5fe922378659921bbe to your computer and use it in GitHub Desktop.
Convert and save image in webp from raw base64 string in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Str; | |
function save_base64_to_webp( | |
$string, | |
$file_directory, | |
$file_name = null, | |
$disk_driver = 'local' | |
) | |
{ | |
$handle = fopen("php://memory", "rw"); | |
$decoded_image = imagecreatefromstring( | |
base64_decode($string) | |
); | |
imagepalettetotruecolor($decoded_image); | |
imagewebp($decoded_image, $handle, 75); | |
imagedestroy($decoded_image); | |
$file_name = $file_name ?? Str::random(15); | |
$file_path = "{$file_directory}{$file_name}.webp"; | |
Storage::disk($disk_driver)->put($file_path, $handle); | |
fclose($handle); | |
return $file_path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment