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
}
@MarcStoecker
Copy link

I like the general idea of having an aspect ratio plugin in ImageResizer! I would suggest to go with something like aspectw and aspecth to allow aspect keeping in both dimensions? So this would be more generic and not so tightly coupled to the requirements we have right now regarding slimmage/slimresponse and width/height.

Also we would need to take into account that params can be semicolon seperated (not only querystring) and there is w as well as width. But that's just details. Unchecked claim. Maybe Config.Pipeline already does that?

@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