55using Microsoft . AspNetCore . Http ;
66using Microsoft . IO ;
77using SixLabors . ImageSharp . Formats ;
8+ using SixLabors . ImageSharp . Formats . Jpeg ;
9+ using SixLabors . ImageSharp . Formats . Png ;
10+ using SixLabors . ImageSharp . Formats . Webp ;
811using SixLabors . ImageSharp . Web . Commands ;
912using SixLabors . ImageSharp . Web . Providers ;
1013
@@ -15,6 +18,8 @@ namespace SixLabors.ImageSharp.Web.Middleware;
1518/// </summary>
1619public class ImageSharpMiddlewareOptions
1720{
21+ private static readonly Configuration DefaultConfiguration = CreateDefaultConfiguration ( ) ;
22+
1823 private Func < ImageCommandContext , byte [ ] , string > onComputeHMAC = ( context , secret ) =>
1924 {
2025 string uri = CaseHandlingUriBuilder . BuildRelative (
@@ -35,7 +40,12 @@ public class ImageSharpMiddlewareOptions
3540 /// <summary>
3641 /// Gets or sets the base library configuration.
3742 /// </summary>
38- public Configuration Configuration { get ; set ; } = Configuration . Default ;
43+ public Configuration Configuration { get ; set ; } = DefaultConfiguration ;
44+
45+ /// <summary>
46+ /// Gets a value indicating whether the current configuration is the default configuration.
47+ /// </summary>
48+ internal bool HasDefaultConfiguration => ReferenceEquals ( this . Configuration , DefaultConfiguration ) ;
3949
4050 /// <summary>
4151 /// Gets or sets the recyclable memorystream manager used for managing pooled stream
@@ -176,4 +186,33 @@ public Func<HttpContext, Task> OnPrepareResponseAsync
176186 this . onPrepareResponseAsync = value ;
177187 }
178188 }
189+
190+ private static Configuration CreateDefaultConfiguration ( )
191+ {
192+ // Build a Configuration for the requests that replaces the default JPEG, PNG, and WebP encoders
193+ // with ones with compression options that are more suitable for web use.
194+ // We do not skip metadata as that can affect things like orientation.
195+ Configuration configuration = Configuration . Default . Clone ( ) ;
196+ configuration . ImageFormatsManager . SetEncoder ( JpegFormat . Instance , new JpegEncoder ( )
197+ {
198+ Quality = 75 ,
199+ Progressive = true ,
200+ Interleaved = true ,
201+ ColorType = JpegColorType . YCbCrRatio420 ,
202+ } ) ;
203+
204+ configuration . ImageFormatsManager . SetEncoder ( PngFormat . Instance , new PngEncoder ( )
205+ {
206+ CompressionLevel = PngCompressionLevel . BestCompression ,
207+ FilterMethod = PngFilterMethod . Adaptive ,
208+ } ) ;
209+
210+ configuration . ImageFormatsManager . SetEncoder ( WebpFormat . Instance , new WebpEncoder ( )
211+ {
212+ Quality = 75 ,
213+ Method = WebpEncodingMethod . BestQuality ,
214+ } ) ;
215+
216+ return configuration ;
217+ }
179218}
0 commit comments