maintaining image aspect ratio in datalist

M

mharness

Hello All,

Does anyone know how to dynamically change the width and height properties
of an image in a datalist in order to maintain the original aspect ratio?

I've managed to do this with a single image (see below) but don't have a
clue how to apply the same approach in a datalist, perhaps with a custom
databinding expression (or what?).

I would also prefer not displaying the image if it's blank so being able to
set visible false when the file does not exist would be useful too.

Thanks for any suggestions.

Mike

code for adjusting size and maintaining aspect ratio mostly courtesy of
Scott Mitchell at http://aspnet.4guysfromrolla.com/articles/011503-1.2.aspx
(thanks Scott!)

If File.Exists(strImagePath) Then

Dim myImage As System.Drawing.Image =
System.Drawing.Image.FromFile(strImagePath)

Dim imgHeight As Integer = myImage.Height

Dim imgWidth As Integer = myImage.Width

Dim intMaxWidth As Integer = 200

Dim intMaxHeight As Integer = 200

Dim ImageScaleFactor As Double = PSDB.ImageScaleFactor(myImage.Height,
myImage.Width, intMaxHeight , intMaxWidth )

Me.imgThumbnail.Height = System.Web.UI.WebControls.Unit.Pixel(myImage.Height
* ImageScaleFactor)

Me.imgThumbnail.Width = System.Web.UI.WebControls.Unit.Pixel(myImage.Width *
ImageScaleFactor)

Me.imgThumbnail.ImageUrl = strImagePath

Else 'file does not exist so hide the image box

Me.imgThumbnail.Visible = False

End If



Public Shared Function ImageScaleFactor(ByVal ImgHeight As Integer, ByVal
ImgWidth As Integer, ByVal MaxHeight As Integer, ByVal MaxWidth As Integer)
As Double

If ImgWidth > MaxWidth Or ImgHeight > MaxHeight Then

'Determine which dimension is off by more

Dim DeltaWidth As Integer = ImgWidth - MaxWidth

Dim DeltaHeight As Integer = ImgHeight - MaxHeight

Dim ScaleFactor As Double

If deltaHeight > deltaWidth Then

'Scale by the height

scaleFactor = MaxHeight / ImgHeight

Else

'Scale by the Width

scaleFactor = MaxWidth / ImgWidth

End If

ImageScaleFactor = ScaleFactor

End If

End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,588
Members
45,095
Latest member
EmiliaAlfo

Latest Threads

Top