Consider this scenario: After a lot of rendering steps, you finally have a canvas of a magical image produced by your magnificent mind. Now, you are sending the canvas to the server via an ajax POST request as a base64 string.

let base64_string = canvas.toDataURL();
$.post(address, { base64_string });

On the other end, the server received the base64 string and ready to save the image into the file system. What we have is a string, how are we suppose to save an image?

  1. Decode this string by using base64_decode function.
    <?php
    $content = base64_decode($base64_string);
    
  2. Open a file stream to write.
    <?php
    $file = fopen($output_file, "wb");
    
  3. Write to the stream and close it.
    <?php
    fwrite($file, $content);
    fclose($file);
    

If you run the steps above, you will receive an error. The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image when the base64 function decodes it (Step 1). Remove that data before decoding the string, like so:

<?php
$data = explode(',', $base64_string);
$content = base64_decode($data[1]);

As a result, a full function of converting a base64 string to an image file is presented as bellow:

<?php
function base64ToImage($base64_string, $output_file) {
    $file = fopen($output_file, "wb");

    $data = explode(',', $base64_string);

    fwrite($file, base64_decode($data[1]));
    fclose($file);

    return $output_file;
}

This solution is taken from this question on StackOverflow.

Loading comments

netcell

Software engineer with 4+ years of work experience in designing and developing cross-platform games and apps on web technology.