Skip to content

Commit fae857f

Browse files
Clamp JPEG quality estimation results.
1 parent e4ba5d3 commit fae857f

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public static int EstimateQuality(ref Block8x8F table, ReadOnlySpan<byte> target
146146
quality = (int)Math.Round(5000.0 / sumPercent);
147147
}
148148

149-
return quality;
149+
return Numerics.Clamp(quality, MinQualityFactor, MaxQualityFactor);
150150
}
151151

152152
/// <summary>

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
99
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
1010
using SixLabors.ImageSharp.PixelFormats;
11+
using SixLabors.ImageSharp.Processing;
1112
using SixLabors.ImageSharp.Tests.TestUtilities;
1213

1314
// ReSharper disable InconsistentNaming
@@ -425,6 +426,32 @@ public void EncodedStringTags_Read()
425426
VerifyEncodedStrings(exif);
426427
}
427428

429+
// https://github.com/SixLabors/ImageSharp/issues/2758
430+
[Theory]
431+
[WithFile(TestImages.Jpeg.Issues.Issue2758, PixelTypes.L8)]
432+
public void Issue2758_DecodeWorks<TPixel>(TestImageProvider<TPixel> provider)
433+
where TPixel : unmanaged, IPixel<TPixel>
434+
{
435+
using Image<TPixel> image = provider.GetImage(JpegDecoder.Instance);
436+
437+
Assert.Equal(59787, image.Width);
438+
Assert.Equal(511, image.Height);
439+
440+
JpegMetadata meta = image.Metadata.GetJpegMetadata();
441+
442+
// Quality determination should be between 1-100.
443+
Assert.Equal(15, meta.LuminanceQuality);
444+
Assert.Equal(1, meta.ChrominanceQuality);
445+
446+
// We want to test the encoder to ensure the determined values can be encoded but not by encoding
447+
// the full size image as it would be too slow.
448+
// We will crop the image to a smaller size and then encode it.
449+
image.Mutate(x => x.Crop(new(0, 0, 100, 100)));
450+
451+
using MemoryStream ms = new();
452+
image.Save(ms, new JpegEncoder());
453+
}
454+
428455
private static void VerifyEncodedStrings(ExifProfile exif)
429456
{
430457
Assert.NotNull(exif);

tests/ImageSharp.Tests/TestImages.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ public static class Issues
320320
public const string HangBadScan = "Jpg/issues/Hang_C438A851.jpg";
321321
public const string Issue2517 = "Jpg/issues/issue2517-bad-d7.jpg";
322322
public const string Issue2638 = "Jpg/issues/Issue2638.jpg";
323+
public const string Issue2758 = "Jpg/issues/issue-2758.jpg";
323324

324325
public static class Fuzz
325326
{
Lines changed: 3 additions & 0 deletions
Loading

0 commit comments

Comments
 (0)