【问题标题】:ASP.NET core image to CanvasASP.NET 核心图像到 Canvas
【发布时间】:2020-04-13 17:25:29
【问题描述】:

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

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

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

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

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

@{
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");
        }
    }

我什至尝试添加一个 Javascript 函数并从 c# 部分调用它,但没有成功,因为即使调用了该函数,他似乎也找不到我的 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);

【问题讨论】:

    标签: javascript c# asp.net-core


    【解决方案1】:

    我找到了解决办法,我的问题是

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

    第二次我的项目被配置为使用 HTTPS,我不得不将其设置为正常的 HTTP

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2017-11-30
      • 2019-07-20
      • 1970-01-01
      • 2022-08-17
      • 2019-12-21
      • 1970-01-01
      • 2017-10-23
      相关资源
      最近更新 更多