Canvas always returns images in png format. But for crystal report, it does not accept png. So it is necessary to convert png to jpeg image format.
Steps:
1. From base64 get byte array. (png)
2. then convert to a logical file. (png)
3. get the logical file and convert it to a jpeg file (bitmap png to jpeg)
4. get a jpeg logical file and convert it to the binary array.
5. save in the database. Field Type varbinary(max)
View::
@model gBanker.Web.ViewModels.MemberInfoViewModel
@{
ViewBag.Title = "DigitalSignature";
Layout = "~/Views/Shared/_LayoutMaster.cshtml";
}
<h2>Add Digital Signature</h2>
@using (Html.BeginForm("DigitalSignature", "newMember", FormMethod.Post, new { id = "drawingForm" }))
{
@Html.HiddenFor(model => model.MemberID)
<div class="row">
<div class="col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.CenterID, htmlAttributes: new { @class = "control-label" })
@Html.TextBox(" ", ViewData["CenterID"].ToString(), new { @ID = "CenterID", @class = "form-control", @readonly = true })
@Html.ValidationMessageFor(model => model.CenterID, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.MemberCode, htmlAttributes: new { @class = "control-label" })
@Html.TextBox(" ", ViewData["MemberCode"].ToString(), new { @ID = "MemberCode", @class = "form-control", @readonly = true })
@Html.ValidationMessageFor(model => model.MemberCode, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-5">
<input type="hidden" name="imageData" id="imageData" />
<input type="hidden" MemberId_Sig="@ViewData["MemberID"]" />
<canvas id="kfCanvas" name="kfCanvas" typeof="jpg" height="300px;" width="400px;" style="border: 3px dotted #000; cursor: crosshair;">
Sorry, your browser doesn't support canvas technology.
</canvas>
</div>
<div class="col-md-3">
<input type="submit" id="btnSave" class="btn btn-success" onfocus="SetBase64();" value="Save Signature" />
<input type="button" id="btnClear" class="btn btn-warning" value="Clear" onclick="erase();" />
</div>
</div>
<div class="row">
<div class="col-md-3"><h4>4 of 4 pages</h4><label>@ViewBag.Message</label></div>
<div class="col-md-3">
<div class="form-group">
</div>
</div>
</div>
<div class="row">
<div style="height:350px; margin:10px;">
<img id="rsDiagram" src="" class="partDiagram">
</div>
<!-- Button for calling ajax request -->
<button type="button" class="btn btn-primary" onclick="ShowImage();" data-toggle="modal" data-target="">
Load Signature
</button>
</div>
<img id="rsDiagram2" src="" class="partDiagram">
}
<script>
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2.5;
function initSignatureInput() {
canvas = document.getElementById('kfCanvas');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function color(obj) {
switch (obj.id) {
case "green":
x = "green";
break;
case "blue":
x = "blue";
break;
case "red":
x = "red";
break;
case "yellow":
x = "yellow";
break;
case "orange":
x = "orange";
break;
case "black":
x = "black";
break;
case "white":
x = "white";
break;
}
if (x == "white") y = 14;
else y = 2.5;
}
function draw() {
ctx.beginPath();
ctx.lineCap = 'round';
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Want to clear");
if (m) {
ctx.clearRect(0, 0, w, h);
}
}
//function draw2() {
// ctx.beginPath();
// ctx.moveTo(prevX, prevY);
// ctx.lineTo(currX, currY);
// ctx.strokeStyle = x;
// ctx.lineWidth = y;
// ctx.stroke();
// ctx.closePath();
//}
function findxy(res, e) {
// var staticX = 33, staticY = 13;
var staticX = 30, staticY = 120;
if (res == 'down') {
prevX = currX;
prevY = currY;
//currX = e.clientX - (canvas.offsetLeft+235);
//currY = e.clientY - (canvas.offsetTop +135);
currX = (e.pageX - canvas.offsetLeft) - canvas.width / 2;
currY = (e.pageY - canvas.offsetTop) - canvas.height / 2;
currX -= staticX;
currY -= staticY;
flag = true;
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
// currX = e.clientX - (canvas.offsetLeft + 235);
// currY = e.clientY - (canvas.offsetTop + 135);
currX = (e.pageX - canvas.offsetLeft) - canvas.width / 2;
currY = (e.pageY - canvas.offsetTop) - canvas.height / 2;
currX -= staticX;
currY -= staticY;
draw();
}
}
}
initSignatureInput();
function SetBase64() {
var image = document.getElementById("kfCanvas").toDataURL("image/png");
//var image = document.getElementById("kfCanvas").toDataURL();
// image = image.replace('data:image/png;base64,', '');
//image = image.replace('data:image/png;base64,', '');
document.getElementById('rsDiagram2').src = image;
//var rsDiagram = $("#rsDiagram").attr('src');
$('#imageData').val(image);
}
function ShowImage() {
//alert($('#MemberID').val());
$.ajax({
type: "GET",
url: "/NewMember/RSView/",
data: { MemberID: $('#MemberID').val() },
success: function (response) {
// console.log(response);
// alert(response);
$("#rsDiagram").attr('src', 'data:image/png;base64,' + response);
},
error: function (response) {
alert(response.responseText);
}
});
}// END Show Image
$(document).ready(function () {
});// END document Ready
</script>
IN Controller:
[HttpPost]
public ActionResult DigitalSignature()
{
string Message_ = "Signature Saved.";
MemberInfoViewModel obj = new MemberInfoViewModel();
try
{
NameValueCollection nvc = Request.Form;
string memberIDs = nvc["MemberID"];
var imageDatas = nvc["imageData"];
var member = memberService.GetByIdLong(Convert.ToInt32(memberIDs));
ViewData["CenterID"] = centerService.GetById(member.CenterID).CenterName;
ViewData["MemberID"] = member.MemberID;
ViewData["MemberCode"] = member.MemberCode;
imageDatas = imageDatas.Substring(22);
byte[] data = Convert.FromBase64String(imageDatas);
// test: Save image
string fileName = Guid.NewGuid().ToString() + ".png";
byte[] imageBytes = data;
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
image.Save(Server.MapPath("~/CapturedImages/" + fileName),
System.Drawing.Imaging.ImageFormat.Png);
//prphoto.ImageName = "/Uploads/" + fileName;
// END Save Image
// Get Image and Convert to jpg
// Assumes myImage is the PNG you are converting
string imageName = Server.MapPath("~/CapturedImages/" + fileName);//@"~/CapturedImages/" + fileName;
//var ifExist = System.IO.File.Exists(imageName);
var imageFile = System.IO.File.Open(imageName, FileMode.Open);
Image myImage = Image.FromStream(imageFile);
//myImage.Save(Server.MapPath("~/CapturedImages/" + fileName),
// System.Drawing.Imaging.ImageFormat.Jpeg);
string fileNameJPEG = "";
using (var b = new Bitmap(myImage.Width, myImage.Height))
{
b.SetResolution(myImage.HorizontalResolution, myImage.VerticalResolution);
using (var g = Graphics.FromImage(b))
{
g.Clear(Color.White);
g.DrawImageUnscaled(myImage, 0, 0);
}
myImage.Dispose();
imageFile.Close();
fileNameJPEG = Guid.NewGuid().ToString() + ".jpeg";
b.Save(Server.MapPath("~/CapturedImages/" + fileNameJPEG),
System.Drawing.Imaging.ImageFormat.Jpeg);
}
// END jpg
// Convert jpeg to byte Array and save
string imageNameJPEG = Server.MapPath("~/CapturedImages/" + fileNameJPEG);//@"~/CapturedImages/" + fileName;
//var ifExistJPEG = System.IO.File.Exists(imageNameJPEG);
var imageFileJPEG = System.IO.File.Open(imageNameJPEG, FileMode.Open);
var memoryStream = new MemoryStream();
imageFileJPEG.CopyTo(memoryStream);
var dataJPEG = memoryStream.ToArray();
imageFileJPEG.Close();
var objs = memberService.GetById(Convert.ToInt32(memberIDs));
objs.DigitalSignature = dataJPEG;
memberService.Update(objs);
// Delete png and JPEG file
System.IO.File.Delete(imageNameJPEG);
System.IO.File.Delete(imageName);
//END Delete
//var objs = memberService.GetById(Convert.ToInt32(memberIDs));
//objs.DigitalSignature = data;
//memberService.Update(objs);
}
catch (Exception ex)
{
return GetErrorMessageResult("Sorry, Please try again.");
}
ViewBag.Message = Message_;
return GetSuccessMessageResult("Signature Added.");
}
public ActionResult RSView(long MemberID)
{
var member = memberService.GetByIdLong(Convert.ToInt32(MemberID));
string fileToSend = Convert.ToBase64String(member.DigitalSignature);
return Json(fileToSend,JsonRequestBehavior.AllowGet);
}
No comments:
Post a Comment