Skip to content

Instantly share code, notes, and snippets.

@kipusoep
Created December 16, 2014 13:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kipusoep/9fa2dc1160d21afaabc4 to your computer and use it in GitHub Desktop.
Save kipusoep/9fa2dc1160d21afaabc4 to your computer and use it in GitHub Desktop.
ImageProcessor auto-resize
MediaFileSystem mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
IContentSection contentSection = UmbracoConfig.For.UmbracoSettings().Content;
IEnumerable<string> supportedTypes = contentSection.ImageFileTypes.ToList();
foreach (IMedia media in e.SavedEntities)
{
if (media.HasProperty("umbracoFile"))
{
// Make sure it's an image.
string path = media.GetValue<string>("umbracoFile");
if (!string.IsNullOrEmpty(path))
{
string extension = Path.GetExtension(path).Substring(1);
if (supportedTypes.InvariantContains(extension))
{
// Resize the image to 1920px wide, height is driven by the aspect ratio of the image.
string fullPath = mediaFileSystem.GetFullPath(path);
using (ImageFactory imageFactory = new ImageFactory(true))
{
int resizeDimension = 1920;
int.TryParse(ConfigurationManager.AppSettings["ic:ResizeDimension"], out resizeDimension);
int umbracoWidth = int.Parse(media.GetValue<string>("umbracoWidth"));
int umbracoHeight = int.Parse(media.GetValue<string>("umbracoHeight"));
ResizeLayer layer = new ResizeLayer(new Size(umbracoWidth > umbracoHeight ? resizeDimension : 0, umbracoHeight > umbracoWidth ? resizeDimension : 0), resizeMode: ResizeMode.Max)
{
Upscale = false
};
imageFactory.Load(fullPath).Resize(layer).Save(fullPath);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment