在PHP上解码base64图像得到空白图像

时间:2018-08-05 07:00:04

标签: php image codeigniter base64

我正在尝试在php上解码base64图像,但是出现黑屏显示Windows不支持此类文件的空白图像。

这是我的代码

public function uploadfoto(){
    $img = $_POST['foto'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $filedir = "./assets/upload/presensi/mx_" . mktime() . ".jpg";
    $filename = "mx_".mktime().".jpg";

    $result = file_put_contents($filedir, $data);
}

我从网络摄像头获取图像,这是我的观点

<form id ="inputfoto">
    <div id="my_camera" style="width: 320px; height: 240px;" class="center"></div>
    <!-- First, include the Webcam.js JavaScript Library -->
    <script type="text/javascript" src="<?php echo base_url();?>assets/dist/js/webcamjs/webcam.js"></script>

    <!-- Configure a few settings and attach camera -->
    <script language="JavaScript">
        Webcam.set({
            width: 320,
            height: 240,
            image_format: 'jpeg',
            jpeg_quality: 100
        });
        Webcam.attach( '#my_camera' );
    </script>
    <div id="results" align = "middle" >Hasil akan tampil di sini</div>
    <input type="button" value="Take Snapshot" onclick="take_snapshot()" class="center" style="margin-bottom: 5px;">
    <input type="button" value="Submit" onClick="saveSnap()" class="center">
</form>

<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>HASIL</h2>' + 
                '<img id="foto" src="'+data_uri+'"/>';
        } );
    }
    function saveSnap(){
        var file =  document.getElementById("foto").src;
        var formdata = new FormData();
        formdata.append("foto", file);
        var ajax = new XMLHttpRequest();
        ajax.open("POST", "<?php echo base_url();?>asisten/presensi/uploadfoto");
        ajax.send(formdata);
    }
</script>

这是 Blank Image

我的代码有什么问题?非常感谢您的回复。

1 个答案:

答案 0 :(得分:0)

This code works for me.Please check it

$image = $this->generateImage($_POST['foto']);

public function generateImage($img)
    {

        $folderPath = "uploads/";
        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("uploads/", $image_parts[0]);
        $image_base64 = base64_decode($image_parts[1]);
        $name = uniqid() . '.png';
        $file = $folderPath . $name;
        file_put_contents($file, $image_base64);
        return $name;

    }