Save a PNG image from a base64 data string with PHP

We can extract the base64 image data from that string, decode it and save it to disk, don't need GD since it already is a png.

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>
5.00 avg. rating (97% score) - 1 vote

One thought on “Save a PNG image from a base64 data string with PHP

  1. man choy

    Hellp, this code cannot work with mine. Can you have a look on my code?

    my ajax.

    var id = localStorage.getItem('cameraResult');

    alert(id);

    $.ajax({

    type: "POST",

    url:'http://www.kipkad.com.my/kipcard/api/appery_kipcard_imageRwApi.php',

    data: ({img: id}),

    complete: function (response) {

    var data = response.responseText;

    var json = JSON.parse(data);

    Apperyio.storage.ImageResult.set(json['result']);

    alert(localStorage.getItem('ImageResult'));

    if(ImageResult==='true'){

    alert('true');

    Apperyio.navigateTo('Scan3', {transition : 'none'});

    }else{

    alert('error');

    Apperyio.navigateTo('Scan2', {transition : 'none'});

    }

    },

    error: function (result, status, err) {

    alert("error", result.responseText);

    alert("error", status.responseText);

    alert("error", err.Message);

    }

    });

    my php

    $file_name);

    echo json_encode($arr);

    } else{

    $arr = array('result' =>'false');

    echo json_encode($arr);

    ?>