Save a GoogleMaps image on server with ASP.NET MVC 4 and C#

I am making a site where I use Google Maps API, generate coordinates and search for a specific site, then I take a capture of the site with html2canvas to generate an image in a <img>, my question is:

How can I bring this image to the controller?

This is the div in which the image is:

<div id="googlemapimage">
    <img id="googlemapbinary" width="640" height="480"/>
</div>

In my controller I am using functions to transform the image as I want, but they were entering by httppostfilebase, can I use the image of the div in the controller? If so, how?

 1
Author: rsciriano, 2016-01-25

2 answers

  1. Let's generate 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 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>
    
  2. With that string, use an Ajax Request or a post to send it to the controller. That name variable "miCadenaEnBase64" you should get it from the above method and well, I introduce you to the 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!');
        }
    });
    
  3. 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 on that folder.

 2
Author: fredyfx, 2016-01-28 22:21:02

If you are applying this technique

HTML5 Canvas Save Drawing as an Image

Or you use the toDataURL() then you are assigning to the img an image whose encode is base64. You can validate this I comment with this example

HTML5 Canvas: toDataURL()

There you will see how the image is generated in base64 and assigned to the img, it is as well as the tomarias of the img to send it to the controller.

Get image data in JavaScript?

You basically have to put in a variable in javascript the base64 content, but removing the part that defines the image type.

Then in asp.net mvc defines an action with a parameter of type string that will receive the image in base64. To invoke the action Use $.ajax, $.post and in the parameters you send the image as string.

In the controller you use Convert.FromBase64String to get the byte array of the image.

 0
Author: Leandro Tuttini, 2017-05-23 12:39:20