Are canvas.toDataURL compatible with PHP's base64_decode


Are canvas.toDataURL compatible with PHP's base64_decode?

我的问题如下。。。我有一个屏幕,用户可以在其中从计算机中选择PNG图像,使用这个:

<input id='icon' type='file' accept='image/png' style='width:400px; height:20px' onchange='llenarThumbnail(this)'>
<img id='thumb' src='#'>

当用户选择图像时,会自动显示缩略图,使用onclick="Lenar thumbnail(this)",如下所示:

function llenarThumbnail(input){
 if (input.files && input.files[0]){
  var reader = new FileReader();
  reader.onload = function (e){
   $('#thumb').attr('src', e.target.result).width(48).height(48);
  };
  reader.readAsDataURL(input.files[0]);
 }
}

然后,当用户点击合适的按钮上传图像(而不是提交按钮)时,我会执行以下操作将图像编码到Base64:

function getBase64Image(img){
 var canvas = document.createElement("canvas");
 canvas.width = img.width;
 canvas.height = img.height;
 var ctx = canvas.getContext("2d");
 ctx.drawImage(img, 0, 0);
 var dataURL = canvas.toDataURL("image/png");
 console.log(dataURL);
 return dataURL.replace(/^data:image'/(png|jpg);base64,/, "");
}

然后,我使用AJAX将这个编码的图像数据发送到服务器,PHP脚本执行以下操作:

$binary=base64_decode($imagen_data);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen($icono, 'wb');
fwrite($file, $binary);
fclose($file);

当我在这个过程中打印不同的警报时,我可以看到编码正在执行(我不太确定是否正确),PHP接收数据并创建PNG文件,但当我打开图像时,图像是空的,没有数据。。。这就是为什么我要问这个to方法是否兼容。。。我想他们是因为他们都是Base64…但如果不是这样,那我做错了什么???

拜托,我已经厌倦了在网上到处找这个了!我需要一些答案!非常感谢。

在没有看到您的ajax POST的情况下,这里有一个疯狂猜测

尝试保留前缀,直到URL到达php。

您正在使用哪台php服务器?

其他一些常见的问题:

  • 请确保已正确设置上传目录
  • 请确保您对上载目录设置了正确的权限

客户端:

// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();
// post the dataUrl to php
$.ajax({
  type: "POST",
  url: "upload.php",
  data: {image: dataURL}
}).done(function( respond ) {
  // you will get back the temp file name
  // or "Unable to save this image."
  console.log(respond);
});

服务器文件:upload.php

<?php
// make sure the image-data exists and is not empty
// php is particularly sensitive to empty image-data 
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {    
    // get the dataURL
    $dataURL = $_POST["image"];  
    // the dataURL has a prefix (mimetype+datatype) 
    // that we don't want, so strip that prefix off
    $parts = explode(',', $dataURL);  
    $data = $parts[1];  
    // Decode base64 data, resulting in an image
    $data = base64_decode($data);  
    // create a temporary unique file name
    $file = UPLOAD_DIR . uniqid() . '.png';
    // write the file to the upload directory
    $success = file_put_contents($file, $data);
    // return the temp file name (success)
    // or return an error message just to frustrate the user (kidding!)
    print $success ? $file : 'Unable to save this image.';
}

我无法让markE解决方案工作,不得不更改数据修改:

发件人:

$parts = explode(',', $dataURL);  
$data = $parts[1];
$data=base64_decode($data)

收件人:

$img = str_replace('data:image/png;base64,', '', $dataURL);
$img = str_replace(' ', '+', $img);
$data=base64_decode($img);

的方法