Maintaining image size and position on the page in database using ASP.NET MVC

Sheonarayan
Posted by in ASP.NET MVC category on for Advance level | Points: 250 | Views : 31894 red flag
Rating: 5 out of 5  
 4 vote(s)

In this article, we are going to look into how to maintain the image size and position of an image on the page in database so that next time the image renders on the page it renders exactly at the same place and same size where user had saved. ASP.NET MVC is used in the article however the same approach can be followed in any other technologies.

Introduction


In scenarios, where we need to provide end user an ability to resize and position image; jQuery UI comes very handy however the only limitation is all these happens client side and we need to write our own logic to save images size and position into the database so that next time when user comes he sees the size and position of images exactly he had saved. In this article, we are going to learn how to maintain the image size and position in the database and render those images back with saved size and position.

Objective


The objective of this article is to explain how to maintain image position and size into the database and render images back to the page at saved size and position.


Using the code


As the piece of code I am going to use here to explain has been taken from live website  - http://www.kidsfunda.com/Charts/Details/12/mountains-in-world designed by me so we are going to assume certain things that will be talk about later.

First lets see how the database (SQL Server is used in the article) structure should look like that will save other details apart from the image position and size.



In my case, there are few more columns apart from those that are being displayed above but as those are not related with this functionality we are going to learn so they are hidden. You may customize this table as per your requirement but following fields are mandatory

  1. AutoId (auto increment)
  2. ImageTitle (varchar)
  3. ImagePath (varchar)
  4. ImagePostion (varchar)
  5. ImageSize (varchar)
Please note that we are going to save the Image position separated by "x" that means that if the value of ImagePosition field for a particular image is 38x627 that means, the image should be rendered at 38 pixel from left and 627 pixel from top. 

Similarly, if the ImageSize value of a certain field is 150x198 that means that the image width is 150 pixel and its height is 198 pixel.

Now lets assume that we are going to get Images saved into the database in ViewBag.Images. So here is going to be our ASP.NET View page code to render those images.

<div id="divImages">
    @foreach (dynamic img in ViewBag.Images)
    {
        string width = string.Empty; string sizeWH = string.Empty;
        string height = string.Empty; 
        string left = string.Empty; string positionLT = string.Empty;
        string top = string.Empty;
        int initialImageLeftPosition = 0;
string[] size = img.ImageSize.Split('x'); if (size.Length > 1) { width = "width:" + size[0] + "px;"; height = "height:" + size[1] + "px"; ; sizeWH = size[0] + "x" + size[1]; } else { width = "width:50px;"; height = "height:50px;"; } string[] position = img.ImagePosition.Split('x'); if (position.Length > 1) { left = "left:" + position[0] + "px;"; top = "top:" + position[1] + "px;position:absolute;"; positionLT = position[0] + "x" + position[1]; } else { left = "left:" + initialImageLeftPosition +"px;"; initialImageLeftPosition = 60; } imagesCount++; var photoUrl = Resources.SiteConfiguration.ChartImagePath.Substring(1) + img.ImagePath; <div style="cursor:move;position:absolute;display:inline-block;text-align:center;@Html.Raw(left + top)" draggable="true" id="@imagesCount"> <img style="@Html.Raw(width + height)" id="@Html.Raw("img" + imagesCount)" src="@photoUrl" title="Hold the mouse and drag to reposition" /> <span class="chartImgTitle">@img.ImageTitle</span> <input type="hidden" name="@Html.Raw("cht" + imagesCount)" id="@Html.Raw("cht" + imagesCount)" value="@img.AutoId" /> <input type="hidden" name="@Html.Raw("pos" + imagesCount)" id="@Html.Raw("pos" + imagesCount)" value="@positionLT" /> <input type="hidden" name="@Html.Raw("siz" + imagesCount)" id="@Html.Raw("siz" + imagesCount)" value="@sizeWH" /> </div> } <input type="hidden" name="imagesCount" value="@imagesCount" /> <label id="lbl"></label> </div> <input type="submit" value="Save" name="smtBtn" id="smtBtnA" />

