Upload canvas images

Task:  take a snapshot from camera (using canvas) and save it to the server as a file

 

Cshtml:

 

<canvas id="canvas" width="640" height="480"></canvas>

                <div style="text-align: center">            

                    <button data-bind="click: openCamera">Take another Snapshot</button>

                    <button data-bind="click: function () { saveSnapshot(document.getElementById('canvas').toDataURL('image/jpeg')); }">Save</button>

                </div>

 

Javascript code:

 

takeCameraSnapshot = function () {

 $.post('/Story/' + this.StoryId + '/SaveSnapshot', { dataURL: snapshot },  (data, status) => {

                this.imageUrl(data);

                this.selectedView('edtiTile');

            });

 

 

openCamera = function () {

            // show camera

            this.selectedView('takePictureFromCamera');

            this.isCameraVisible(true);

            var video = $('#takePictureFromCamera video')[0];

            (navigator).webkitGetUserMedia({

                video: true

            }, function (stream) {

                video.src = (window).webkitURL.createObjectURL(stream);

                video.play();

            }, function (error) {

                return console.log("Video capture error: ", error.code);

            });

        };

 Server size:

 

        static string path = @"C:\work\ComicTales\ComicTales.Web\Upload\";

 

        [HttpPost]

        public ActionResult SaveSnapshot(string id, string dataURL)

        {

            string fileNameWitPath = string.Empty;

            string pathSuffix = string.Empty;

            string tick = DateTime.Now.Ticks.ToString();

     // For Chrome browsers

            if (dataURL.Contains("jpeg"))

            {

                 // To remove the Prefix 'data:image/png;base64,'

         dataURL = dataURL.Remove(0, 23);

                pathSuffix = ".jpeg";

               

            }

            // For Explorer browsers

            else if (dataURL.Contains("png"))

            {

                dataURL = dataURL.Remove(0, 22);

                pathSuffix = ".png";

            }

            fileNameWitPath = path + tick + pathSuffix;

            using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))

            {

                using (BinaryWriter bw = new BinaryWriter(fs))

                {

                    byte[] snapshotData = Convert.FromBase64String(dataURL);

                    bw.Write(snapshotData);

                    bw.Close();

 

                }

            }

 

             // Need to return the full image name to the client

return Json(tick + pathSuffix, JsonRequestBehavior.AllowGet);

        }

 

 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com