Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Helpers;
using ImageProcessor.Web.Services;
using YourSite.Web.Models.Media;
namespace YourSite
{
/// <summary>
/// Image service for retrieving images from EPiServer
/// </summary>
public class EPiServerImageService : IImageService
{
/// <summary>
/// Gets or sets the prefix for the given implementation.
/// <remarks>
/// This value is used as a prefix for any image requests that should use this service.
/// </remarks>
/// </summary>
public string Prefix { get; set; } = string.Empty;
/// <summary>
/// Gets a value indicating whether the image service requests files from
/// the locally based file system.
/// </summary>
public bool IsFileLocalService => true;
/// <summary>
/// Gets or sets any additional settings required by the service.
/// </summary>
public Dictionary<string, string> Settings { get; set; }
/// <summary>
/// Gets or sets the white list of <see cref="System.Uri"/>.
/// </summary>
public Uri[] WhiteList { get; set; }
public Injected<IContentRouteHelper> ContentRouteHelper { get; set; }
/// <summary>
/// Gets a value indicating whether the current request passes sanitizing rules.
/// </summary>
/// <param name="path">
/// The image path.
/// </param>
/// <returns>
/// <c>True</c> if the request is valid; otherwise, <c>False</c>.
/// </returns>
public bool IsValidRequest(string path)
{
return ImageHelpers.IsValidImageExtension(path);
}
/// <summary>
/// Gets the image using the given identifier.
/// </summary>
/// <param name="id">
/// The value identifying the image to fetch.
/// </param>
/// <returns>
/// The <see cref="System.Byte"/> array containing the image data.
/// </returns>
public async Task<byte[]> GetImage(object id)
{
var image = ContentRouteHelper.Service.Content as ImageFile;
if (image == null)
{
var virtualPath = id.ToString().Replace(HostingEnvironment.ApplicationPhysicalPath, string.Empty).Replace(@"\", "/");
throw new HttpException((int)HttpStatusCode.NotFound, "No image exists at " + virtualPath);
}
using (var ms = new MemoryStream())
{
using (var blob = image.BinaryData.OpenRead())
{
await blob.CopyToAsync(ms);
return ms.ToArray();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment