Technorati Tags:
xml,
xslt,
images Let's say you have a bunch of different sized images that you want to constrain to some maximum dimension. You don't want to enlarge images smaller than you constraining dimension. If your limit was 150px, you might try the following:
<img>
<xsl:attribute name="src">
<xsl:value-of select="media/thumbnail/url" />
</xsl:attribute>
<xsl:if test="media/thumbnail/width > 150 or media/thumbnail/height > 150 ">
<xsl:attribute name="style">
width: 150px; height: 150px;
</xsl:attribute>
</xsl:if>
</img>
The problem with manually specifying the width and height in the style is that if the original image is not square (and most aren’t) the image will be distorted in one dimension. In order to prevent this distortion, you will need to size both dimensions by the same coefficient.
<img>
<xsl:attribute name="src">
<xsl:value-of select="media/thumbnail/url" />
</xsl:attribute>
<xsl:choose>
<xsl:when test="media/thumbnail/width > 150 and media/thumbnail/width >= media/thumbnail/height">
<xsl:attribute name="width">
<xsl:value-of select="(150 div media/thumbnail/width) * media/thumbnail/width" />px
</xsl:attribute>
<xsl:attribute name="height">
<xsl:value-of select="(150 div media/thumbnail/width) * media/thumbnail/height" />px
</xsl:attribute>
</xsl:when>
<xsl:when test="media/thumbnail/height > 150 and media/thumbnail/width < media/thumbnail/height">
<xsl:attribute name="width">
<xsl:value-of select="(150 div media/thumbnail/height) * media/thumbnail/width" />
</xsl:attribute>
<xsl:attribute name="height">
<xsl:value-of select="(150 div media/thumbnail/height) * media/thumbnail/height" />
</xsl:attribute>
</xsl:when>
</xsl:choose>
</img>
In this version, we use an xsl:choose to determine if the height or width is the larger dimension. If the larger dimension is greater than our maximum (again, 150px in this example), then we calculate the percentage that 150px is of that dimension; this is our coefficient. We then multiply both dimension by the coefficient to get the final size: the largest dimension will be 150px, and the smallest will be size proportionally to 150px or less.
For those so inclined, here’s the sorta math:
let m be the desired maximum dimension
let w and h be the width and height of the image respectively
L = maximum(w, h)
k = m / L
w = w * k
h = h * k
Note that in the example above, we could have simplified it by just applying the percentages directly to the image dimensions instead of taking the extra step of multiplying it by the original dimension. I just liked being able to see that it was exactly 150px in the output.