Search code examples
c#asp.netsitecoreimage-resizingsitecore-media-library

How do you apply allow-stretch to all sitecore media img tags?


How do I make it so that the "allow-stretch" property is applied to all of the tags that sitecore creates when inserting media from the media library?

I understand that you can set the allow-stretch property using the individual <sc:image> tags, but I want this setting to be applied globally so that whenever a user inserts media from the media library onto the page, the generated tag already has the "as=1" property applied to it by default.

Currently, whenever a user inserts media from the media library in my web application, the image tag created by sitecore looks something like this:

<img alt="" height="500" width="709" src="~/media/EAF03CA5568245B59FDDCC4B8FBD83E4.ashx?h=500&amp;w=709" />`

but I want it to look something like this:

<img alt="" height="500" width="709" src="~/media/EAF03CA5568245B59FDDCC4B8FBD83E4.ashx?h=500&amp;w=709&as=1" />

Notice that the second img tag that i provided has as=1 at the end.

Does anyone know how to make this happen?

I'm using Sitecore 6.5


Solution

  • You can create your own implementation of MediaProvider and set AllowStretch to always true. Inherit from Sitecore.Resources.Media.MediaProvider and override the GetMediaUrl() method:

    namespace MyCustom.Media
    {
      public class MediaProvider : Sitecore.Resources.Media.MediaProvider
      {
        public override string GetMediaUrl(MediaItem item)
        {
          Assert.ArgumentNotNull((object) item, "item");
          return this.GetMediaUrl(item, MediaUrlOptions.Empty);
        }
    
        public override string GetMediaUrl(MediaItem item, MediaUrlOptions options)
        {
          options.AllowStretch = true;
          return base.GetMediaUrl(item, options);
        }
    }
    

    And then in config patch the media provider to your custom implementation:

    <mediaProvider type="MyCustom.Media.MediaProvider, MyCustom.Kernel"/>
    

    EDIT: As Maras has suggested, try overriding the overloaded GetMediaUrl(MediaItem item, MediaUrlOptions options) method too.