Vertical and horizontal centring an image in a div
The problem: A client uploads images to the server which are auto-resized on-the-fly to fit inside 100px x 100px boxes. The resized images then need to be displayed vertically and horizontally centred in 120px x 120px divs like slides.
Horizontal centring in the slide is easy with CSS (text-align:center;) but vertical CSS centring is more problematic.
The solution: Using ServerObjects Image Size, it's possible to retrieve the height and width of each of the original uploaded images and then calculate the top margin necessary to vertically centre each resized image in it's slide.
The Function:
<%
Function topMargin(theImage)
Set imageObj = Server.CreateObject("ImgSize.Check")
imageObj.FileName = "server_path_to_image_folder\" & theImage
If (imageObj.Error = "") Then
If imageObj.Width >= imageObj.Height Then
intWidth = 100
Else
IntHeight = 100
End If
If imageObj.Width >= imageObj.Height Then
intHeight = imageObj.Height/(imageObj.Width/intWidth)
Else
intWidth = imageObj.Width/(imageObj.Height/intHeight)
End If
Else
IntHeight = 100
End If
intTopMargin = (120 - intHeight)/2
intTopMargin = FormatNumber(intTopMargin,0)
Set imageObj = Nothing
topMargin = intTopMargin
End Function
%>
Usage (using the file system object to obtain all the images from a folder):
<% For Each file In filecollection %>
<div class="slide" style="height:120px; width:120px; text-align:center;">
<img src="/resize-script.aspx?image=/image_folder/<%= file.name %>" style="margin-top:<%= topMargin(file.name) %>"px;" />
</div>
<% Next %>
Comments
Leave a comment