Skip to content

Instantly share code, notes, and snippets.

@erdum
Created January 31, 2024 18:46
Show Gist options
  • Save erdum/f9ac2f9ddd0afd5fe922378659921bbe to your computer and use it in GitHub Desktop.
Save erdum/f9ac2f9ddd0afd5fe922378659921bbe to your computer and use it in GitHub Desktop.
Convert and save image in webp from raw base64 string in Laravel
<?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