如何将图像画布保存到文件夹?

时间:2015-11-11 08:57:05

标签: c# asp.net-mvc canvas

我需要使用ajax或javascript来保存画布图像...... !! TKS!

我的观点

@using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{

                <canvas id="myCanvas" width="352" height="352"
                        style="border: 1px solid #d3d3d3;">
                    Your browser does not support the HTML5 canvas tag.
                </canvas>
                <input type="hidden" name="imageData" id="imageData"/>
                <input type="button" id="btnSave" value="Save Drawing"/>
}


[HttpPost]  
public ActionResult SaveImage(CampaignViewModel model, string imageData)
 {
     //code.....
     return RedirectToAction("Index", "Home");
 }

2 个答案:

答案 0 :(得分:0)

在视图中:

      @using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
    {
         <canvas id="myCanvas" width="352" height="352"
                            style="border: 1px solid #d3d3d3;">
                        Your browser does not support the HTML5 canvas tag.
                    </canvas>
        <input type="hidden" name="imageData" id="imageData"/>
        <input type="button" onclick="saveimage(event)" id="btnSave" value="Save Drawing" />
        <img style="display: none" src="images/ajax-loader/ajax-loader.gif" id="progressbar"/>
    }

   @*call action*@
<script>
    function saveimage(event) {
        @*prevent call back to server*@
        event.preventDefault();
        @*show progress bar *@
        var progress = document.getElementById("progressbar");
        $(progress).css('display', 'block');
        @*get form data *@
        var data = $("#drawingForm").serialize();
        @*save image information to imageData tag  *@
        var image = document.getElementById("myCanvas").toDataURL("image/png");
        image = image.replace('data:image/png;base64,', '');
        $("#imageData").val(image);

         @*make ajax call *@
        $.ajax({
            url: "/Campaign/SaveImage",
            data: data,
            type: "Post",
            dataType: "Json",
            success: function (data) {
                //do something
            },
            error: function (xhr, status, error) {
                //do something
            },
            complete: function (data) {
                $(progress).css('display', 'none');
            }
        });
    }</script>

并在控制器中:

[HttpPost]
        public ActionResult SaveImage(CampaignViewModel model, string imageData)
        {
            //path of folder taht you want to save the canvas
            var path = Server.MapPath("~/images/canvaseimg");
            //produce new file name
            var fileName =   GetPictureName(path);
            //get full file path
            var fileNameWitPath = Path.Combine(path, fileName);

            //save canvas
            using (var fs = new FileStream(fileNameWitPath, FileMode.Create))
            {
                using (var bw = new BinaryWriter(fs))
                {
                    var data = Convert.FromBase64String(imageData);
                    bw.Write(data);
                    bw.Close();
                }
                fs.Close();
            }

            //do somthing with model
            return RedirectToAction("Index", "Home");
        }

答案 1 :(得分:0)

我们在ImindQ Online中将画布导出为PNG,并为您的场景添加以下适用的代码:

在视图中:

<!DOCTYPE html>   
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Image</title>
</head>
<body>
    <div> 
        @using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
        {   
            <canvas id="myCanvas" width="352" height="352"
                    style="border: 1px solid #d3d3d3;">
                Your browser does not support the HTML5 canvas tag.
            </canvas>
            <input type="hidden" name="imageData" id="imageData" />
            <input type="button" id="btnSave" value="Save Drawing" />
        }

        <script>
            (function () {
                document.getElementById('btnSave').addEventListener('click', function () {
                    var r = new XMLHttpRequest();
                    r.open("POST", "SaveImage", true);
                    r.onreadystatechange = function () {
                        if (r.readyState != 4 || r.status != 200) return;                            
                    };
                    var p = document.getElementById('myCanvas').toDataURL('image/png').replace('data:image/png;base64,', '');
                    r.send(p);
                });
            })();
        </script>
    </div>
</body>
</html>
控制器中的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace WebApplication2.Controllers
{
    //public class CampaignViewModel
    //{
    //    public string ImageData { get; set; }
    //}

    public class CampaignController : Controller
    {
        // GET: Campaign
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SaveImage()
        {
            int len = (int)Request.InputStream.Length;
            byte[] buffer = new byte[len];
            int c = Request.InputStream.Read(buffer, 0, len);
            string png64 = Encoding.UTF8.GetString(buffer, 0, len);
            byte[] png = Convert.FromBase64String(png64);
            System.IO.File.WriteAllBytes("d:\\a.png", png);
            //string pngz = Encoding.UTF8.GetString(png, 0, png.Length);
            //code.....
            return RedirectToAction("Index", "Home");
        }
        //
    }
}