I am in the process of developing an administrator system that allows users with admin privileges to create new user accounts. One of the requirements for creating a user account is uploading a photograph.
To enhance user experience, I have integrated a file upload feature and I am also exploring the option of using a webcam to capture an image directly.
Although I have successfully implemented this functionality, I encountered an issue where the saved image on the server appears cropped at the bottom.
My initial assumption was that the problem might be related to the dimensions of the canvas or video elements used in the process. I attempted to adjust these sizes manually but it did not resolve the cropping issue.
Visually, the captured image from the video element displays correctly on the canvas as intended. Additionally, I have included a text box bound to the Model to send the canvas data as text to the server.
Below is the code snippet:
<video id='v' class="employee-image-display"></video>
@Html.TextBoxFor(m => m.WebcamImageData, new { id = "tbWebcamImage" })
<a class="btn btn-block red" id="btnTakePhoto">
<i class="fa fa-camera"></i>
</a>
<canvas id="canvas"></canvas>
Javascript:
function TakePhoto() {
var canvas = $('#canvas')[0];
//set canvas width/height
canvas.width = 600;//v.videoWidth;
canvas.height = 600;//v.videoHeight;
canvas.getContext('2d').drawImage(v, 0, 0, 600, 600, 0, 0, 600, 600);
//get image data from canvas
var imgData = canvas.toDataURL("img/png");
imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "");
$('#tbWebcamImage').val(imgData);
}
function StartWebCam() {
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia(
{
video: true,
audio: false
},
function (stream) {
var url = window.URL || window.webkitURL;
v.src = url ? url.createObjectURL(stream) : stream;
v.play();
},
function (error) {
alert('Something went wrong. (error code ' + error.code + ')');
return;
}
);
}
else {
alert('Sorry, the browser you are using doesn\'t support getUserMedia');
return;
}
}
$(document).ready(function () {
$('#btnTakePhoto').on('click', function () {
TakePhoto();
});
StartWebCam();
});
Controller Action:
if (!string.IsNullOrWhiteSpace(model.WebcamImageData))
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(bytes);
stream.Seek(0, SeekOrigin.Begin);
string filepath = "~/Content/Images/Employees/test.png";
System.IO.File.WriteAllBytes(Server.MapPath(filepath), bytes);
}
}
}
https://i.sstatic.net/hZiUo.png
Upon reviewing the images linked above, you can observe that the cropped version does not show the entire image (missing my chest area), while the uncropped version displays correctly.
Seeking advice from anyone who can pinpoint why the image is cropped – Is the error occurring on the client side or server side?