Skip to content

Instantly share code, notes, and snippets.

@perosb
Last active December 24, 2015 03:49
Show Gist options
  • Save perosb/6740184 to your computer and use it in GitHub Desktop.
Save perosb/6740184 to your computer and use it in GitHub Desktop.
ImageResizer AspectRatioPlugin
/// <summary>
/// A ImageResizerPlugin that uses a special ascpetratio command to calculate the height.
/// </summary>
/// <author>Per Osbäck</author>
public class AspectRatioPlugin : IPlugin
{
public AspectRatioPlugin()
{
}
#region IPlugin Members
public IPlugin Install(ImageResizer.Configuration.Config c)
{
c.Plugins.add_plugin(this);
c.Pipeline.Rewrite += new UrlRewritingEventHandler(Pipeline_RewriteDefaults);
return this;
}
void Pipeline_RewriteDefaults(IHttpModule sender, HttpContext context, IUrlEventArgs e)
{
var aspectW = e.QueryString["aspectw"];
var aspectH = e.QueryString["aspecth"];
if (aspectH == null && aspectW == null)
{
return;
}
double aspectratio = 0;
if (double.TryParse(aspectW ?? aspectH, out aspectratio) && aspectratio > 0)
{
int parameterValue = 0;
if (aspectW != null && int.TryParse(e.QueryString["width"], out parameterValue))
{
UpdateParameters("height", (int)(parameterValue / aspectratio), e);
}
else if (aspectH != null && int.TryParse(e.QueryString["height"], out parameterValue))
{
UpdateParameters("width", (int)(parameterValue * aspectratio), e);
}
}
}
private void UpdateParameters(string targetKey, int targetValue, IUrlEventArgs e)
{
e.QueryString.Remove(targetKey);
e.QueryString.Add(targetKey, targetValue.ToString());
}
public bool Uninstall(ImageResizer.Configuration.Config c)
{
c.Plugins.remove_plugin(this);
c.Pipeline.RewriteDefaults -= new UrlRewritingEventHandler(Pipeline_RewriteDefaults);
return true;
}
#endregion
}
@perosb
Copy link
Author

perosb commented Sep 28, 2013

Thanks for the suggestion, updated gist based on your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment