@@ -86,10 +86,10 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
86
86
ImageMetadata metadata = image . Metadata ;
87
87
JpegMetadata jpegMetadata = metadata . GetJpegMetadata ( ) ;
88
88
89
- // If the color type was not specified by the user, preserve the color type of the input image, if it's a supported color type .
90
- if ( ! this . colorType . HasValue && IsSupportedColorType ( jpegMetadata . ColorType ) )
89
+ // If the color type was not specified by the user, preserve the color type of the input image.
90
+ if ( ! this . colorType . HasValue )
91
91
{
92
- this . colorType = jpegMetadata . ColorType ;
92
+ this . colorType = GetFallbackColorType ( image ) ;
93
93
}
94
94
95
95
// Compute number of components based on color type in options.
@@ -156,6 +156,39 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
156
156
stream . Flush ( ) ;
157
157
}
158
158
159
+ /// <summary>
160
+ /// If color type was not set, set it based on the given image.
161
+ /// Note, if there is no metadata and the image has multiple components this method
162
+ /// returns <see langword="null"/> defering the field assignment
163
+ /// to <see cref="InitQuantizationTables(int, JpegMetadata, out Block8x8F, out Block8x8F)"/>.
164
+ /// </summary>
165
+ private static JpegColorType ? GetFallbackColorType < TPixel > ( Image < TPixel > image )
166
+ where TPixel : unmanaged, IPixel < TPixel >
167
+ {
168
+ // First inspect the image metadata.
169
+ JpegColorType ? colorType = null ;
170
+ JpegMetadata metadata = image . Metadata . GetJpegMetadata ( ) ;
171
+ if ( IsSupportedColorType ( metadata . ColorType ) )
172
+ {
173
+ return metadata . ColorType ;
174
+ }
175
+
176
+ // Secondly, inspect the pixel type.
177
+ // TODO: PixelTypeInfo should contain a component count!
178
+ bool isGrayscale =
179
+ typeof ( TPixel ) == typeof ( L8 ) || typeof ( TPixel ) == typeof ( L16 ) ||
180
+ typeof ( TPixel ) == typeof ( La16 ) || typeof ( TPixel ) == typeof ( La32 ) ;
181
+
182
+ // We don't set multi-component color types here since we can set it based upon
183
+ // the quality in InitQuantizationTables.
184
+ if ( isGrayscale )
185
+ {
186
+ colorType = JpegColorType . Luminance ;
187
+ }
188
+
189
+ return colorType ;
190
+ }
191
+
159
192
/// <summary>
160
193
/// Returns true, if the color type is supported by the encoder.
161
194
/// </summary>
0 commit comments