Developing a C# MVC platform that allows users to save canvas designs as image files on the server, with the added functionality of

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?

Answer №1

Which web browser do you use?

For proper video and canvas dimension settings, consider implementing the following code:

var v = document.getElementById('v');
var c = document.getElementById('c');
var canvasWidth = 600;
var canvasHeight = 600;

// Ensure video stream is ready to play
v.addEventListener('canplay', function (e) {
    if (!isStreaming) {
        // Adjust canvas dimensions based on video aspect ratio
        if (v.videoWidth > 0) {
            canvasHeight = v.videoHeight / (v.videoWidth / canvasWidth)
        }
        v.setAttribute('width', canvasWidth);
        v.setAttribute('height', canvasHeight);
        c.setAttribute('width', canvasWidth);
        c.setAttribute('height', canvasHeight);
        isStreaming = true;
    }
}, false);

To enhance cross-browser compatibility in your code, add the following snippet:

// Cross browser support
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

if (navigator.getUserMedia) {
    // Request access to video feed only
    navigator.getUserMedia(
                {
                    video: true,
                    audio: false
                },
                function (stream) {
                    // Apply cross-browser compatibility checks
                    var url = window.URL || window.webkitURL;
                    v.src = url ? url.createObjectURL(stream) : stream;
                    // Start playing the video
                    v.play();
                },
                function (error) {
                    alert('An error occurred. Error code: ' + error.code);
                }
    );
}
else {
        alert('Unfortunately, your current browser is not supported.');
        return;
     }

UPDATE: To fit the context, include the following code:

var con = c.getContext('2d');
con.drawImage(v, 0, 0, canvasWidth, canvasHeight);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

What are the reasons behind the lack of clarity in the cache for an ajax request

I am encountering an issue with my external JavaScript file that is supposed to run the home.php file using an Ajax request. Despite adding a random function to the URL to clear the cache, I am still facing issues with caching in my code. Below is the Ja ...

Instructions for setting the value of a <input> element using scope

Having Trouble Passing Scope Value to Hidden Input Type I am facing an issue with passing the scope value to a hidden input type. Despite my efforts, I am unable to make it work as intended. Instead of displaying "PremiumVal", I need it to display "75" ba ...

Swap out the content within the selected element

Let's imagine we have the following shopping list: export default { data() { return { items: { Apple, Orange, Appricot } } } } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js" ...

Navigating on Blogger can be a tricky task when it comes to searching and

I recently added a Table to my blogger post, along with an input form for readers to easily search data. After finding the code on W3Schools (link here), I implemented it successfully. However, I am looking to make some improvements. Here is my question: ...

Local Storage State Persistence Issue with React Checkbox Component

I am currently working on a React component that features a checkbox. My goal is to have the checkbox toggle between on and off states and save this state in local storage so that even when navigating to another page, the toggle will remain in its previous ...

I am interested in extracting specific data from the JSON response

I am trying to extract the value of the message parameter under the messages array where the parameter name is equal to documentId (highlighted in bold below). However, the code I have tried so far does not achieve this as needed. dynamic obj = JsonConver ...

Verify the information received from the ajax call to PHP

After incorporating all the guidance I received, I performed an update and here are the results: UPDATED CODE: $(document).ready(function(){ $("#submit").submit(function(e){ e.preventDefault(); var username = $("#username").val(); var ...

Updating TextBox Content upon task accomplishment

I'm currently working on a WinForms application with two forms. In the first form, users input information and then click a button to move to the second form. Upon doing so, form1 is hidden, form2 loads, and a task (whose function is defined in form1) ...

The NPM START ERROR message is indicating a problem with locating a file in npm

Having an issue with npm while trying to set up a basic server using node.js. Hello network! I've searched through forums, videos, and articles for solutions, but none have resolved my problem. The error message indicates that the package.json file ...

What is preventing me from being able to reach the instance of Cropper JS?

I'm facing some issues with executing the loadImage() function as I am unable to access the variable cropper. My ultimate objective is to run cropper.getCroppedCanvas and save its output value into an input field so that I can transmit it via AJAX. T ...

How to run a series of diverse SQL queries using OracleCommand in C#

My goal is to execute various SQL statements using OracleCommand. var conn = new OracleConnection("User Id=SYSTEM;Password=mw;Data Source=SampleDataSource"); // Open the connection if (conn.State != ConnectionState.Open) conn.Open(); string sql = @" ...

When jQuery updates the content, the div content disappears temporarily

I am currently using jQuery to generate HTML by fetching data from a JSON file. Below is the code snippet where I create the HTML: $(document).ready(function () { $('#searchForm').submit(function () { var entry= $("#searchFo ...

How to remove a specific item from an array in MongoDB using JavaScript

So, I've retrieved a nested array from a database query. The query brings back the following data: { _id: new ObjectId("623rf3f22275f399f88bb"), first_name: 'Are', last_name: 'You', email: '<a href="/cdn-cgi/l/email ...

The function is failing to provide a return value

In the Game.js file, there is a function that I am working on Game.prototype.onClick = function(event){ var x = event.x; var y = event.y; if (this.blueDeck[0].contains(x, y)) alert("Blue Deck Clicked"); } The OnClick function is ca ...

Tips for simulating external module method?

I have come across a module containing a function: const utilities = { redirectTo(url) { if (url) { window.location = url; } }, }; export default utilities; This function is being used in a React component as follows: import utilities ...

What is the best way to employ TypeScript for passing parameters to JavaScript functions that utilize the arguments object?

Using Angular 8 at the moment and attempting to implement a script from someone else. However, I am facing an issue due to my lack of knowledge in this area. The function in the javascript operates like this: window.X = function() { var e = argument.l ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

Automating the box selection process using table-react functionality

I am facing an issue with table-react. I need to implement a functionality where certain checkboxes should be checked based on user permissions. For instance, if the user has an id = 3 and can view companies with ids: 5, 6, 7, the checkboxes corresponding ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...