We are doing following in the above code snippet
  1. Looping through all images
  2. Declaring width, height, and position related variables
  3. Splitting ImageSize by "x" and saving width and height into respective variables. sizeWH is a variable whose value will be set as hidden field value that will ultimately be accessed from server side to save the current width and height of the image. If the size of the image has not been saved till now (just uploaded and rendering first time) then we are setting default width and height of the image.
  4. Similarly setting the image position from left and height.
  5. Incrementing the imagesCount variable value (of int type) that has been defined at the top of the page (not in the above code snippet).
  6. We are generating the photoUrl so that the image displays on the page.
  7. All are images that are going to be rendered are wrapped in the div element so we are setting the left and top css style from the variables value calculated above.
  8. Then the size of the image are being set in its style attribute of img element.
  9. To save the image position and size we are maintaining three hidden fields
    • first hidden field saves the Auto Id value of the image
    • second hidden field saves current position value of the image
    • third hidden field saves current size value of the image
  10. Writing the final images count into another hidden variables.


How to make image Resizeable and Draggable in ASP.NET MVC?


To make the image Resizeable and Draggable, I am using jQueryUI and below is the code that does all.

<script type="text/javascript">

    var currentMousePos = { x: 300, y: 400 };

    $("#divImages div").draggable(
    {
        drag: function () {
            var offset = $(this).offset();
            var xPos = parseInt(offset.left);
            var yPos = parseInt(offset.top);

            var id = $(this).attr('id');
            $('#pos' + id).val(xPos + "x" + yPos);
        }
    });


    $(document).mousemove(function (event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
        // $("#lbl").html(currentMousePos.x + " : " + currentMousePos.y);
    });


    $(function () {
        $("#divImages div img").resizable({
            stop: function (event, ui) {
                var id = $(this).parent().attr('id');
                $('#siz' + id).val($(this).width() + 'x' + $(this).height());
            }});
    });

</script>
Above code snippets does following
  1. Defines a currentMousePos object with x and y property.
  2. Makes all divs inside divImages (parent div - refer 1st code snippet) draggable (as all our images are wrapped inside div). When user actually drags the image, the drag event fires and it saves the div position into the respective hidden field of the image.
  3. When mouse moves, the current position of the mouse is set to the currentMousePos object's respective value.
  4. The last function of the script block makes the image resizeable. When the resize activity stops by the user, the stop event fires and saves the width and height of the image to respective image size hidden field.


Now when the submit button is clicked, following action method of the controller executes

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DesignChart(int id, string differentiator = "")
        {
            int imagesCount = 0;
            int.TryParse(Request.Form["imagesCount"], out imagesCount);

            // update images details
            for (int i = 1; i <= imagesCount; i++)
            {
                int imageId = int.Parse(Request.Form["cht" + i]);

                ImageModel model = db.ImageModels.Find(imageId);
                db.Entry(model).State = EntityState.Modified;

                model.ImagePosition = Request.Form["pos" + i];
                model.ImageSize = Request.Form["siz" + i];
            }
            
            db.SaveChanges();

            return RedirectToAction("DesignChart", new { id = id }); // Change name to suit you
        }

In the above code snippet, we are doing following

  1. Getting the images count from the hidden field
  2. Making a for loop of the imagesCount
  3. Getting the image id
  4. Finding the image from the Images collection and setting its State to Modified (Entity Framework is being used here. Also it is assumed that when these images are uploaded and saved into the database there will be some default value in the database for ImagePosition and ImageSize or these fields are empty but not null.
  5. Setting the ImagePostion and ImageSize properties of this particular Image model
  6. Calling SaveChanges method so that ImagePostion and ImageSize details the image will be saved into the database.
To see the functional version of this functionality, please visit Chart Paper section of KidsFunda.com.

Hope this article will be useful for DotNetFunda.com members and readers. Do share this to your friends and colleagues. 

Thanks for reading and let me know your feedback or comments if any.

Reference


http://jqueryui.com/


Recommendation
Read Creating a drawing board using Canvas in HTML 5 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Rinkeshmodi on: 1/12/2016 | Points: 25
Is there any download link for this code ..?
i want to see how it works and learn from it .

Login to post response

Comment using Facebook(Author doesn't get notification)