How to convert and store base64 encoding to an image in php?

I am trying to take image fron webcam then store it in a file as jpeg format. So far this code captures image and convert that in base64 encoding. Now how can I store it in folder. This is my first time. I am working a long time with it. How can I fix it.

php

<?php
if(isset($_POST["mydata"])) {

 $encoded_data = $_POST['mydata'];
 $binary_data = base64_decode( $encoded_data );

// save to server (beware of permissions)
$result = file_put_contents( 'webcam.jpg', $binary_data );
// move_uploaded_file ( "test.png" , "/img" );
//if (!$result) die("Could not save image!  Check file permissions."); 

 }
?>

html

<body>
<div id="results">Your captured image will appear here...</div>

<h1>WebcamJS Test Page</h1>

<div id="my_camera"></div>

<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="webcam.min.js"></script>

<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
    Webcam.set({
        width: 180,
        height: 100,
        image_format: 'jpeg',
        jpeg_quality: 90
    });
    Webcam.attach( '#my_camera' );
</script>

<!-- A button for taking snaps -->

<input type=button value="Take Snapshot" onClick="take_snapshot()">


<form id="myform" method="post" action="" enctype="multipart/form-data">
    <input id="mydata" type="hidden" name="mydata" value=""/>
</form>

<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '<h2>Here is your image:</h2>' + 
                '<img src="'+data_uri+'"/>';

                var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');

               document.getElementById('mydata').value = raw_image_data;
               document.getElementById('myform').submit();
        } );
    }

</script>

Upvotes: 1

Views: 1784

Answers (1)

Touheed Khan
Touheed Khan

Reputation: 2151

Try below code, it will convert your base64 data to png and save it with random name.

I am assuming you are doing everything right, just doing mistake while converting base64 to image.

Code :

<?php

if(isset($_POST["mydata"])) {
    define('UPLOAD_DIR', 'uploads/');
    $encoded_data = $_POST['mydata'];
    $img          = str_replace('data:image/jpeg;base64,', '', $encoded_data );
    $data         = base64_decode($img);
    $file_name    = 'image_'.date('Y-m-d-H-i-s', time()); // You can change it to anything
    $file         = UPLOAD_DIR . $file_name . '.png';
    $success      = file_put_contents($file, $data);
}

Upvotes: 3

Related Questions