Resize media library images to width of the mobile device
You may find this code useful if you do not want mobile users requesting images from the media library at a resolution which is larger than their device width, to save a bit of bandwidth.
public class MobileMediaRequestHandler : MediaRequestHandler
{
protected override bool DoProcessRequest(HttpContext context)
{
if (Sitecore.Context.Device.Name.Equals("Mobile", StringComparison.InvariantCultureIgnoreCase))
{
Assert.ArgumentNotNull(context, "context");
MediaRequest mediaRequest = MediaManager.ParseMediaRequest(context.Request);
if (mediaRequest == null)
{
return false;
}
Sitecore.Resources.Media.Media media = MediaManager.GetMedia(mediaRequest.MediaUri);
if (media == null)
{
using (SecurityDisabler securityDisabler = new SecurityDisabler())
{
media = MediaManager.GetMedia(mediaRequest.MediaUri);
}
string text;
if (media == null)
{
text = Settings.ItemNotFoundUrl;
}
else
{
Assert.IsNotNull(Context.Site, "site");
text = ((Context.Site.LoginPage != string.Empty) ? Context.Site.LoginPage : Settings.NoAccessUrl);
}
if (Settings.RequestErrors.UseServerSideRedirect)
{
HttpContext.Current.Server.Transfer(text);
}
else
{
HttpContext.Current.Response.Redirect(text);
}
return true;
}
int screenHeight = HttpContext.Current.Request.Browser.ScreenPixelsHeight;
int screenWidth = HttpContext.Current.Request.Browser.ScreenPixelsWidth;
int imageWidth = TypeGuard.Cast<int>(media.MediaData.MediaItem.InnerItem["width"], 0);
if (imageWidth != 0 && (imageWidth > screenWidth))
{
mediaRequest.Options.MaxWidth = screenWidth;
mediaRequest.Options.UseMediaCache = true;
}
return this.DoProcessRequest(context, mediaRequest, media);
}
return base.DoProcessRequest(context);
}