Phonegap正在取得成功,Laravel告诉我成功,但它始终是白色的。
Phonegap(Android)js的两个相关代码块是:
function sendImage(src) {
window.localStorage.setItem('csrf', csrf);
src = (src == 'library') ? Camera.PictureSourceType.PHOTOLIBRARY : Camera.PictureSourceType.CAMERA;
navigator.camera.getPicture(success, fail, {quality: 45, sourceType: src});
function success(imageData) {
imageData = getBase64Image(imageData);
userId = window.localStorage.getItem("user_id");
var url = 'https://example.com/profile/update/picture';
var params = {photo: 'image/png;space,' + imageData, user_id: userId};
//csrf = window.localStorage.getItem("csrf");
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: params,
headers: {"x-csrf-token": 'notoken'},
async: false,
success: function(res)
{
if(res.success)
{
alert("Success!");
}
},
complete: function(res)
{
},
error: function(res)
{
alert("Error = " + JSON.stringify(res));
}
});
}
function fail(error){
alert('You are FAIL');
}
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
//use this block to not draw image unless image is loaded
var callback = function(image) {
if(!image) image = this;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(image, 0, 0);
}
//check if image is loaded
if(img.complete) {
callback(img);
}else {
img.onload = callback;
}
//get the data-URL formatted image
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
}
在Laravel中,照片正在更新为空白或空白。有一次,我在这里的代码块返回true,因此Laravel至少认为该图像是合法的:
public static function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
答案 0 :(得分:0)
如果您获得空白或透明图像,这意味着您的绘图功能在图像完全上传之前调用。 Javascript工作异步。在你的代码中,在执行callback()函数之前执行了两行。
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");