Quantcast
Channel: Pipeline – SitecoreJunkie.com
Viewing all articles
Browse latest Browse all 51

Specify the Maximum Width of Images Uploaded to the Sitecore Media Library

$
0
0

Last week someone started a thread in one of the SDN forums asking how one could go about making Sitecore resize images larger than a specific width down to that width.

Yesterday an astute SDN visitor recommended using a custom getMediaStream pipeline processor to set the maximum width for images — a property for this maximum width is exposed via the GetMediaStreamPipelineArgs parameters object passed through the getMediaStream pipeline.

I thought I would try out the suggestion, and came up with the following getMediaStream pipeline processor:

using Sitecore.Diagnostics;

using Sitecore.Resources.Media;

namespace Sitecore.Sandbox.Resources.Media
{
    public class MaxWidthProcessor
    {
        public int MaxWidth { get; set; }

        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (!ShouldSetMaxWidth(args))
            {
                return;
            }

            args.Options.MaxWidth = MaxWidth;
        }

        private bool ShouldSetMaxWidth(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            return MaxWidth > 0 && args.Options.MaxWidth < 1;
        }
    }
}

I then interlaced it into the getMediaStream pipeline before the ResizeProcessor processor — this is the processor where the magical resizing happens — using the following patch configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getMediaStream>
        <processor patch:before="processor[@type='Sitecore.Resources.Media.ResizeProcessor, Sitecore.Kernel']"
                   type="Sitecore.Sandbox.Resources.Media.MaxWidthProcessor, Sitecore.Sandbox">
          <MaxWidth>1024</MaxWidth>
        </processor>  
      </getMediaStream>
    </pipelines>
  </sitecore>
</configuration>

The maximum width for images is set to 1024 pixels — the width I am using in my test below.

Let’s see how we did.

I decided to use one of my favorite images that ships with Sitecore for testing:

lighthouse-small

As you can see its width is much larger than 1024 pixels:

lighthouse-properties

After uploading the lighthouse image into the media library, its width was set to the maximum specified, and its height was scaled down proportionally:

resized-during-upload

If you have any thoughts on this, or other ideas on resizing images uploaded to the media library, please drop a comment.



Viewing all articles
Browse latest Browse all 51

Trending Articles