public static void Enable(IApplicationBuilder app, IHostingEnvironment env) { app.Use((context, task) => { try { var originalUrl = context.Request.Path; string newfilepath; string sourcefile = env.WebRootPath + originalUrl; ICompressor compressor; var match = System.Text.RegularExpressions.Regex.Match(originalUrl, @"^(.+)\.(?<ext>png|jpg|jpeg|gif)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (match != null && match.Length > 0) { //判断请求头是否包括image/webp if (context.Request.Headers["Accept"].ToString().ToLower().Contains("image/webp")) { #region webp var result = $"{originalUrl}.webp"; newfilepath = env.WebRootPath + result; if (File.Exists(sourcefile) == false) { return(task()); } context.Response.ContentType = "image/webp"; compressor = compressors[0]; #endregion } else { #region 正常的图片压缩 var ext = match.Groups["ext"].Value.ToLower(); var result = $"{originalUrl}.c"; newfilepath = env.WebRootPath + result; if (File.Exists(sourcefile) == false) { return(task()); } if (ext == "jpg") { ext = "jpeg"; } else if (ext == "gif") { return(task()); } context.Response.ContentType = $"image/{ext}"; compressor = compressors[1]; #endregion } var srcfileinfo = new System.IO.FileInfo(sourcefile); if (File.Exists(newfilepath)) { var fileinfo = new System.IO.FileInfo(newfilepath); if (fileinfo.LastWriteTime == srcfileinfo.LastWriteTime && fileinfo.Length > 0) { return(FileSender.SendFile(context, fileinfo, newfilepath)); } } compressor.Compress(app.ApplicationServices, sourcefile, newfilepath); System.IO.File.SetLastWriteTime(newfilepath, srcfileinfo.LastWriteTime); if (true) { var fileinfo = new System.IO.FileInfo(newfilepath); return(FileSender.SendFile(context, fileinfo, newfilepath)); } } } catch (Exception ex) { var loggerFactory = (ILoggerFactory)app.ApplicationServices.GetService(typeof(ILoggerFactory)); var logger = loggerFactory.CreateLogger("ImageToWebp"); logger.LogError(ex, ""); } return(task()); }); }
public static void Enable(IApplicationBuilder app) { app.Use((context, task) => { try { var configuration = app.ApplicationServices.GetService <IConfiguration>(); var originalUrl = context.Request.Path; var match = System.Text.RegularExpressions.Regex.Match(originalUrl, @"^(.+)\.(?<ext>png|jpg|jpeg|bmp)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (match != null && match.Length > 0) { string sourcefile = configuration["wwwroot"] + originalUrl; if (File.Exists(sourcefile) == false) { return(task()); } var nodejsPath = "./squoosh"; if (Directory.Exists(nodejsPath) == false) { return(context.Response.WriteAsync("miss squoosh folder")); } string codedfile; string type; if (context.Request.Headers["Accept"].ToString().ToLower().Contains("image/webp")) { context.Response.ContentType = "image/webp"; codedfile = $"{configuration["wwwroot"]}/__webpcache__{originalUrl}.webp"; type = "webp"; } else { codedfile = $"{configuration["wwwroot"]}/__webpcache__{originalUrl}.code"; type = Path.GetExtension(originalUrl).Substring(1).ToLower(); switch (type) { case "png": context.Response.ContentType = "image/png"; break; default: context.Response.ContentType = "image/jpeg"; break; } } var lastWriteTime = new FileInfo(sourcefile).LastWriteTime; if (File.Exists(codedfile) == false || new FileInfo(codedfile).LastWriteTime != lastWriteTime) { var threadid = RunningDict.GetOrAdd(codedfile, (k) => { return(Thread.CurrentThread.ManagedThreadId); }); if (threadid == Thread.CurrentThread.ManagedThreadId) { try { var dir = Path.GetDirectoryName(codedfile); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } var info = new ProcessStartInfo(); info.FileName = configuration["nodePath"]; info.Arguments = $"\"{AppDomain.CurrentDomain.BaseDirectory}squoosh/index.js\" \"{sourcefile}\" {type} \"{codedfile}\""; info.RedirectStandardError = true; info.RedirectStandardOutput = true; var process = System.Diagnostics.Process.Start(info); process.WaitForExit(); var ret = process.StandardOutput.ReadToEnd(); if (ret.StartsWith("ok")) { new FileInfo(codedfile).LastWriteTime = lastWriteTime; return(FileSender.SendFile(context, codedfile, lastWriteTime)); } else { context.Response.ContentType = "text/html"; return(context.Response.WriteAsync(ret)); } } catch (Exception) { throw; } finally { RunningDict.Remove(codedfile, out int o); } } else { return(task()); } } else { return(FileSender.SendFile(context, codedfile, lastWriteTime)); } } } catch (Exception ex) { context.Response.ContentType = "text/html"; return(context.Response.WriteAsync(ex.ToString())); } return(task()); }); }