fuwasegu/php-base64-image

Library for easy handling of base64-encoded images in PHP

1.1.0 2023-03-15 00:42 UTC

This package is auto-updated.

Last update: 2024-04-15 03:01:55 UTC


README

Coverage Status example workflow MIT License

Library for easy handling of base64-encoded images in PHP

📦 Installation

composer require fuwasegu/php-base64-image

✅ Usage

Assuming you are using this package in a Laravel project, you can use it as follows:

💡Tips

Of course, this library does not depend on Laravel, so it can be used for pure PHP projects as well.

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Fuwasegu\PhpBase64Image\Image;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Str;

class ImageSaveController
{
    public function __invoke(Request $request): JsonResponse
    {
        // Base64 encoded image data uri
        $dataUri = $request->input('image');
        
        // Create Image object from base64 image data uri
        $image = Image::fromBase64($dataUri);
        
        // Random string for image name based on uuid
        $uuid = Str::uuid();
        
        // Upload to S3 using Storage facade
        Storage::put(
            path: "images/{$uuid}.{$image->extension()->value}",
            contents: $image->data(),
            options: 'private',
        );
        
        return new JsonResponse(['message' => 'success'], 200);
    }
}