下面的代码使用了一个名为cropit的插件提供的base64字符串,并将其转换为图像。
list($type, $base64) = explode(';', $base64);
list(, $base64) = explode(',', $base64);
$base64 = str_replace("data:image/jpeg;base64,", "", $base64);
$base64 = base64_decode($base64);
file_put_contents($directory, $base64);我还将提供我的javascript,它通过使用输入将base64发送到php函数。我知道这个问题是由PHP引起的,因为当我将imageData发送到一个新窗口时,图像将完美地显示出来,没有任何问题。
$('.export_upload').click(function() {
$("#upload_form_identifier").val("upload_form");
var imageData = $('.image-editor-upload').cropit('export', {
type: 'image/jpeg',
quality: 0.3,
originalSize: true
});
//Set value of hidden input to base64
$("#hidden_base64_upload").val(imageData);
//Pause form submission until input is populated
window.setTimeout(function() {
document.upload_form.submit();
}, 1000);
});我的问题是,如果我输入一个图像,它会把它剪辑成一个随机点。PHP会耗尽内存吗?我对base64不是很有经验,所以我真的不知道是什么原因造成了这种情况。任何帮助都会很好。
原始图像:

在PHP处理完base64之后:

发布于 2016-05-02 23:14:11
虽然这不是最好的解决方案,但它适合我,而且可能适合您的需要。我发现的问题是,使用originalSize: true可以导出图像的裁剪部分,而不需要进行任何压缩,从而导致非常大的base64。解决这个问题的方法是将originalSize设置为false,然后将预览调整到我将使用的大小。下面的代码应该有效。
$('.export_upload').click(function() {
$("#upload_form_identifier").val("upload_form");
$('.image-editor-upload').cropit('previewSize', {width:1024, height:1024});
var imageData = $('.image-editor-upload').cropit('export', {
type: 'image/jpeg',
quality: .75,
originalSize: false
});
//Set value of hidden input to base64
$("#hidden_base64_upload").val(imageData);
//Pause form submission until input is populated
window.setTimeout(function() {
window.open(imageData);
document.upload_form.submit();
}, 1000);
});关键是$('.image-editor-upload').cropit('previewSize', {width:1024, height:1024});。这将使图像在发送到php函数之前调整大小。唯一真正的问题是,如果用户修改javascript,他们将能够更改图像的输出大小,但如果您使用php验证上传以确保宽度和高度与您放在括号内的内容相匹配,则不应该出现此问题。
我今天想出了一个基本的验证功能。如果图像的尺寸是否正确,它将返回真假。您可以将其应用到正在设置图像的初始表单中,并检查其是否匹配,并相应抛出错误。
/**
* Checks the dimensions of the provided image
* @param string $base64_image Base64 string of the image
* @param string $width Desired width of the image
* @param string $height Desired height of the image
* @return bool True if dimensions match, false if dimensions do not match
*/
public function checkImageDimensions ($base64_image, $width, $height) {
list($type, $base64_image) = explode(';', $base64_image);
list(, $base64_image) = explode(',', $base64_image);
$base64_image = base64_decode($base64_image);
$dimensions = getimagesizefromstring($base64_image);
if ($dimensions[0] == $width && $dimensions[1] == $height) {
return true;
} else if ($dimensions[0] !== $width && $dimensions[1] !== $height) {
return false;
}
}https://stackoverflow.com/questions/36991401
复制相似问题