1

我正在尝试使用网络摄像头拍照,使用 jcrop jquery 库对其进行裁剪,然后将裁剪后的照片上传到服务器。无论缩略图的大小如何,它总是以 300 像素的宽度和 150 像素的高度结束。

对于网络摄像头照片捕获,我一直在使用 jQuery 网络摄像头插件:http ://www.xarg.org/project/jquery-webcam-plugin/ 。我还尝试了一种使用 getusermedia https://github.com/MrSwitch/jquery.getUserMedia.js的方法。

仅上传网络摄像头快照可以正常工作,并且是预期的大小。

我的JavaScript:

$('#canvas').Jcrop({
        boxWidth: 320,
        boxHeight: 240,
        onChange:   updatePreview,
        onSelect:   updatePreview,
        addClass: 'jcrop-dark',
        aspectRatio : 1},function(){
    jcrop_api = this;
 });

 function showPreview(coords)
{
    var rx = 100 / coords.w;
    var ry = 100 / coords.h;

    $('#preview').css({
        width: Math.round(rx * 320) + 'px',
        height: Math.round(ry * 240) + 'px',
        marginLeft: '-' + Math.round(rx * coords.x) + 'px',
        marginTop: '-' + Math.round(ry * coords.y) + 'px'
    });
}

function updatePreview(c) {
    if(parseInt(c.w) > 0) {
        // Show image preview
        var imageObj = $("#canvas")[0];
        var canvas = $("#preview")[0];
        var context = canvas.getContext("2d");
        context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height);
    }
};
$('#save').click(function(){
    var imgData = document.getElementById('canvas').toDataURL();
    var postStr = "img=" + encodeURIComponent(imgData);
    $.ajax({
        type: 'POST',
        url: '{{ path('photo_upload') }}',
        data: postStr,
        async: false,
        processData: false,
        error: function(){
            $('.hero-unit').prepend('<div class="alert alert-error">The photo could not be uploaded.<button type="button" class="close" data-dismiss="alert">×</button></div>');
        }
    });
});

简单测试 PHP

define('UPLOAD_DIR', 'photos/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR  . 'photo.png';
$fp = fopen($file, 'wb');
$success=fwrite($fp, $data);
fclose($fp);
print $success ? $file : 'Unable to save the file.';

我的 HTML:

<div id="webcam"></div>
<a href="javascript:webcam.capture();changeFilter();void(0);">Take a picture instantly</a>
<canvas id="canvas" height="240" width="320"></canvas>
<canvas id="preview" style="width:300px;height:300px;overflow:hidden;"></canvas>
<a class="btn btn-primary btn-large" id="save">Save Photo</a>
4

1 回答 1

0

该代码正是您要使用的代码吗?

我的猜测是您的画布仍处于默认大小(恰好是 300x150),这导致它成为发送到您的服务器并保存的图像。

另外,为什么您的预览带有样式宽度和高度,而不是设置实际的宽度和高度?

于 2012-12-12T04:35:21.347 回答