我已经在互联网上搜索了一段时间,但找不到任何可以告诉我如何从 $('#image-cropper').cropit('export')
转换结果的信息转换为 PHP 可以上传到服务器的图像。我正在使用 Cropit 插件,我所需要的只是一张可以传递到我的 php 上传脚本中的图像。我的代码如下:
HTML:
<div id="image-cropper">
<input type="file" class="cropit-image-input" />
<div class="cropit-image-preview"></div>
<input type="range" class="cropit-image-zoom-input" />
<button class="export">Export</button>
</div>
jQuery:
var username = "<?php echo $userData['username']; ?>";
$('#image-cropper').cropit({
imageState:{
src:'users/'+username+'/profile_picture.jpg'
},
});
$('#image-cropper').cropit('previewSize', {width:500, height:500});
$('.export').click(function() {
var imageData = $('#image-cropper').cropit('export');
//$("#code").val(imageData);
window.open(imageData);
});
这里的代码对于插件来说工作正常,但我无法将看起来像 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD...
的结果转换成我可以的图像在 php 脚本中使用。任何帮助都会很棒。谢谢!
最佳答案
我让它工作的方法是搞乱 Cropit 的质量设置并创建一个 PHP 函数来读取 base64 字符串并将其转换为图像。
以下代码适用于 cropit。我正在设置超时,因为如果你不这样做,它会在 cropit 创建 base64 之前将表单发送到 php。 base64 字符串只是存储在一个文本字段中,php 可以根据 $_POST
//Initiate Cropper
$('.image-editor').cropit();
//Assign Export Function
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export', {
type: 'image/jpeg',
quality: 0.33,
originalSize: true,
});
//Set value of hidden input to base64
$("#hidden_base64").val(imageData);
//Pause form submission until input is populated
window.setTimeout(function() {
document.upload_form.submit();
alert(imageData);
}, 1000);
});
下面的代码是针对 php 的。它通过解码 base64 然后将其移动到指定目录来工作。
function decode ($code, $username) {
list($type, $code) = explode(';', $code);
list(, $code) = explode(',', $code);
$code = base64_decode($code);
file_put_contents('directory/filename.jpg', $code);
}
关于php - 如何将图像从 cropit 导出到 php 以进行上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125836/