@@ -25,6 +25,11 @@ public sealed class JpegEncoder : IImageEncoder, IJpegEncoderOptions
2525 /// </summary>
2626 public JpegSubsample ? Subsample { get ; set ; }
2727
28+ /// <summary>
29+ /// Gets or sets the color type, that will be used to encode the image.
30+ /// </summary>
31+ public JpegColorType ? ColorType { get ; set ; }
32+
2833 /// <summary>
2934 /// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>.
3035 /// </summary>
@@ -35,6 +40,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream)
3540 where TPixel : unmanaged, IPixel < TPixel >
3641 {
3742 var encoder = new JpegEncoderCore ( this ) ;
43+ this . InitializeColorType < TPixel > ( image ) ;
3844 encoder . Encode ( image , stream ) ;
3945 }
4046
@@ -50,7 +56,31 @@ public Task EncodeAsync<TPixel>(Image<TPixel> image, Stream stream, Cancellation
5056 where TPixel : unmanaged, IPixel < TPixel >
5157 {
5258 var encoder = new JpegEncoderCore ( this ) ;
59+ this . InitializeColorType < TPixel > ( image ) ;
5360 return encoder . EncodeAsync ( image , stream , cancellationToken ) ;
5461 }
62+
63+ /// <summary>
64+ /// If ColorType was not set, set it based on the given image.
65+ /// </summary>
66+ private void InitializeColorType < TPixel > ( Image < TPixel > image )
67+ where TPixel : unmanaged, IPixel < TPixel >
68+ {
69+ // First inspect the image metadata.
70+ if ( this . ColorType == null )
71+ {
72+ JpegMetadata metadata = image . Metadata . GetJpegMetadata ( ) ;
73+ this . ColorType = metadata . ColorType ;
74+ }
75+
76+ // Secondly, inspect the pixel type.
77+ if ( this . ColorType == null )
78+ {
79+ bool isGrayscale =
80+ typeof ( TPixel ) == typeof ( L8 ) || typeof ( TPixel ) == typeof ( L16 ) ||
81+ typeof ( TPixel ) == typeof ( La16 ) || typeof ( TPixel ) == typeof ( La32 ) ;
82+ this . ColorType = isGrayscale ? JpegColorType . Luminance : JpegColorType . YCbCr ;
83+ }
84+ }
5585 }
5686}
0 commit comments