Laravel: Save Base64 .png file to public folder from controller

Laravel: Save Base64 .png file to public folder from controller

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Saving Base64 Images in Laravel Controllers: Handling Streams and Paths Correctly

You have successfully received a PNG image encoded as a Base64 string via an Ajax request, extracted the payload, and decoded it back into binary data. However, when you attempt to persist this file using Image::make($image)->getRealPath()->save(), the operation fails or produces unexpected results. The issue isn't with your routing or JSON response; it is a fundamental misunderstanding of how Laravel's Storage facade and the Illuminate\Http\UploadedFile class handle data types.

The core problem lies in this line:

Image::make($image)->getRealPath()

When you pass a binary string directly to Image::make(), it creates an instance of Laravel\SerializableClosure\SerializableClosure or, more commonly in older versions, treats the input as a stream handle that requires specific handling. The critical error is attempting to call getRealPath() on an object created from a raw string without first converting that string into an UploadedFile instance. The getRealPath() method expects a file path or a resource (stream), not a binary string wrapped in a temporary stream handle generated internally by the image package.

To resolve this, you must instantiate a new Illuminate\Http\UploadedFile object using the decoded binary string as the first argument and a dummy filename as the second. This allows Laravel to wrap the raw data into an object that adheres to its storage contract. Once wrapped, you can use the storeAs() method or generate a path and save it explicitly.

Here is the corrected implementation for your controller:

use Illuminate\Http\UploadedFile;
use Intervention\Image\Facades\Image;

public function postTest() {
    // Retrieve raw data from the request
    $data = request()->all(); 

    // Extract Base64 string content after the comma (removing 'data:image/png;base64,')
    $base64_str = substr($data['base64_image'], strpos($data['base64_image'], ',') + 1);

    // Decode the Base64 string back to binary
    $imageData = base64_decode($base64_str);

    if ($imageData === false) {
        return response()->json(['status' => 'error', 'message' => 'Failed to decode image'], 500);
    }

    // Create an UploadedFile instance from the binary string
    $uploadedFile = new UploadedFile(
        $imageData, 
        null, // File name can be null here as we will generate one
        'image/png', // MIME type based on the expected format
        true, // Assume file is uploaded (bypass validation)
        null // Original filename
    );

    // Define the destination path within the public folder
    $path = 'img/designs/product-' . time() . '.png';

    try {
        // Save using Intervention Image, passing the UploadedFile instance directly
        Image::make($uploadedFile)->save(public_path($path));
        
        return response()->json([
            'status' => 'success',
            'file_path' => $path
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'error',
            'message' => $e->getMessage()
        ], 500);
    }
}

Why file_put_contents Might Have Failed You

You mentioned trying $result = file_put_contents($path, $image);. While this function writes binary data to a file correctly, the variable $path in your original code was constructed using public_path(). If you intended to use the filesystem directly without the Image library, file_put_contents() works fine with absolute paths. However, if you are relying on Laravel's storage engine later, mixing raw filesystem calls with Storage facades can lead to permission inconsistencies or race conditions in shared environments.

Best Practices for Base64 Handling

Storing images encoded as Base64 directly into the public folder is functional but carries specific trade-offs. Since Base64 expands data size by roughly 33%, your files will be larger than necessary if you are storing them permanently. Furthermore, every time a user uploads an image, you are creating a new file with a timestamp-based name. This can quickly clutter the public/img/designs directory and complicate asset management or CDN caching strategies.

For production applications where performance and scalability matter, consider using Laravel's cloud storage drivers (like S3) instead of writing directly to the local disk. The logic remains similar—wrap the string in an UploadedFile, but pass it to the cloud driver rather than public_path(). Additionally, always validate the MIME type strictly before processing. A malicious user could send a file claiming to be a PNG that is actually executable code if you blindly trust the header.

For more complex image manipulation workflows or optimized storage solutions, resources like LaravelCompany offer deep dives into leveraging Laravel's ecosystem for media management.

Our network