Click here to Skip to main content
14,826,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, 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.

What I have tried:

my Index.cshtml view:
ASP.NET
<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# Part
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;
                Image image;                

                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:

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


C#
ScriptManager.RegisterStartupScript(this, GetType(), "LoadImagetoCanvas", "LoadImagetoCanvas()", true);
Posted
Updated 14-Apr-20 1:14am

1 solution

I found the solution, my problem is
1st I had to reference the jQuery by adding
HTML
<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
   
Comments
Richard Deeming 14-Apr-20 8:45am
   
Bad idea. If you deploy your site without using HTTPS, it will be susceptible to interception and tampering.
Troy Hunt: Here's Why Your Static Website Needs HTTPS[^]

The Google CDN supports HTTPS. Reference the script using the HTTPS URL instead:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

You can then leave your site configured to HTTPS.
Nizar Belhiba 14-Apr-20 18:51pm
   
Thank you :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900