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 | |
} |
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
I like the general idea of having an aspect ratio plugin in ImageResizer! I would suggest to go with something like
aspectw
andaspecth
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 isUnchecked claim. Maybe Config.Pipeline already does that?w
as well aswidth
. But that's just details.