I am trying to take a photo with a webcam, crop it using jcrop jquery library, and upload the cropped photo to a server. Regardless of the size of the thumbnail, it always ends up with a width of 300 pixels and a height of 150 pixels.
For the webcam photo capture, I've been using a jQuery webcam plugin: http://www.xarg.org/project/jquery-webcam-plugin/. I've also tried one that uses getusermedia https://github.com/MrSwitch/jquery.getUserMedia.js.
Uploading just the webcam snaptshot works correctly and is the expected size.
My 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>');
}
});
});
Simple Test 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.';
My 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>
Is that code exactly what you are trying to use?
My guess would be you have a canvas which is still at the default size (which just happens to be 300x150) which is causing that to be the image that is sent to your server and saved.
Also, why do you have your preview with a style width and height instead of setting the actual width and height?