using System; using System.IO; using System.Linq; using System.Threading; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Web.Memory; using SixLabors.Primitives; namespace test_imagesharp { public class Startup { private readonly IHostingEnvironment _hostingEnvironment; public Startup(IHostingEnvironment env) { _hostingEnvironment = env; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.Run(async context => { const int thumbsPerColumn = 10; const int thumbWidth = 110; const int thumbHeight = 62; const int width = thumbWidth * thumbsPerColumn; var fileProvider = _hostingEnvironment.WebRootFileProvider; var files = fileProvider.GetDirectoryContents("0793a16e-903b-4ba4-8ffa-3bf5576ab568"); var height = (int) Math.Ceiling(files.Count() / (decimal) thumbsPerColumn) * thumbHeight; byte[] outBuffer = null; try { using (var strip = new Image(width, height)) { var nIndex = 0; foreach (var file in files) { byte[] buffer; using (var stream = file.CreateReadStream()) { buffer = BufferDataPool.Rent((int) stream.Length); await stream.ReadAsync(buffer, 0, (int) stream.Length); } using (var thumb = Image.Load(buffer)) { thumb.Mutate(x => x.Resize(thumbWidth, thumbHeight)); strip.Mutate(x => x.DrawImage( thumb, 1, new Size(thumbWidth, thumbHeight), new Point( nIndex % thumbsPerColumn * thumbWidth, (int) Math.Floor(nIndex / (decimal) thumbsPerColumn) * thumbHeight))); nIndex++; } BufferDataPool.Return(buffer); } using (var outStream = new MemoryStream()) { strip.Save(outStream, new JpegEncoder { Quality = 75, IgnoreMetadata = true }); outStream.Seek(0, SeekOrigin.Begin); outBuffer = BufferDataPool.Rent((int) outStream.Length); await outStream.ReadAsync(outBuffer, 0, (int) outStream.Length); } context.Response.StatusCode = StatusCodes.Status200OK; context.Response.ContentType = "image/jpeg"; await context.Response.Body.WriteAsync(outBuffer, 0, outBuffer.Length, CancellationToken.None); } } finally { BufferDataPool.Return(outBuffer); } }); } } }