簡體   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