Skip to content

Instantly share code, notes, and snippets.

@erdum
Created May 12, 2022 20:43
Show Gist options
  • Save erdum/fbf25e9c53cb6c5f97933da964aa35c0 to your computer and use it in GitHub Desktop.
Save erdum/fbf25e9c53cb6c5f97933da964aa35c0 to your computer and use it in GitHub Desktop.
Handle image upload in laravel and convert them to webp for storage.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageUploadController
{
public function saveToWebp($src, $destination, $extension)
{
$image = null;
if ($extension == 'webp') {
$image = imagecreatefromwebp($src);
} elseif ($extension == 'jpeg' || $extension == 'jpg') {
$image = imagecreatefromjpeg($src);
} elseif ($extension == 'gif') {
$image = imagecreatefromgif($src);
} elseif ($extension == 'png') {
$image = imagecreatefrompng($src);
}
if ($image == null) return response()->json(['message' => 'File type not supported'], 422);
return imagewebp($image, public_path($destination), 75);
}
public function upload(Request $request)
{
if (count($request->files) > 0) {
foreach ($request->files as $file)
{
$file_name = explode('.', $file->getClientOriginalName());
$extension = end($file_name);
$file_name = $file_name[0];
if (!$this->saveToWebp($file, 'photos/' . $file_name . '.webp', $extension)) {
return response()->json(['message' => 'failed to save image']);
}
}
return response()->json(['message' => 'success']);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment