We are generating the Canvas from the image you have in that div with the function getBase64. I did it in the most generic way, you'll have to give it to play with the variables to get what you want.
<html>
<head></head>
<script>
function getBase64Image() {
var img = document.getElementById("LaImagenAprocesar");
// creamos un canvas en blanco
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copiamos el contenido de la imagen al canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Obtenemos el data-URL con formato de la imagen
// Firefox soporta PNG y JPEG. Ojo aqui, hay que revisar
// el img.src al formato original, ten cuidado si utilizas image/jpeg,
// porque esto le dara un re-encode a la imagen
var dataURL = canvas.toDataURL("image/png");
return alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
}
</script>
<body>
<div>
<img id="LaImagenAprocesar" src="unaimagen.png" alt="">
<button type="button" onclick="getBase64Image()">mostrar data-url</button>
</div>
</body>
</html>
With that string, use an Ajax Request
or a post
to send it to the controller. That variable with the name "myCadenaEnBase64" must be obtained from the previous method and well, I present you to Ajax using jQuery, it would be like this:
$.ajax({
cache: false,
async: true,
type: "POST",
url: "http://example.com/MiControlador/Create",
data: {
imageData: miCadenaEnBase64
},
success: function () {
alert('Se ha guardado la imagen!');
}
});
Here the implementation in the controller
[HttpPost]
public ActionResult Create(string imageData)
{
string fileName = "NombreDelArchivo.png";
string fileNameWitPath = Path.Combine(Server.MapPath("~/FolderToSave"), fileName);
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
fs.Close();
}
return RedirectToAction("Index");
}
By the way, check to have write permissions in this folder.