繁体   English   中英

ASP.NET 核心映像到 Canvas

[英]ASP.NET core image to Canvas

我需要创建一个图像模板,用户可以在其中定义和标记/突出显示/某些区域。 目标是下次当用户上传类似图像时,程序会识别它并自动突出显示模板中定义的区域。

它必须作为 Web 应用程序来完成,所以我使用的是 ASP.net 内核

我想上传一个图像将其保存到 canvas 中,然后通过鼠标矩形在区域上绘制,并以某种方式保存每次 canvas 中的鼠标指针/矩形坐标和大小。

文件上传然后显示图像(不在画布中)工作正常。

但我不知道为什么图像没有加载到 canvas 中。

@{
ViewData["Title"] = "Home Page";
}
<script src="~/js/jquery-2.2.3.min.js"></script>
<form method="post" asp-controller="Home" asp-action="ImageUpload" enctype="multipart/form-data">
        <div class="from-group row">
            <label class="col-sm-2 col-form-label">Scan Datei </label>
            <div class="col-sm-10">
                <div class="custom-file">
                    <input class="from-control custom-file-input" type="file" name="file" onchange="LoadImagetoCanvas()" />
                    <label class="custom-file-label">Datei auswählen</label>
                </div>
            </div>
            <button type="submit">Bild laden</button>
        </div>
        <img calss="custom-image" src="@ViewData["FileLocation"]" width="600" height="400" />
        <canvas id="imageCanvas" height="740" width="1024" runat="server" style="border:2px solid black">
                Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.
            </canvas>

    </form>
    <script>
            $(function () {
                $(".custom-file-input").change(function (e) {
                    var file = e.target.files[0],
                        imageType = /image.*/;

                    if (!file.type.match(imageType))
                        return;

                    var reader = new FileReader();
                    reader.onload = fileOnload;
                    reader.readAsDataURL(file);
                });

                function fileOnload(e) {
                    var $img = $('<img>', { src: e.target.result });
                    $img.load(function () {
                        var canvas = $('#imageCanvas')[0];
                        var context = canvas.getContext('2d');

                        canvas.width = this.naturalWidth;
                        canvas.height = this.naturalHeight;
                        context.drawImage(this, 0, 0);
                    });
                }
            });
    </script>

和 c# 代码:

public class HomeController : Controller
    {
        IHostingEnvironment _env;

        public HomeController(IHostingEnvironment environment)
        {
            _env = environment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task<IActionResult> ImageUpload(IFormFile file)
        {
            if(file != null && file.Length>0)
            {
                string imagePath = @"\Upload\Images\";
                string uploadPath = _env.WebRootPath + imagePath;

                if(!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                string uniqFileName = Guid.NewGuid().ToString();
                string filename = Path.GetFileName(uniqFileName+"."+file.FileName.Split(".")[1].ToLower());
                string fullPath = uploadPath + filename;                    
                imagePath = imagePath + @"\";

                string filePath = @".." + Path.Combine(imagePath, filename);

                using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);                    
                }

                ViewData["FileLocation"] = filePath;
            }

            return View("../Home/Index");
        }
    }

I even tried to add a Javascript Function and calling it from the c# part but without success, as even if the function get called it seems that he can't find my Canvas:

script "text/javascript">
        function LoadImagetoCanvas() {
            var c = document.getElementById("imageCanvas")
            var ctx = c.getContext("2d")
            var imageObj = new Image()
            //imageObj.src = @ViewData["FileLocation"]
            imageObj.src = "./Uploads/Test.jpg"
            imageObj.onload = () => {
                ctx.drawImage(imageObj, 0, 0)
            }                
        }
    </script>

在 C# 中:

ScriptManager.RegisterStartupScript(this, GetType(), "LoadImagetoCanvas", "LoadImagetoCanvas()", true);

我找到了解决方案,我的问题是

首先,我必须通过添加<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.js"></script>来引用 jQuery

第二个我的项目配置为使用 HTTPS,我必须将其设置为正常 HTTP

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM