Last active
December 24, 2015 03:49
-
-
Save perosb/6740184 to your computer and use it in GitHub Desktop.
ImageResizer AspectRatioPlugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the suggestion, updated gist based on your feedback.