Vote Charlie!

Constraining Movable Type image by width and height

Posted at age 23.
Created . Edited .

In Movable Type templates, you can use the AssetThumbnailURL tag to generate a thumbnail of an image asset in the system.

    <$mt:AssetThumbnailURL width="100" square="1"$>

The tag has some limitations, though, and the implementation is confusing when using both the width and height parameters.

The documentation states “When both of height and width are specified, the longer side of the original image will be processed, and the lesser side will be scaled proportionally.”

This unfortunately does not mean we can specify both parameters and expect the resulting image to not exceed either constraint. But we can use some template logic to take care of this for us.

You might want to save this code within a template module to make it easier to use, but here is the basic idea. Set the desired maximum height and width as the variables “x2” and “y2” on LL. 2–3:

<mt:SetVarTemplate name="thumb_attribs">
  <$mt:Var name="x2" value="325"$>
  <$mt:Var name="y2" value="265"$>
  <$mt:AssetProperty property="image_width" setvar="x1"$>
  <$mt:AssetProperty property="image_height" setvar="y1"$>
  <$mt:Var name="x3" value="$x1"$>
  <$mt:Var name="y3" value="$y1"$>
  <$mt:AssetThumbnailURL setvar="url"$>
  <$mt:Var name="OR" value="0"$>
  <mt:If name="x1" ge="$x2"><$mt:Var name="OR" value="1"$></mt:If>
  <mt:If name="y1" ge="$y2"><$mt:Var name="OR" value="1"$></mt:If>
  <mt:If name="OR">
    <$mt:Var name="x2" op="/" value="$x1" setvar="rx"$>
    <$mt:Var name="y2" op="/" value="$y1" setvar="ry"$>
    <mt:If name="rx" gt="$ry">
      <$mt:Var name="ry" setvar="r"$>
      <$mt:Var name="rx" setvar="r"$>
    <$mt:Var name="x1" op="*" value="$r" sprintf="%.0f" setvar="x3"$>
    <$mt:Var name="y1" op="*" value="$r" sprintf="%.0f" setvar="y3"$>
    <$mt:AssetThumbnailURL height="$y3" setvar="url"$>
  src="<$mt:Var name="url"$>" height="<$mt:Var name="y3"$>" width="<$mt:Var name="x3"$>"

Then you could execute the code like this:

<mt:EntryLinkedAssets field="image">
  <img <$mt:Var name="thumb_attribs"$> alt="" />