我正在尝试将图像从网络摄像头中取出,然后将其存储为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>
答案 0 :(得分:2)
尝试以下代码,它会将您的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);
}