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
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
- AutoId (auto increment)
- ImageTitle (varchar)
- ImagePath (varchar)
- ImagePostion (varchar)
- 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
- Looping through all images
- Declaring width, height, and position related variables
- 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. - Similarly setting the image position from left and height.
- Incrementing the
imagesCount
variable value (of int type) that has been defined at the top of the page (not in the above code snippet). - We are generating the
photoUrl
so that the image displays on the page. - 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. - Then the size of the image are being set in its
style
attribute of img element. - 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
- Writing the final images count into another hidden variables.
How to make image Resizeable and Draggable in ASP.NET MVC?
<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
- Defines a
currentMousePos
object with x and y property. - 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. - When mouse moves, the current position of the mouse is set to the
currentMousePos
object's respective value. - 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
- Getting the images count from the hidden field
- Making a for loop of the imagesCount
- Getting the image id
- 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. - Setting the
ImagePostion
and ImageSize
properties of this particular Image model - 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/