Skip to content

Instantly share code, notes, and snippets.

@skttl
Last active August 20, 2020 07:36
Show Gist options
  • Save skttl/de2de24d67b91e8a259eb08f4304b960 to your computer and use it in GitHub Desktop.
Save skttl/de2de24d67b91e8a259eb08f4304b960 to your computer and use it in GitHub Desktop.
Resize all media in Umbraco 7
using ImageProcessor;
using ImageProcessor.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Web.WebApi;
namespace skttl
{
public class ResizerController : UmbracoApiController
{
private int MaxWidth = 2400;
private int MaxHeight = 0;
[HttpGet]
public string ResizeMedia()
{
var sb = new StringBuilder();
var mediaItems = ApplicationContext.Current.Services.MediaService.GetRootMedia();
foreach (var item in mediaItems)
{
ResizeWithChildren(item, sb);
}
return sb.ToString();
}
private void ResizeWithChildren(IMedia item, StringBuilder sb)
{
Resize(item);
if (item.IsPropertyDirty(Constants.Conventions.Media.Width))
{
Services.MediaService.Save(item, item.CreatorId, false);
sb.AppendLine("Resized " + item.Name + " (" + item.Path + ")");
}
else
{
sb.AppendLine("Skipped " + item.Name + " (" + item.Path + ")");
}
var children = item.Children().ToList();
foreach (var child in children)
{
ResizeWithChildren(child, sb);
}
}
private void Resize(IContentBase node)
{
var imageCroppers = node.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.ImageCropperAlias);
var fileUploads = node.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias);
if (!imageCroppers.Any() && !fileUploads.Any()) return;
MediaMeta meta = null;
foreach (var crop in imageCroppers)
{
var imagePath = crop.Value;
if (imagePath == null) continue;
var json = Newtonsoft.Json.Linq.JObject.Parse(imagePath.ToString());
if (json.GetValue("src") != null)
{
var path = json.GetValue("src").ToString();
// Resize the image, and update meta object if necessary
MediaMeta result = null;
if (Resize(path, out result) && crop.Alias == Constants.Conventions.Media.File) meta = result;
}
}
foreach (var file in fileUploads)
{
if (file.Value != null)
{
var path = file.Value.ToString();
// Resize the image, and update meta object if necessary
MediaMeta result = null;
if (Resize(path, out result) && file.Alias == Constants.Conventions.Media.File) meta = result;
}
}
if (meta != null)
{
// Set the correct meta values for the image.
node.SetValue(Constants.Conventions.Media.Width, meta.Width);
node.SetValue(Constants.Conventions.Media.Height, meta.Height);
node.SetValue(Constants.Conventions.Media.Bytes, meta.Bytes);
}
}
/// <summary>
/// Resizes the image at the specified path, using the specified resize settings.
/// </summary>
/// <param name="path"></param>
/// <param name="settings"></param>
/// <param name="meta"></param>
/// <returns></returns>
private bool Resize(string path, out MediaMeta meta)
{
meta = null;
if (path.IsNullOrWhiteSpace()) return false;
string extension = Path.GetExtension(path).Substring(1);
var supportedExts = UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.ToList();
if (supportedExts.InvariantContains(extension) && (MaxWidth > 0 || MaxHeight > 0))
{
using (var imageFactory = new ImageFactory(true))
{
var layer = new ResizeLayer(new Size(MaxWidth, MaxHeight), ResizeMode.Max)
{
Upscale = false
};
var mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
using (var imageFileStream = mediaFileSystem.OpenFile(path))
{
imageFactory.Load(imageFileStream).Resize(layer);
}
var resizedImage = imageFactory.Image;
meta = new MediaMeta(resizedImage.Width, resizedImage.Height);
using (var fileStream = new MemoryStream())
{
imageFactory.Save(fileStream);
fileStream.Position = 0;
mediaFileSystem.AddFile(path, fileStream, true);
meta.Bytes = fileStream.Length;
}
}
return true;
}
return false;
}
}
public class MediaMeta
{
public MediaMeta()
{
}
public MediaMeta(int width, int height)
{
Width = width;
Height = height;
}
public int Width { get; set; }
public int Height { get; set; }
public long Bytes { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment