Skip to content

Instantly share code, notes, and snippets.

@rasmuseeg
Last active October 19, 2019 15:42
Show Gist options
  • Save rasmuseeg/65c990b631a8863f8558 to your computer and use it in GitHub Desktop.
Save rasmuseeg/65c990b631a8863f8558 to your computer and use it in GitHub Desktop.
Gets the most dominant color from a image and saves it to a property with the name of "umbacoDominantColor"
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using ImageProcessor;
using ImageProcessor.Imaging;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Core.Logging;
namespace Umbraco.Web
{
public class ApplicationEvents: IApplicationEventHandler
{
#region Events
public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
throw new NotImplementedException();
}
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
}
public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
// Tap into the Saving event
MediaService.Saving += MediaService_Saving;
}
#endregion
void MediaService_Saving (IMediaService sender, Core.Events.SaveEventArgs<IMedia> e)
{
IContentSection contentSection = UmbracoConfig.For.UmbracoSettings().Content;
IEnumerable<string> supportedTypes = contentSection.ImageFileTypes.ToList();
foreach( IMedia media in e.SavedEntities )
{
if( media.HasProperty( "umbracoFile" ) && media.HasProperty( "umbracoDominantColor" ) )
{
string extention = media.GetValue<string>( "umbracoExtension" );
if( supportedTypes.InvariantContains( extention ) )
{
Color dominantColor = GetDominantColorFromMedia( media );
string hex = ConvertColorToHex( dominantColor );
media.SetValue( "umbracoDominantColor", hex );
}
}
}
}
private Color GetDominantColorFromMedia (IMedia media)
{
string path = GetImagePathFromMedia( media );
Color dominantColor = GetDominantColorFromImagePath( path );
return dominantColor;
}
private Color GetDominantColorFromImagePath (string path)
{
try
{
// Resize the image to 1px wide
using( ImageFactory imageFactory = new ImageFactory( false ) )
{
var size = new System.Drawing.Size() { Width = 1 };
var resizeLayer = new ResizeLayer( size : size, resizeMode : ResizeMode.Max );
var image = imageFactory.Load( path ).Resize( resizeLayer ).Image;
// Now get the only color left, dominant color.
using( Bitmap bmp = new Bitmap( image ) )
{
return bmp.GetPixel( 0, 0 );
}
} // END of ImageFactory
}
catch( Exception )
{
throw new NotImplementedException( "Unable to get dominant color from image" ); ;
}
}
private string ConvertColorToHex (System.Drawing.Color c)
{
return "#" + c.R.ToString( "X2" ) + c.G.ToString( "X2" ) + c.B.ToString( "X2" );
}
private string GetImagePathFromMedia (IMedia media)
{
string value = media.GetValue<string>("umbracoFile");
string src = GetSrcFromMedia(value);
if (!string.IsNullOrEmpty(src))
{
return HttpContext.Current.Server.MapPath(src);
}
return string.Empty;
}
private string GetSrcFromMedia(string value)
{
string src;
try
{
var imageCropDateSet = JsonConvert.DeserializeObject<Umbraco.Web.Models.ImageCropDataSet>(value);
src = imageCropDateSet.Src;
}
catch (Exception ex)
{
LogHelper.Error(this.GetType(), "Failed to parse umbracoFile as ImageCropper", ex);
src = value;
}
return src;
}
}
}
using ImageProcessor;
using ImageProcessor.Imaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Implement;
namespace Umbraco.Web
{
public class DominantColorExtractorComposer : IUserComposer
{
#region Events
public void Compose(Composition composition)
{
MediaService.Saving += MediaService_Saving;
}
#endregion
void MediaService_Saving(IMediaService sender, Core.Events.SaveEventArgs<IMedia> e)
{
IContentSection contentSection = Current.Configs.Settings().Content;
IEnumerable<string> supportedTypes = contentSection.ImageFileTypes.ToList();
foreach (IMedia media in e.SavedEntities)
{
if (media.HasProperty("umbracoFile") && media.HasProperty("umbracoDominantColor"))
{
string extention = media.GetValue<string>("umbracoExtension");
if (supportedTypes.InvariantContains(extention))
{
Color dominantColor = GetDominantColorFromMedia(media);
string hex = ConvertColorToHex(dominantColor);
media.SetValue("umbracoDominantColor", hex);
}
}
}
}
private Color GetDominantColorFromMedia(IMedia media)
{
string path = GetImagePathFromMedia(media);
Color dominantColor = GetDominantColorFromImagePath(path);
return dominantColor;
}
private Color GetDominantColorFromImagePath(string path)
{
try
{
// Resize the image to 1px wide
using (ImageFactory imageFactory = new ImageFactory(false))
{
var size = new System.Drawing.Size() { Width = 3, height = 3 };
var resizeLayer = new ResizeLayer(size: size, resizeMode: ResizeMode.Max);
var image = imageFactory.Load(path).Resize(resizeLayer).Image;
// Now get the only color left, dominant color.
using (Bitmap bmp = new Bitmap(image))
{
return bmp.GetPixel(1, 1);
}
} // END of ImageFactory
}
catch (Exception)
{
throw new NotImplementedException("Unable to get dominant color from image"); ;
}
}
private string ConvertColorToHex(System.Drawing.Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
private string GetImagePathFromMedia(IMedia media)
{
string value = media.GetValue<string>("umbracoFile");
string src = GetSrcFromMedia(value);
if (!string.IsNullOrEmpty(src))
{
return HttpContext.Current.Server.MapPath(src);
}
return string.Empty;
}
private string GetSrcFromMedia(string value)
{
string src;
try
{
var imageCropDateSet = JsonConvert.DeserializeObject<ImageCropperValue>(value);
src = imageCropDateSet.Src;
}
catch (Exception ex)
{
Current.Logger.Error(this.GetType(), "Failed to parse umbracoFile as ImageCropper", ex);
src = value;
}
return src;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment