Skip to content

Instantly share code, notes, and snippets.

@mortenbock
Created October 10, 2013 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mortenbock/6925184 to your computer and use it in GitHub Desktop.
Save mortenbock/6925184 to your computer and use it in GitHub Desktop.
Constraining images with imageprocessor
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using ImageProcessor;
using ImageProcessor.Helpers.Extensions;
using ImageProcessor.Processors;
using ImageProcessor.Web.Config;
namespace Demo.ImageProcessors
{
public class Constrain : IGraphicsProcessor
{
private static readonly Regex QueryRegex = new Regex(@"constrain=\d+,\d+", RegexOptions.Compiled);
public Regex RegexPattern
{
get
{
return QueryRegex;
}
}
public dynamic DynamicParameter { get; set; }
public int SortOrder { get; private set; }
public Dictionary<string, string> Settings { get; set; }
public int MatchRegexIndex(string queryString)
{
int index = 0;
// Set the sort order to max to allow filtering.
this.SortOrder = int.MaxValue;
foreach (Match match in this.RegexPattern.Matches(queryString))
{
if (match.Success)
{
if (index == 0)
{
// Set the index on the first instance only.
this.SortOrder = match.Index;
int[] constraints = match.Value.ToPositiveIntegerArray();
int x = constraints[0];
int y = constraints[1];
this.DynamicParameter = new Size(x,y);
}
index += 1;
}
}
return this.SortOrder;
}
public Image ProcessImage(ImageFactory factory)
{
double constrainedWidth = DynamicParameter.Width;
double constrainedHeight = DynamicParameter.Height;
var original = factory.Image;
double width = original.Width;
double height = original.Height;
if (width > constrainedWidth || height > constrainedHeight)
{
double constraintRatio = constrainedHeight/constrainedWidth;
double originalRatio = height/width;
Size newSize = originalRatio < constraintRatio
? new Size((int) constrainedWidth, 0)
: new Size(0, (int) constrainedHeight);
var resizer = ImageProcessorConfig.Instance.GraphicsProcessors.FirstOrDefault(g => g is Resize) as Resize;
if (resizer != null)
{
resizer.DynamicParameter = newSize;
Image processed = resizer.ProcessImage(factory);
return processed;
}
}
return factory.Image;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment