在PHP中使用cordova将base64字符串保存为图像


saving base64 string as image in php using cordova

我试图将捕获的图像保存在服务器上为jpg/png,我将字符串解码为base64并上传,但当我打开图像时,它说'文件无法打开'。我不明白为什么会发生这种情况,或者我只是错过了任何代码。

jquery

navigator.camera.getPicture(onSuccess, onFail, { quality: 100,destinationType: Camera.DestinationType.DATA_URL });
function onSuccess(imageURI) {
 var image = document.getElementById('dr_preview');
 image.src = imageURI;
 snapSrc = imageURI;
}
var img = document.getElementById('dr_preview');
var src = $('#dr_preview').attr('src');
console.log(src);
var dataparam = 'type=3&dr='+dr_value+'&image='+src;
$.ajax({
        type: 'POST',
        dataType: 'json',
        async: true,
        url: 'http://localhost/v_2/dr-getDrDetails.php',
        data: dataparam,
        cache: true,
        success: function(data)
        {
        }
 });
php

$data = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/'w+;base64,#i', '', $data));
$filePath = $_SERVER['DOCUMENT_ROOT']. '/v_2/scanedDR/'.$dr.'.PNG';
$file = fopen($filePath, 'w');
fwrite($file, $data);
fclose($file);

您可以使用此函数将base64转换为图像。

function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb"); 
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1])); 
fclose($ifp); 
return $output_file; 
}