繁体   English   中英

如何在PHP中将base64编码转换并存储为图像?

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

我正在尝试拍摄图像摄像头,然后将其存储为jpeg格式的文件。 到目前为止,此代码捕获图像并将其转换为base64编码。 现在如何将其存储在文件夹中。 这是我第一次。 我已经花了很长时间了。 我该如何解决。

的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>

尝试下面的代码,它将把您的base64数据转换为png并以随机名称保存。

我假设您做的一切正确,只是在将base64转换为图像时出错。

代码:

<?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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM