简体   繁体   中英

ASP.NET core image to Canvas

I need to create a template of an image in which the user define and mark/highlight/ some regions. the goal is that next time when the user upload a similar image the program recognize it and auto highlight the areas which were defined in the template.

it has to be done as a Web Application, so I'm using ASP.net core

I thought to upload an image save it into a canvas, and then draw by mouse rectangle on the areas, and save somehow each time the mouse pointer/rectangle coordinate in the canvas and the size.

The file upload and then displaying the image (not in the Canvas) is working perfectly.

But I have no Idea why the image is not loaded into the 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>

and the c# code:

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>

and in C#:

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

I found the solution, my problem is

1st I had to reference the jQuery by adding <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

2nd My Project was configured to use HTTPS,and I had to set it back for normal HTTP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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