Skip to content

Commit 28c20de

Browse files
JimBobSquarePantsantonfirsov
authored andcommitted
Clamp JPEG quality estimation results.
Signed-off-by: antonfirsov <antonfir@gmail.com>
1 parent 4b910e7 commit 28c20de

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

src/ImageSharp/Formats/Jpeg/Components/Quantization.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ public static int EstimateQuality(ref Block8x8F table, ReadOnlySpan<byte> target
147147
quality = (int)Math.Round(5000.0 / sumPercent);
148148
}
149149

150-
return quality;
150+
return Numerics.Clamp(quality, MinQualityFactor, MaxQualityFactor);
151151
}
152152

153153
/// <summary>

tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs

+27
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
1111
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
1212
using SixLabors.ImageSharp.PixelFormats;
13+
using SixLabors.ImageSharp.Processing;
1314

1415
using Xunit;
1516

@@ -361,6 +362,32 @@ public void EncodedStringTags_Read()
361362
{
362363
ExifProfile exif = image.Metadata.ExifProfile;
363364
VerifyEncodedStrings(exif);
365+
}
366+
367+
// https://github.com/SixLabors/ImageSharp/issues/2758
368+
[Theory]
369+
[WithFile(TestImages.Jpeg.Issues.Issue2758, PixelTypes.L8)]
370+
public void Issue2758_DecodeWorks<TPixel>(TestImageProvider<TPixel> provider)
371+
where TPixel : unmanaged, IPixel<TPixel>
372+
{
373+
using Image<TPixel> image = provider.GetImage(JpegDecoder.Instance);
374+
375+
Assert.Equal(59787, image.Width);
376+
Assert.Equal(511, image.Height);
377+
378+
JpegMetadata meta = image.Metadata.GetJpegMetadata();
379+
380+
// Quality determination should be between 1-100.
381+
Assert.Equal(15, meta.LuminanceQuality);
382+
Assert.Equal(1, meta.ChrominanceQuality);
383+
384+
// We want to test the encoder to ensure the determined values can be encoded but not by encoding
385+
// the full size image as it would be too slow.
386+
// We will crop the image to a smaller size and then encode it.
387+
image.Mutate(x => x.Crop(new(0, 0, 100, 100)));
388+
389+
using MemoryStream ms = new();
390+
image.Save(ms, new JpegEncoder());
364391
}
365392
}
366393

tests/ImageSharp.Tests/TestImages.cs

+1
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ public static class Issues
269269
public const string ValidExifArgumentNullExceptionOnEncode = "Jpg/issues/Issue2087-exif-null-reference-on-encode.jpg";
270270
public const string Issue2133DeduceColorSpace = "Jpg/issues/Issue2133.jpg";
271271
public const string HangBadScan = "Jpg/issues/Hang_C438A851.jpg";
272+
public const string Issue2758 = "Jpg/issues/issue-2758.jpg";
272273

273274
public static class Fuzz
274275
{
Loading

0 commit comments

Comments
 (0)