Browse Source

Use using declarations to reduce nesting

pull/1090/head
Brian Popow 7 years ago
parent
commit
38454f8fde
  1. 39
      tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs
  2. 16
      tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs
  3. 38
      tests/ImageSharp.Tests/Drawing/DrawImageTests.cs
  4. 144
      tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs
  5. 45
      tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs
  6. 4
      tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs
  7. 41
      tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs
  8. 40
      tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs
  9. 42
      tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs
  10. 34
      tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs
  11. 8
      tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs
  12. 8
      tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs
  13. 8
      tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs
  14. 4
      tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs
  15. 32
      tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs
  16. 4
      tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs
  17. 12
      tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs
  18. 45
      tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs
  19. 26
      tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs
  20. 12
      tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs
  21. 8
      tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs
  22. 4
      tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs
  23. 6
      tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs
  24. 4
      tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs
  25. 4
      tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs
  26. 44
      tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs
  27. 52
      tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs
  28. 49
      tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs
  29. 22
      tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs
  30. 60
      tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs
  31. 40
      tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs
  32. 4
      tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs
  33. 6
      tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs
  34. 4
      tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs
  35. 24
      tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs
  36. 24
      tests/ImageSharp.Tests/Image/ImageCloneTests.cs
  37. 16
      tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs
  38. 31
      tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs
  39. 6
      tests/ImageSharp.Tests/Image/ImageRotationTests.cs
  40. 4
      tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs
  41. 14
      tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs
  42. 24
      tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs
  43. 24
      tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs
  44. 24
      tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs
  45. 16
      tests/ImageSharp.Tests/Image/ImageTests.Save.cs
  46. 20
      tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs
  47. 16
      tests/ImageSharp.Tests/Image/ImageTests.cs
  48. 30
      tests/ImageSharp.Tests/Memory/Buffer2DTests.cs
  49. 28
      tests/ImageSharp.Tests/Memory/BufferAreaTests.cs
  50. 4
      tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs
  51. 12
      tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs
  52. 4
      tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs
  53. 10
      tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs
  54. 8
      tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs
  55. 4
      tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs
  56. 16
      tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs
  57. 28
      tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs
  58. 10
      tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs
  59. 8
      tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs
  60. 16
      tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs
  61. 10
      tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs
  62. 8
      tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs
  63. 97
      tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs
  64. 6
      tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs
  65. 24
      tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs
  66. 16
      tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs
  67. 4
      tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs
  68. 4
      tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs
  69. 4
      tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs
  70. 8
      tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs
  71. 46
      tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs
  72. 0
      tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs
  73. 8
      tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs
  74. 8
      tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs
  75. 12
      tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs
  76. 18
      tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs
  77. 6
      tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs
  78. 22
      tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs
  79. 48
      tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs
  80. 12
      tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs
  81. 50
      tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs
  82. 32
      tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs
  83. 22
      tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs

39
tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs

@ -20,8 +20,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced
public void WhenMemoryIsOwned<TPixel>(TestImageProvider<TPixel> provider) public void WhenMemoryIsOwned<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image0 = provider.GetImage()) using Image<TPixel> image0 = provider.GetImage();
{
var targetBuffer = new TPixel[image0.Width * image0.Height]; var targetBuffer = new TPixel[image0.Width * image0.Height];
// Act: // Act:
@ -31,13 +30,11 @@ namespace SixLabors.ImageSharp.Tests.Advanced
Assert.Equal(image0.Width * image0.Height, memory.Length); Assert.Equal(image0.Width * image0.Height, memory.Length);
memory.Span.CopyTo(targetBuffer); memory.Span.CopyTo(targetBuffer);
using (Image<TPixel> image1 = provider.GetImage()) using Image<TPixel> image1 = provider.GetImage();
{
// We are using a copy of the original image for assertion // We are using a copy of the original image for assertion
image1.ComparePixelBufferTo(targetBuffer); image1.ComparePixelBufferTo(targetBuffer);
} }
}
}
[Theory] [Theory]
[WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32 | PixelTypes.Bgr24)] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32 | PixelTypes.Bgr24)]
@ -45,8 +42,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced
public void WhenMemoryIsConsumed<TPixel>(TestImageProvider<TPixel> provider) public void WhenMemoryIsConsumed<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image0 = provider.GetImage()) using Image<TPixel> image0 = provider.GetImage();
{
var targetBuffer = new TPixel[image0.Width * image0.Height]; var targetBuffer = new TPixel[image0.Width * image0.Height];
image0.GetPixelSpan().CopyTo(targetBuffer); image0.GetPixelSpan().CopyTo(targetBuffer);
@ -54,20 +50,17 @@ namespace SixLabors.ImageSharp.Tests.Advanced
Memory<TPixel> externalMemory = managerOfExternalMemory.Memory; Memory<TPixel> externalMemory = managerOfExternalMemory.Memory;
using (var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height)) using var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height);
{
Memory<TPixel> internalMemory = image1.GetPixelMemory(); Memory<TPixel> internalMemory = image1.GetPixelMemory();
Assert.Equal(targetBuffer.Length, internalMemory.Length); Assert.Equal(targetBuffer.Length, internalMemory.Length);
Assert.True(Unsafe.AreSame(ref targetBuffer[0], ref internalMemory.Span[0])); Assert.True(Unsafe.AreSame(ref targetBuffer[0], ref internalMemory.Span[0]));
image0.ComparePixelBufferTo(internalMemory.Span); image0.ComparePixelBufferTo(internalMemory.Span);
}
// Make sure externalMemory works after destruction: // Make sure externalMemory works after destruction:
image0.ComparePixelBufferTo(externalMemory.Span); image0.ComparePixelBufferTo(externalMemory.Span);
} }
} }
}
[Theory] [Theory]
[WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)]
@ -75,8 +68,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced
public void GetPixelRowMemory<TPixel>(TestImageProvider<TPixel> provider) public void GetPixelRowMemory<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var targetBuffer = new TPixel[image.Width * image.Height]; var targetBuffer = new TPixel[image.Width * image.Height];
// Act: // Act:
@ -87,13 +79,11 @@ namespace SixLabors.ImageSharp.Tests.Advanced
} }
// Assert: // Assert:
using (Image<TPixel> image1 = provider.GetImage()) using Image<TPixel> image1 = provider.GetImage();
{
// We are using a copy of the original image for assertion // We are using a copy of the original image for assertion
image1.ComparePixelBufferTo(targetBuffer); image1.ComparePixelBufferTo(targetBuffer);
} }
}
}
[Theory] [Theory]
[WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)]
@ -101,8 +91,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced
public void GetPixelRowSpan<TPixel>(TestImageProvider<TPixel> provider) public void GetPixelRowSpan<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var targetBuffer = new TPixel[image.Width * image.Height]; var targetBuffer = new TPixel[image.Width * image.Height];
// Act: // Act:
@ -113,13 +102,11 @@ namespace SixLabors.ImageSharp.Tests.Advanced
} }
// Assert: // Assert:
using (Image<TPixel> image1 = provider.GetImage()) using Image<TPixel> image1 = provider.GetImage();
{
// We are using a copy of the original image for assertion // We are using a copy of the original image for assertion
image1.ComparePixelBufferTo(targetBuffer); image1.ComparePixelBufferTo(targetBuffer);
} }
}
}
#pragma warning disable 0618 #pragma warning disable 0618
@ -128,8 +115,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced
public unsafe void DangerousGetPinnableReference_CopyToBuffer<TPixel>(TestImageProvider<TPixel> provider) public unsafe void DangerousGetPinnableReference_CopyToBuffer<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var targetBuffer = new TPixel[image.Width * image.Height]; var targetBuffer = new TPixel[image.Width * image.Height];
ref byte source = ref Unsafe.As<TPixel, byte>(ref targetBuffer[0]); ref byte source = ref Unsafe.As<TPixel, byte>(ref targetBuffer[0]);
@ -145,4 +131,3 @@ namespace SixLabors.ImageSharp.Tests.Advanced
} }
} }
} }
}

16
tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs

@ -15,32 +15,27 @@ namespace SixLabors.ImageSharp.Tests.Common
[InlineData(-1)] [InlineData(-1)]
public void Skip_CountZeroOrLower_PositionNotChanged(int count) public void Skip_CountZeroOrLower_PositionNotChanged(int count)
{ {
using (var memStream = new MemoryStream(5)) using var memStream = new MemoryStream(5);
{
memStream.Position = 4; memStream.Position = 4;
memStream.Skip(count); memStream.Skip(count);
Assert.Equal(4, memStream.Position); Assert.Equal(4, memStream.Position);
} }
}
[Fact] [Fact]
public void Skip_SeekableStream_SeekIsCalled() public void Skip_SeekableStream_SeekIsCalled()
{ {
using (var seekableStream = new SeekableStream(4)) using var seekableStream = new SeekableStream(4);
{
seekableStream.Skip(4); seekableStream.Skip(4);
Assert.Equal(4, seekableStream.Offset); Assert.Equal(4, seekableStream.Offset);
Assert.Equal(SeekOrigin.Current, seekableStream.Loc); Assert.Equal(SeekOrigin.Current, seekableStream.Loc);
} }
}
[Fact] [Fact]
public void Skip_NonSeekableStream_BytesAreRead() public void Skip_NonSeekableStream_BytesAreRead()
{ {
using (var nonSeekableStream = new NonSeekableStream()) using var nonSeekableStream = new NonSeekableStream();
{
nonSeekableStream.Skip(5); nonSeekableStream.Skip(5);
Assert.Equal(3, nonSeekableStream.Counts.Count); Assert.Equal(3, nonSeekableStream.Counts.Count);
@ -49,18 +44,15 @@ namespace SixLabors.ImageSharp.Tests.Common
Assert.Equal(3, nonSeekableStream.Counts[1]); Assert.Equal(3, nonSeekableStream.Counts[1]);
Assert.Equal(1, nonSeekableStream.Counts[2]); Assert.Equal(1, nonSeekableStream.Counts[2]);
} }
}
[Fact] [Fact]
public void Skip_EofStream_NoExceptionIsThrown() public void Skip_EofStream_NoExceptionIsThrown()
{ {
using (var eofStream = new EofStream(7)) using var eofStream = new EofStream(7);
{
eofStream.Skip(7); eofStream.Skip(7);
Assert.Equal(0, eofStream.Position); Assert.Equal(0, eofStream.Position);
} }
}
private class SeekableStream : MemoryStream private class SeekableStream : MemoryStream
{ {

38
tests/ImageSharp.Tests/Drawing/DrawImageTests.cs

@ -34,9 +34,8 @@ namespace SixLabors.ImageSharp.Tests.Drawing
public void ImageBlendingMatchesSvgSpecExamples<TPixel>(TestImageProvider<TPixel> provider, PixelColorBlendingMode mode) public void ImageBlendingMatchesSvgSpecExamples<TPixel>(TestImageProvider<TPixel> provider, PixelColorBlendingMode mode)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> background = provider.GetImage()) using Image<TPixel> background = provider.GetImage();
using (var source = Image.Load<TPixel>(TestFile.Create(TestImages.Png.Ducky).Bytes)) using var source = Image.Load<TPixel>(TestFile.Create(TestImages.Png.Ducky).Bytes);
{
background.Mutate(x => x.DrawImage(source, mode, 1F)); background.Mutate(x => x.DrawImage(source, mode, 1F));
background.DebugSave( background.DebugSave(
provider, provider,
@ -52,7 +51,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing
appendPixelTypeToFileName: false, appendPixelTypeToFileName: false,
appendSourceFileOrDescription: false); appendSourceFileOrDescription: false);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32, TestImages.Png.Splash, PixelColorBlendingMode.Normal, 1f)] [WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32, TestImages.Png.Splash, PixelColorBlendingMode.Normal, 1f)]
@ -73,9 +71,8 @@ namespace SixLabors.ImageSharp.Tests.Drawing
float opacity) float opacity)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (var blend = Image.Load<TPixel>(TestFile.Create(brushImage).Bytes)) using var blend = Image.Load<TPixel>(TestFile.Create(brushImage).Bytes);
{
var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4); var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4);
var position = new Point(image.Width / 8, image.Height / 8); var position = new Point(image.Width / 8, image.Height / 8);
blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic)); blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic));
@ -95,7 +92,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing
provider, provider,
testInfo); testInfo);
} }
}
[Theory] [Theory]
[WithTestPatternImage(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)] [WithTestPatternImage(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)]
@ -104,11 +100,10 @@ namespace SixLabors.ImageSharp.Tests.Drawing
{ {
byte[] brushData = TestFile.Create(TestImages.Png.Ducky).Bytes; byte[] brushData = TestFile.Create(TestImages.Png.Ducky).Bytes;
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (Image brushImage = provider.PixelType == PixelTypes.Rgba32 using Image brushImage = provider.PixelType == PixelTypes.Rgba32
? (Image)Image.Load<Bgra32>(brushData) ? (Image)Image.Load<Bgra32>(brushData)
: Image.Load<Rgba32>(brushData)) : Image.Load<Rgba32>(brushData);
{
image.Mutate(c => c.DrawImage(brushImage, 0.5f)); image.Mutate(c => c.DrawImage(brushImage, 0.5f));
image.DebugSave(provider, appendSourceFileOrDescription: false); image.DebugSave(provider, appendSourceFileOrDescription: false);
@ -117,7 +112,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing
provider, provider,
appendSourceFileOrDescription: false); appendSourceFileOrDescription: false);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 0, 0)] [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 0, 0)]
@ -126,9 +120,8 @@ namespace SixLabors.ImageSharp.Tests.Drawing
[WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, -25, -30)] [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, -25, -30)]
public void WorksWithDifferentLocations(TestImageProvider<Rgba32> provider, int x, int y) public void WorksWithDifferentLocations(TestImageProvider<Rgba32> provider, int x, int y)
{ {
using (Image<Rgba32> background = provider.GetImage()) using Image<Rgba32> background = provider.GetImage();
using (var overlay = new Image<Rgba32>(50, 50)) using var overlay = new Image<Rgba32>(50, 50);
{
overlay.GetPixelSpan().Fill(Rgba32.Black); overlay.GetPixelSpan().Fill(Rgba32.Black);
background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F));
@ -145,16 +138,14 @@ namespace SixLabors.ImageSharp.Tests.Drawing
appendPixelTypeToFileName: false, appendPixelTypeToFileName: false,
appendSourceFileOrDescription: false); appendSourceFileOrDescription: false);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Splash, PixelTypes.Rgba32)] [WithFile(TestImages.Png.Splash, PixelTypes.Rgba32)]
public void DrawTransformed<TPixel>(TestImageProvider<TPixel> provider) public void DrawTransformed<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (var blend = Image.Load<TPixel>(TestFile.Create(TestImages.Bmp.Car).Bytes)) using var blend = Image.Load<TPixel>(TestFile.Create(TestImages.Bmp.Car).Bytes);
{
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(45F) .AppendRotationDegrees(45F)
.AppendScale(new SizeF(.25F, .25F)) .AppendScale(new SizeF(.25F, .25F))
@ -175,7 +166,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing
appendSourceFileOrDescription: false, appendSourceFileOrDescription: false,
appendPixelTypeToFileName: false); appendPixelTypeToFileName: false);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, -30)] [WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, -30)]
@ -184,9 +174,8 @@ namespace SixLabors.ImageSharp.Tests.Drawing
[WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, 130)] [WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, 130)]
public void NonOverlappingImageThrows(TestImageProvider<Rgba32> provider, int x, int y) public void NonOverlappingImageThrows(TestImageProvider<Rgba32> provider, int x, int y)
{ {
using (Image<Rgba32> background = provider.GetImage()) using Image<Rgba32> background = provider.GetImage();
using (var overlay = new Image<Rgba32>(Configuration.Default, 10, 10, Rgba32.Black)) using var overlay = new Image<Rgba32>(Configuration.Default, 10, 10, Rgba32.Black);
{
ImageProcessingException ex = Assert.Throws<ImageProcessingException>(Test); ImageProcessingException ex = Assert.Throws<ImageProcessingException>(Test);
Assert.Contains("does not overlap", ex.ToString()); Assert.Contains("does not overlap", ex.ToString());
@ -198,4 +187,3 @@ namespace SixLabors.ImageSharp.Tests.Drawing
} }
} }
} }
}

144
tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs

@ -37,27 +37,23 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_MiscellaneousBitmaps<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_MiscellaneousBitmaps<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
if (TestEnvironment.IsWindows) if (TestEnvironment.IsWindows)
{ {
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(BitfieldsBmpFiles), PixelTypes.Rgba32)] [WithFileCollection(nameof(BitfieldsBmpFiles), PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeBitfields<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBitfields<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit16Inverted, PixelTypes.Rgba32)] [WithFile(Bit16Inverted, PixelTypes.Rgba32)]
@ -65,12 +61,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_Inverted<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_Inverted<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit1, PixelTypes.Rgba32)] [WithFile(Bit1, PixelTypes.Rgba32)]
@ -78,20 +72,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_1Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_1Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(Bit4, PixelTypes.Rgba32)] [WithFile(Bit4, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_4Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_4Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows.
@ -100,55 +91,46 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
} }
}
[Theory] [Theory]
[WithFile(Bit8, PixelTypes.Rgba32)] [WithFile(Bit8, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_8Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_8Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit16, PixelTypes.Rgba32)] [WithFile(Bit16, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_16Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit32Rgb, PixelTypes.Rgba32)] [WithFile(Bit32Rgb, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_32Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_32Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Rgba32v4, PixelTypes.Rgba32)] [WithFile(Rgba32v4, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_32BitV4Header_Fast<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_32BitV4Header_Fast<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(RLE4Cut, PixelTypes.Rgba32)] [WithFile(RLE4Cut, PixelTypes.Rgba32)]
@ -157,8 +139,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit_WithDelta<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit_WithDelta<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black });
{
image.DebugSave(provider); image.DebugSave(provider);
// The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows.
@ -167,15 +148,13 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
} }
}
[Theory] [Theory]
[WithFile(RLE4, PixelTypes.Rgba32)] [WithFile(RLE4, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black });
{
image.DebugSave(provider); image.DebugSave(provider);
// The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows.
@ -184,7 +163,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
} }
}
[Theory] [Theory]
[WithFile(RLE8Cut, PixelTypes.Rgba32)] [WithFile(RLE8Cut, PixelTypes.Rgba32)]
@ -194,15 +172,13 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRefDecoder<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRefDecoder<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black });
{
image.DebugSave(provider); image.DebugSave(provider);
if (TestEnvironment.IsWindows) if (TestEnvironment.IsWindows)
{ {
image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder());
} }
} }
}
[Theory] [Theory]
[WithFile(RLE8Cut, PixelTypes.Rgba32)] [WithFile(RLE8Cut, PixelTypes.Rgba32)]
@ -210,12 +186,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecoder<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecoder<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette });
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(RLE8, PixelTypes.Rgba32)] [WithFile(RLE8, PixelTypes.Rgba32)]
@ -223,12 +197,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette });
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(RLE24, PixelTypes.Rgba32)] [WithFile(RLE24, PixelTypes.Rgba32)]
@ -237,48 +209,41 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) using Image<TPixel> image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black });
{
image.DebugSave(provider); image.DebugSave(provider);
// TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file.
// image.CompareToOriginal(provider); // image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(RgbaAlphaBitfields, PixelTypes.Rgba32)] [WithFile(RgbaAlphaBitfields, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeAlphaBitfields<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeAlphaBitfields<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file.
// image.CompareToOriginal(provider); // image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit32Rgba, PixelTypes.Rgba32)] [WithFile(Bit32Rgba, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(Rgba321010102, PixelTypes.Rgba32)] [WithFile(Rgba321010102, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel // Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel
@ -288,7 +253,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
// Exporting the image as PNG with GIMP yields to the same result as the ImageSharp implementation. // Exporting the image as PNG with GIMP yields to the same result as the ImageSharp implementation.
image.CompareToOriginal(provider, ImageComparer.TolerantPercentage(6.1f), new MagickReferenceDecoder()); image.CompareToOriginal(provider, ImageComparer.TolerantPercentage(6.1f), new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(WinBmpv2, PixelTypes.Rgba32)] [WithFile(WinBmpv2, PixelTypes.Rgba32)]
@ -296,36 +260,30 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecodeBmpv2<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBmpv2<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(WinBmpv3, PixelTypes.Rgba32)] [WithFile(WinBmpv3, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeBmpv3<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBmpv3<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(LessThanFullSizedPalette, PixelTypes.Rgba32)] [WithFile(LessThanFullSizedPalette, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeLessThanFullPalette<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeLessThanFullPalette<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(OversizedPalette, PixelTypes.Rgba32)] [WithFile(OversizedPalette, PixelTypes.Rgba32)]
@ -333,15 +291,13 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecodeOversizedPalette<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeOversizedPalette<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
if (TestEnvironment.IsWindows) if (TestEnvironment.IsWindows)
{ {
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
} }
}
[Theory] [Theory]
[WithFile(InvalidPaletteSize, PixelTypes.Rgba32)] [WithFile(InvalidPaletteSize, PixelTypes.Rgba32)]
@ -375,36 +331,30 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecodeAdobeBmpv3<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeAdobeBmpv3<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(Rgba32bf56AdobeV3, PixelTypes.Rgba32)] [WithFile(Rgba32bf56AdobeV3, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, new MagickReferenceDecoder()); image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(WinBmpv4, PixelTypes.Rgba32)] [WithFile(WinBmpv4, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecodeBmpv4<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBmpv4<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(WinBmpv5, PixelTypes.Rgba32)] [WithFile(WinBmpv5, PixelTypes.Rgba32)]
@ -412,48 +362,40 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecodeBmpv5<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecodeBmpv5<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Pal8Offset, PixelTypes.Rgba32)] [WithFile(Pal8Offset, PixelTypes.Rgba32)]
public void BmpDecoder_RespectsFileHeaderOffset<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_RespectsFileHeaderOffset<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(F, CommonNonDefaultPixelTypes)] [WithFile(F, CommonNonDefaultPixelTypes)]
public void BmpDecoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Bit8Palette4, PixelTypes.Rgba32)] [WithFile(Bit8Palette4, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode4BytePerEntryPalette<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode4BytePerEntryPalette<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider); image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[InlineData(Bit32Rgb, 32)] [InlineData(Bit32Rgb, 32)]
@ -471,13 +413,11 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void Identify_DetectsCorrectPixelType(string imagePath, int expectedPixelSize) public void Identify_DetectsCorrectPixelType(string imagePath, int expectedPixelSize)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
IImageInfo imageInfo = Image.Identify(stream); IImageInfo imageInfo = Image.Identify(stream);
Assert.NotNull(imageInfo); Assert.NotNull(imageInfo);
Assert.Equal(expectedPixelSize, imageInfo.PixelType?.BitsPerPixel); Assert.Equal(expectedPixelSize, imageInfo.PixelType?.BitsPerPixel);
} }
}
[Theory] [Theory]
[InlineData(Bit32Rgb, 127, 64)] [InlineData(Bit32Rgb, 127, 64)]
@ -491,54 +431,45 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void Identify_DetectsCorrectWidthAndHeight(string imagePath, int expectedWidth, int expectedHeight) public void Identify_DetectsCorrectWidthAndHeight(string imagePath, int expectedWidth, int expectedHeight)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
IImageInfo imageInfo = Image.Identify(stream); IImageInfo imageInfo = Image.Identify(stream);
Assert.NotNull(imageInfo); Assert.NotNull(imageInfo);
Assert.Equal(expectedWidth, imageInfo.Width); Assert.Equal(expectedWidth, imageInfo.Width);
Assert.Equal(expectedHeight, imageInfo.Height); Assert.Equal(expectedHeight, imageInfo.Height);
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new BmpDecoder(); var decoder = new BmpDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
[Theory] [Theory]
[WithFile(Os2v2Short, PixelTypes.Rgba32)] [WithFile(Os2v2Short, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_Os2v2XShortHeader<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_Os2v2XShortHeader<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file.
// image.CompareToOriginal(provider); // image.CompareToOriginal(provider);
} }
}
[Theory] [Theory]
[WithFile(Os2v2, PixelTypes.Rgba32)] [WithFile(Os2v2, PixelTypes.Rgba32)]
public void BmpDecoder_CanDecode_Os2v2Header<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_Os2v2Header<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it, // TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it,
@ -546,7 +477,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
// The results are the same as the image sharp implementation. // The results are the same as the image sharp implementation.
// image.CompareToOriginal(provider, new MagickReferenceDecoder()); // image.CompareToOriginal(provider, new MagickReferenceDecoder());
} }
}
[Theory] [Theory]
[WithFile(Os2BitmapArray, PixelTypes.Rgba32)] [WithFile(Os2BitmapArray, PixelTypes.Rgba32)]
@ -561,8 +491,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void BmpDecoder_CanDecode_Os2BitmapArray<TPixel>(TestImageProvider<TPixel> provider) public void BmpDecoder_CanDecode_Os2BitmapArray<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new BmpDecoder())) using Image<TPixel> image = provider.GetImage(new BmpDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file.
@ -570,4 +499,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
} }
} }
} }
}

45
tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs

@ -54,23 +54,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
var options = new BmpEncoder(); var options = new BmpEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
ImageMetadata meta = output.Metadata; ImageMetadata meta = output.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
}
[Theory] [Theory]
[MemberData(nameof(BmpBitsPerPixelFiles))] [MemberData(nameof(BmpBitsPerPixelFiles))]
@ -79,22 +73,16 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
var options = new BmpEncoder(); var options = new BmpEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
BmpMetadata meta = output.Metadata.GetBmpMetadata(); BmpMetadata meta = output.Metadata.GetBmpMetadata();
Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel);
} }
}
}
}
[Theory] [Theory]
[WithTestPatternImage(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] [WithTestPatternImage(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)]
@ -192,8 +180,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
return; return;
} }
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new BmpEncoder var encoder = new BmpEncoder
{ {
BitsPerPixel = BmpBitsPerPixel.Pixel8, BitsPerPixel = BmpBitsPerPixel.Pixel8,
@ -201,12 +188,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
}; };
string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false);
IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile);
using (var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder)) using var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder);
{
referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false);
} }
}
}
[Theory] [Theory]
[WithFile(Bit32Rgb, PixelTypes.Rgba32)] [WithFile(Bit32Rgb, PixelTypes.Rgba32)]
@ -218,8 +202,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
return; return;
} }
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new BmpEncoder var encoder = new BmpEncoder
{ {
BitsPerPixel = BmpBitsPerPixel.Pixel8, BitsPerPixel = BmpBitsPerPixel.Pixel8,
@ -227,12 +210,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
}; };
string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false);
IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile);
using (var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder)) using var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder);
{
referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false);
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Png.GrayAlpha2BitInterlaced, PixelTypes.Rgba32, BmpBitsPerPixel.Pixel32)] [WithFile(TestImages.Png.GrayAlpha2BitInterlaced, PixelTypes.Rgba32, BmpBitsPerPixel.Pixel32)]
@ -247,8 +227,8 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
ImageComparer customComparer = null) ImageComparer customComparer = null)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
// There is no alpha in bmp with less then 32 bits per pixels, so the reference image will be made opaque. // There is no alpha in bmp with less then 32 bits per pixels, so the reference image will be made opaque.
if (bitsPerPixel != BmpBitsPerPixel.Pixel32) if (bitsPerPixel != BmpBitsPerPixel.Pixel32)
{ {
@ -262,4 +242,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
} }
} }
} }
}

4
tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs

@ -36,8 +36,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
public void Identify_DetectsCorrectBitmapInfoHeaderType(string imagePath, BmpInfoHeaderType expectedInfoHeaderType) public void Identify_DetectsCorrectBitmapInfoHeaderType(string imagePath, BmpInfoHeaderType expectedInfoHeaderType)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
IImageInfo imageInfo = Image.Identify(stream); IImageInfo imageInfo = Image.Identify(stream);
Assert.NotNull(imageInfo); Assert.NotNull(imageInfo);
BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata(); BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata();
@ -46,4 +45,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Bmp
} }
} }
} }
}

41
tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs

@ -23,13 +23,11 @@ namespace SixLabors.ImageSharp.Tests
public void ResolutionShouldChange<TPixel>(TestImageProvider<TPixel> provider) public void ResolutionShouldChange<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Metadata.VerticalResolution = 150; image.Metadata.VerticalResolution = 150;
image.Metadata.HorizontalResolution = 150; image.Metadata.HorizontalResolution = 150;
image.DebugSave(provider); image.DebugSave(provider);
} }
}
[Fact] [Fact]
public void ImageCanEncodeToString() public void ImageCanEncodeToString()
@ -38,13 +36,11 @@ namespace SixLabors.ImageSharp.Tests
foreach (TestFile file in Files) foreach (TestFile file in Files)
{ {
using (Image<Rgba32> image = file.CreateRgba32Image()) using Image<Rgba32> image = file.CreateRgba32Image();
{
string filename = path + "/" + file.FileNameWithoutExtension + ".txt"; string filename = path + "/" + file.FileNameWithoutExtension + ".txt";
File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance)); File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance));
} }
} }
}
[Fact] [Fact]
public void DecodeThenEncodeImageFromStreamShouldSucceed() public void DecodeThenEncodeImageFromStreamShouldSucceed()
@ -53,12 +49,10 @@ namespace SixLabors.ImageSharp.Tests
foreach (TestFile file in Files) foreach (TestFile file in Files)
{ {
using (Image<Rgba32> image = file.CreateRgba32Image()) using Image<Rgba32> image = file.CreateRgba32Image();
{
image.Save($"{path}/{file.FileName}"); image.Save($"{path}/{file.FileName}");
} }
} }
}
public static readonly TheoryData<string> QuantizerNames = public static readonly TheoryData<string> QuantizerNames =
new TheoryData<string> new TheoryData<string>
@ -100,8 +94,7 @@ namespace SixLabors.ImageSharp.Tests
foreach (TestFile file in Files) foreach (TestFile file in Files)
{ {
using (Image<Rgba32> image = file.CreateRgba32Image()) using Image<Rgba32> image = file.CreateRgba32Image();
{
using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp")) using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp"))
{ {
image.SaveAsBmp(output); image.SaveAsBmp(output);
@ -123,7 +116,6 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}
[Fact] [Fact]
public void ImageShouldPreservePixelByteOrderWhenSerialized() public void ImageShouldPreservePixelByteOrderWhenSerialized()
@ -132,21 +124,16 @@ namespace SixLabors.ImageSharp.Tests
foreach (TestFile file in Files) foreach (TestFile file in Files)
{ {
byte[] serialized; using var image = Image.Load(file.Bytes, out IImageFormat mimeType);
using (var image = Image.Load(file.Bytes, out IImageFormat mimeType)) using var memoryStream = new MemoryStream();
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, mimeType); image.Save(memoryStream, mimeType);
memoryStream.Flush(); memoryStream.Flush();
serialized = memoryStream.ToArray(); byte[] serialized = memoryStream.ToArray();
}
using (var image2 = Image.Load<Rgba32>(serialized)) using var image2 = Image.Load<Rgba32>(serialized);
{
image2.Save($"{path}/{file.FileName}"); image2.Save($"{path}/{file.FileName}");
} }
} }
}
[Theory] [Theory]
[InlineData(10, 10, "png")] [InlineData(10, 10, "png")]
@ -170,10 +157,8 @@ namespace SixLabors.ImageSharp.Tests
[InlineData(10, 100, "tga")] [InlineData(10, 100, "tga")]
public void CanIdentifyImageLoadedFromBytes(int width, int height, string extension) public void CanIdentifyImageLoadedFromBytes(int width, int height, string extension)
{ {
using (var image = Image.LoadPixelData(new Rgba32[width * height], width, height)) using var image = Image.LoadPixelData(new Rgba32[width * height], width, height);
{ using var memoryStream = new MemoryStream();
using (var memoryStream = new MemoryStream())
{
IImageFormat format = GetFormat(extension); IImageFormat format = GetFormat(extension);
image.Save(memoryStream, format); image.Save(memoryStream, format);
memoryStream.Position = 0; memoryStream.Position = 0;
@ -188,22 +173,18 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(format, detectedFormat); Assert.Equal(format, detectedFormat);
} }
}
}
[Fact] [Fact]
public void IdentifyReturnsNullWithInvalidStream() public void IdentifyReturnsNullWithInvalidStream()
{ {
byte[] invalid = new byte[10]; byte[] invalid = new byte[10];
using (var memoryStream = new MemoryStream(invalid)) using var memoryStream = new MemoryStream(invalid);
{
IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format); IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format);
Assert.Null(imageInfo); Assert.Null(imageInfo);
Assert.Null(format); Assert.Null(format);
} }
}
private static IImageFormat GetFormat(string format) private static IImageFormat GetFormat(string format)
{ {

40
tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs

@ -54,12 +54,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
public void Decode_VerifyAllFrames<TPixel>(TestImageProvider<TPixel> provider) public void Decode_VerifyAllFrames<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.DebugSaveMultiFrame(provider); image.DebugSaveMultiFrame(provider);
image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact); image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact);
} }
}
[Fact] [Fact]
public unsafe void Decode_NonTerminatedFinalFrame() public unsafe void Decode_NonTerminatedFinalFrame()
@ -70,29 +68,23 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
fixed (byte* data = testFile.Bytes.AsSpan(0, length)) fixed (byte* data = testFile.Bytes.AsSpan(0, length))
{ {
using (var stream = new UnmanagedMemoryStream(data, length)) using var stream = new UnmanagedMemoryStream(data, length);
{
var decoder = new GifDecoder(); var decoder = new GifDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
Assert.Equal((200, 200), (image.Width, image.Height)); Assert.Equal((200, 200), (image.Width, image.Height));
} }
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Trans, TestPixelTypes)] [WithFile(TestImages.Gif.Trans, TestPixelTypes)]
public void GifDecoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void GifDecoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(BasicVerificationFiles), PixelTypes.Rgba32)] [WithFileCollection(nameof(BasicVerificationFiles), PixelTypes.Rgba32)]
@ -104,35 +96,29 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
expectedFrameCount = 1; expectedFrameCount = 1;
} }
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.Equal(expectedFrameCount, image.Frames.Count); Assert.Equal(expectedFrameCount, image.Frames.Count);
image.DebugSave(provider); image.DebugSave(provider);
image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)]
public void CanDecodeJustOneFrame<TPixel>(TestImageProvider<TPixel> provider) public void CanDecodeJustOneFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First })) using Image<TPixel> image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First });
{
Assert.Equal(1, image.Frames.Count); Assert.Equal(1, image.Frames.Count);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)]
public void CanDecodeAllFrames<TPixel>(TestImageProvider<TPixel> provider) public void CanDecodeAllFrames<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All })) using Image<TPixel> image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All });
{
Assert.True(image.Frames.Count > 1); Assert.True(image.Frames.Count > 1);
} }
}
[Theory] [Theory]
[InlineData(TestImages.Gif.Cheers, 8)] [InlineData(TestImages.Gif.Cheers, 8)]
@ -142,19 +128,16 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
public void DetectPixelSize(string imagePath, int expectedPixelSize) public void DetectPixelSize(string imagePath, int expectedPixelSize)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel);
} }
}
[Fact] [Fact]
public void CanDecodeIntermingledImages() public void CanDecodeIntermingledImages()
{ {
using (var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) using var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes);
using (Image.Load(TestFile.Create(TestImages.Png.Icon).Bytes)) using var load = Image.Load(TestFile.Create(TestImages.Png.Icon).Bytes);
using (var kumin2 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) using var kumin2 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes);
{
for (int i = 0; i < kumin1.Frames.Count; i++) for (int i = 0; i < kumin1.Frames.Count; i++)
{ {
ImageFrame<Rgba32> first = kumin1.Frames[i]; ImageFrame<Rgba32> first = kumin1.Frames[i];
@ -164,4 +147,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
} }
} }
} }
}

42
tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs

@ -30,8 +30,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
public void EncodeGeneratedPatterns<TPixel>(TestImageProvider<TPixel> provider) public void EncodeGeneratedPatterns<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new GifEncoder var encoder = new GifEncoder
{ {
// Use the palette quantizer without dithering to ensure results // Use the palette quantizer without dithering to ensure results
@ -41,15 +40,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
// Always save as we need to compare the encoded output. // Always save as we need to compare the encoded output.
provider.Utility.SaveTestOutputFile(image, "gif", encoder); provider.Utility.SaveTestOutputFile(image, "gif", encoder);
}
// Compare encoded result // Compare encoded result
string path = provider.Utility.GetTestOutputFileName("gif", null, true); string path = provider.Utility.GetTestOutputFileName("gif", null, true);
using (var encoded = Image.Load<Rgba32>(path)) using var encoded = Image.Load<Rgba32>(path);
{
encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif"); encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif");
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
@ -58,23 +54,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var options = new GifEncoder(); var options = new GifEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
ImageMetadata meta = output.Metadata; ImageMetadata meta = output.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
}
[Fact] [Fact]
public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten() public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten()
@ -83,30 +73,23 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var testFile = TestFile.Create(TestImages.Gif.Rings); var testFile = TestFile.Create(TestImages.Gif.Rings);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
GifMetadata metadata = output.Metadata.GetGifMetadata(); GifMetadata metadata = output.Metadata.GetGifMetadata();
Assert.Equal(1, metadata.Comments.Count); Assert.Equal(1, metadata.Comments.Count);
Assert.Equal("ImageSharp", metadata.Comments[0]); Assert.Equal("ImageSharp", metadata.Comments[0]);
} }
}
}
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Cheers, PixelTypes.Rgba32)] [WithFile(TestImages.Gif.Cheers, PixelTypes.Rgba32)]
public void EncodeGlobalPaletteReturnsSmallerFile<TPixel>(TestImageProvider<TPixel> provider) public void EncodeGlobalPaletteReturnsSmallerFile<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new GifEncoder var encoder = new GifEncoder
{ {
ColorTableMode = GifColorTableMode.Global, ColorTableMode = GifColorTableMode.Global,
@ -124,14 +107,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length); Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length);
} }
}
[Fact] [Fact]
public void NonMutatingEncodePreservesPaletteCount() public void NonMutatingEncodePreservesPaletteCount()
{ {
using (var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes)) using var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes);
using (var outStream = new MemoryStream()) using var outStream = new MemoryStream();
{
inStream.Position = 0; inStream.Position = 0;
var image = Image.Load<Rgba32>(inStream); var image = Image.Load<Rgba32>(inStream);
@ -170,4 +151,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
} }
} }
} }
}

34
tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs

@ -57,13 +57,11 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var testFile = TestFile.Create(TestImages.Gif.Rings); var testFile = TestFile.Create(TestImages.Gif.Rings);
using (Image<Rgba32> image = testFile.CreateRgba32Image(options)) using Image<Rgba32> image = testFile.CreateRgba32Image(options);
{
GifMetadata metadata = image.Metadata.GetGifMetadata(); GifMetadata metadata = image.Metadata.GetGifMetadata();
Assert.Equal(1, metadata.Comments.Count); Assert.Equal(1, metadata.Comments.Count);
Assert.Equal("ImageSharp", metadata.Comments[0]); Assert.Equal("ImageSharp", metadata.Comments[0]);
} }
}
[Fact] [Fact]
public void Decode_IgnoreMetadataIsTrue_CommentsAreIgnored() public void Decode_IgnoreMetadataIsTrue_CommentsAreIgnored()
@ -75,12 +73,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var testFile = TestFile.Create(TestImages.Gif.Rings); var testFile = TestFile.Create(TestImages.Gif.Rings);
using (Image<Rgba32> image = testFile.CreateRgba32Image(options)) using Image<Rgba32> image = testFile.CreateRgba32Image(options);
{
GifMetadata metadata = image.Metadata.GetGifMetadata(); GifMetadata metadata = image.Metadata.GetGifMetadata();
Assert.Equal(0, metadata.Comments.Count); Assert.Equal(0, metadata.Comments.Count);
} }
}
[Fact] [Fact]
public void Decode_CanDecodeLargeTextComment() public void Decode_CanDecodeLargeTextComment()
@ -88,14 +84,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var options = new GifDecoder(); var options = new GifDecoder();
var testFile = TestFile.Create(TestImages.Gif.LargeComment); var testFile = TestFile.Create(TestImages.Gif.LargeComment);
using (Image<Rgba32> image = testFile.CreateRgba32Image(options)) using Image<Rgba32> image = testFile.CreateRgba32Image(options);
{
GifMetadata metadata = image.Metadata.GetGifMetadata(); GifMetadata metadata = image.Metadata.GetGifMetadata();
Assert.Equal(2, metadata.Comments.Count); Assert.Equal(2, metadata.Comments.Count);
Assert.Equal(new string('c', 349), metadata.Comments[0]); Assert.Equal(new string('c', 349), metadata.Comments[0]);
Assert.Equal("ImageSharp", metadata.Comments[1]); Assert.Equal("ImageSharp", metadata.Comments[1]);
} }
}
[Fact] [Fact]
public void Encode_PreservesTextData() public void Encode_PreservesTextData()
@ -103,29 +97,24 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
var decoder = new GifDecoder(); var decoder = new GifDecoder();
var testFile = TestFile.Create(TestImages.Gif.LargeComment); var testFile = TestFile.Create(TestImages.Gif.LargeComment);
using (Image<Rgba32> input = testFile.CreateRgba32Image(decoder)) using Image<Rgba32> input = testFile.CreateRgba32Image(decoder);
using (var memoryStream = new MemoryStream()) using var memoryStream = new MemoryStream();
{
input.Save(memoryStream, new GifEncoder()); input.Save(memoryStream, new GifEncoder());
memoryStream.Position = 0; memoryStream.Position = 0;
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream);
{
GifMetadata metadata = image.Metadata.GetGifMetadata(); GifMetadata metadata = image.Metadata.GetGifMetadata();
Assert.Equal(2, metadata.Comments.Count); Assert.Equal(2, metadata.Comments.Count);
Assert.Equal(new string('c', 349), metadata.Comments[0]); Assert.Equal(new string('c', 349), metadata.Comments[0]);
Assert.Equal("ImageSharp", metadata.Comments[1]); Assert.Equal("ImageSharp", metadata.Comments[1]);
} }
}
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new GifDecoder(); var decoder = new GifDecoder();
IImageInfo image = decoder.Identify(Configuration.Default, stream); IImageInfo image = decoder.Identify(Configuration.Default, stream);
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
@ -133,18 +122,15 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new GifDecoder(); var decoder = new GifDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
@ -152,5 +138,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Gif
} }
} }
} }
}
}

8
tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs

@ -128,14 +128,10 @@ namespace SixLabors.ImageSharp.Tests
public void DetectFormatAllocatesCleanBuffer() public void DetectFormatAllocatesCleanBuffer()
{ {
byte[] jpegImage; byte[] jpegImage;
using (var buffer = new MemoryStream()) using var buffer = new MemoryStream();
{ using var image = new Image<Rgba32>(100, 100);
using (var image = new Image<Rgba32>(100, 100))
{
image.SaveAsJpeg(buffer); image.SaveAsJpeg(buffer);
jpegImage = buffer.ToArray(); jpegImage = buffer.ToArray();
}
}
byte[] invalidImage = { 1, 2, 3 }; byte[] invalidImage = { 1, 2, 3 };

8
tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs

@ -43,8 +43,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
{ {
Block8x8F block = CreateRandomFloatBlock(0, 100); Block8x8F block = CreateRandomFloatBlock(0, 100);
using (Buffer2D<float> buffer = Configuration.Default.MemoryAllocator.Allocate2D<float>(20, 20, AllocationOptions.Clean)) using Buffer2D<float> buffer = Configuration.Default.MemoryAllocator.Allocate2D<float>(20, 20, AllocationOptions.Clean);
{
BufferArea<float> area = buffer.GetArea(5, 10, 8, 8); BufferArea<float> area = buffer.GetArea(5, 10, 8, 8);
block.Copy1x1Scale(area); block.Copy1x1Scale(area);
@ -56,7 +55,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
VerifyAllZeroOutsideSubArea(buffer, 5, 10); VerifyAllZeroOutsideSubArea(buffer, 5, 10);
} }
}
[Theory] [Theory]
[InlineData(1, 1)] [InlineData(1, 1)]
@ -71,8 +69,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var start = new Point(50, 50); var start = new Point(50, 50);
using (Buffer2D<float> buffer = Configuration.Default.MemoryAllocator.Allocate2D<float>(100, 100, AllocationOptions.Clean)) using Buffer2D<float> buffer = Configuration.Default.MemoryAllocator.Allocate2D<float>(100, 100, AllocationOptions.Clean);
{
BufferArea<float> area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor); BufferArea<float> area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor);
block.CopyTo(area, horizontalFactor, verticalFactor); block.CopyTo(area, horizontalFactor, verticalFactor);
@ -95,4 +92,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}

8
tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs

@ -38,8 +38,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
public void LoadAndStretchCorners_FromOrigo<TPixel>(TestImageProvider<TPixel> provider) public void LoadAndStretchCorners_FromOrigo<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> s = provider.GetImage()) using Image<TPixel> s = provider.GetImage();
{
var d = default(GenericBlock8x8<TPixel>); var d = default(GenericBlock8x8<TPixel>);
d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0); d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0);
@ -55,15 +54,13 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.Equal(s[0, 7], d[0, 7]); Assert.Equal(s[0, 7], d[0, 7]);
Assert.Equal(s[7, 7], d[7, 7]); Assert.Equal(s[7, 7], d[7, 7]);
} }
}
[Theory] [Theory]
[WithMemberFactory(nameof(CreateTestImage), PixelTypes.Rgb24 | PixelTypes.Rgba32)] [WithMemberFactory(nameof(CreateTestImage), PixelTypes.Rgb24 | PixelTypes.Rgba32)]
public void LoadAndStretchCorners_WithOffset<TPixel>(TestImageProvider<TPixel> provider) public void LoadAndStretchCorners_WithOffset<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> s = provider.GetImage()) using Image<TPixel> s = provider.GetImage();
{
var d = default(GenericBlock8x8<TPixel>); var d = default(GenericBlock8x8<TPixel>);
d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7); d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7);
@ -94,7 +91,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.Equal(s[9, 9], d[4, 3]); Assert.Equal(s[9, 9], d[4, 3]);
Assert.Equal(s[9, 9], d[7, 7]); Assert.Equal(s[9, 9], d[7, 7]);
} }
}
[Fact] [Fact]
public void Indexer() public void Indexer()

4
tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs

@ -20,8 +20,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
return; return;
} }
using (Image<TPixel> image = provider.GetImage(JpegDecoder)) using Image<TPixel> image = provider.GetImage(JpegDecoder);
{
image.DebugSave(provider); image.DebugSave(provider);
provider.Utility.TestName = DecodeBaselineJpegOutputName; provider.Utility.TestName = DecodeBaselineJpegOutputName;
@ -30,7 +29,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
provider, provider,
appendPixelTypeToFileName: false); appendPixelTypeToFileName: false);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(UnrecoverableTestJpegs), PixelTypes.Rgba32)] [WithFileCollection(nameof(UnrecoverableTestJpegs), PixelTypes.Rgba32)]

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

@ -79,26 +79,21 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new JpegDecoder(); var decoder = new JpegDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new JpegDecoder(); var decoder = new JpegDecoder();
IImageInfo image = decoder.Identify(Configuration.Default, stream); IImageInfo image = decoder.Identify(Configuration.Default, stream);
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
@ -106,50 +101,41 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
[Theory] [Theory]
[MemberData(nameof(QualityFiles))] [MemberData(nameof(QualityFiles))]
public void Identify_VerifyQuality(string imagePath, int quality) public void Identify_VerifyQuality(string imagePath, int quality)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new JpegDecoder(); var decoder = new JpegDecoder();
IImageInfo image = decoder.Identify(Configuration.Default, stream); IImageInfo image = decoder.Identify(Configuration.Default, stream);
JpegMetadata meta = image.Metadata.GetJpegMetadata(); JpegMetadata meta = image.Metadata.GetJpegMetadata();
Assert.Equal(quality, meta.Quality); Assert.Equal(quality, meta.Quality);
} }
}
[Theory] [Theory]
[MemberData(nameof(QualityFiles))] [MemberData(nameof(QualityFiles))]
public void Decode_VerifyQuality(string imagePath, int quality) public void Decode_VerifyQuality(string imagePath, int quality)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new JpegDecoder(); var decoder = new JpegDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
JpegMetadata meta = image.Metadata.GetJpegMetadata(); JpegMetadata meta = image.Metadata.GetJpegMetadata();
Assert.Equal(quality, meta.Quality); Assert.Equal(quality, meta.Quality);
} }
}
}
private static void TestImageInfo(string imagePath, IImageDecoder decoder, bool useIdentify, Action<IImageInfo> test) private static void TestImageInfo(string imagePath, IImageDecoder decoder, bool useIdentify, Action<IImageInfo> test)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
IImageInfo imageInfo = useIdentify IImageInfo imageInfo = useIdentify
? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream) ? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream)
: decoder.Decode<Rgba32>(Configuration.Default, stream); : decoder.Decode<Rgba32>(Configuration.Default, stream);
test(imageInfo); test(imageInfo);
} }
}
private static void TestMetadataImpl( private static void TestMetadataImpl(
bool useIdentify, bool useIdentify,
@ -215,8 +201,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
// Snake.jpg has both Exif and ICC profiles defined: // Snake.jpg has both Exif and ICC profiles defined:
var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Snake); var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Snake);
using (Image<Rgba32> image = testFile.CreateRgba32Image(decoder)) using Image<Rgba32> image = testFile.CreateRgba32Image(decoder);
{
if (ignoreMetadata) if (ignoreMetadata)
{ {
Assert.Null(image.Metadata.ExifProfile); Assert.Null(image.Metadata.ExifProfile);
@ -228,7 +213,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.NotNull(image.Metadata.IccProfile); Assert.NotNull(image.Metadata.IccProfile);
} }
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]

4
tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs

@ -22,8 +22,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
return; return;
} }
using (Image<TPixel> image = provider.GetImage(JpegDecoder)) using Image<TPixel> image = provider.GetImage(JpegDecoder);
{
image.DebugSave(provider); image.DebugSave(provider);
provider.Utility.TestName = DecodeProgressiveJpegOutputName; provider.Utility.TestName = DecodeProgressiveJpegOutputName;
@ -34,4 +33,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}

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

@ -69,8 +69,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
public void ParseStream_BasicPropertiesAreCorrect() public void ParseStream_BasicPropertiesAreCorrect()
{ {
byte[] bytes = TestFile.Create(TestImages.Jpeg.Progressive.Progress).Bytes; byte[] bytes = TestFile.Create(TestImages.Jpeg.Progressive.Progress).Bytes;
using (var ms = new MemoryStream(bytes)) using var ms = new MemoryStream(bytes);
{
var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder());
decoder.ParseStream(ms); decoder.ParseStream(ms);
@ -79,7 +78,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
// VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31); // VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31);
VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31); VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31);
} }
}
public const string DecodeBaselineJpegOutputName = "DecodeBaselineJpeg"; public const string DecodeBaselineJpegOutputName = "DecodeBaselineJpeg";
@ -128,10 +126,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var comparer = ImageComparer.Tolerant(0, 0); var comparer = ImageComparer.Tolerant(0, 0);
using (Image<TPixel> expectedImage = provider.GetReferenceOutputImage<TPixel>(appendPixelTypeToFileName: false)) using Image<TPixel> expectedImage = provider.GetReferenceOutputImage<TPixel>(appendPixelTypeToFileName: false);
using (var pdfJsOriginalResult = Image.Load<Rgba32>(pdfJsOriginalResultPath)) using var pdfJsOriginalResult = Image.Load<Rgba32>(pdfJsOriginalResultPath);
using (var pdfJsPortResult = Image.Load<Rgba32>(sourceBytes, JpegDecoder)) using var pdfJsPortResult = Image.Load<Rgba32>(sourceBytes, JpegDecoder);
{
ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult); ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult);
ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult); ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult);
@ -140,4 +137,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}

45
tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs

@ -47,21 +47,15 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var options = new JpegEncoder(); var options = new JpegEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
JpegMetadata meta = output.Metadata.GetJpegMetadata(); JpegMetadata meta = output.Metadata.GetJpegMetadata();
Assert.Equal(quality, meta.Quality); Assert.Equal(quality, meta.Quality);
} }
}
}
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, nameof(BitsPerPixel_Quality), PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, nameof(BitsPerPixel_Quality), PixelTypes.Rgba32)]
@ -108,8 +102,8 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
int quality = 100) int quality = 100)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
// There is no alpha in Jpeg! // There is no alpha in Jpeg!
image.Mutate(c => c.MakeOpaque()); image.Mutate(c => c.MakeOpaque());
@ -124,7 +118,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
// Does DebugSave & load reference CompareToReferenceInput(): // Does DebugSave & load reference CompareToReferenceInput():
image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png"); image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png");
} }
}
[Fact] [Fact]
public void Quality_0_And_1_Are_Identical() public void Quality_0_And_1_Are_Identical()
@ -136,10 +129,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
using (var memStream0 = new MemoryStream()) using var memStream0 = new MemoryStream();
using (var memStream1 = new MemoryStream()) using var memStream1 = new MemoryStream();
{
input.SaveAsJpeg(memStream0, options); input.SaveAsJpeg(memStream0, options);
options.Quality = 1; options.Quality = 1;
@ -147,7 +139,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.Equal(memStream0.ToArray(), memStream1.ToArray()); Assert.Equal(memStream0.ToArray(), memStream1.ToArray());
} }
}
[Fact] [Fact]
public void Quality_0_And_100_Are_Not_Identical() public void Quality_0_And_100_Are_Not_Identical()
@ -159,10 +150,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
using (var memStream0 = new MemoryStream()) using var memStream0 = new MemoryStream();
using (var memStream1 = new MemoryStream()) using var memStream1 = new MemoryStream();
{
input.SaveAsJpeg(memStream0, options); input.SaveAsJpeg(memStream0, options);
options.Quality = 100; options.Quality = 100;
@ -170,7 +160,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray()); Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray());
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
@ -179,15 +168,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var options = new JpegEncoder(); var options = new JpegEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
ImageMetadata meta = output.Metadata; ImageMetadata meta = output.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
@ -195,6 +181,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}
}
}

26
tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs

@ -34,11 +34,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
private static void SaveBuffer<TPixel>(JpegComponentPostProcessor cp, TestImageProvider<TPixel> provider) private static void SaveBuffer<TPixel>(JpegComponentPostProcessor cp, TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<Rgba32> image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f)) using Image<Rgba32> image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f);
{
image.DebugSave(provider, $"-C{cp.Component.Index}-"); image.DebugSave(provider, $"-C{cp.Component.Index}-");
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Baseline.Calliphora, PixelTypes.Rgba32)] [WithFile(TestImages.Jpeg.Baseline.Calliphora, PixelTypes.Rgba32)]
@ -47,10 +45,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
string imageFile = provider.SourceFileOrDescription; string imageFile = provider.SourceFileOrDescription;
using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile);
using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) using var pp = new JpegImagePostProcessor(Configuration.Default, decoder);
using (var imageFrame = new ImageFrame<Rgba32>(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight)) using var imageFrame = new ImageFrame<Rgba32>(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight);
{
pp.DoPostProcessorStep(imageFrame); pp.DoPostProcessorStep(imageFrame);
JpegComponentPostProcessor[] cp = pp.ComponentProcessors; JpegComponentPostProcessor[] cp = pp.ComponentProcessors;
@ -59,7 +56,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
SaveBuffer(cp[1], provider); SaveBuffer(cp[1], provider);
SaveBuffer(cp[2], provider); SaveBuffer(cp[2], provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(BaselineTestJpegs), PixelTypes.Rgba32)] [WithFileCollection(nameof(BaselineTestJpegs), PixelTypes.Rgba32)]
@ -67,10 +63,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
string imageFile = provider.SourceFileOrDescription; string imageFile = provider.SourceFileOrDescription;
using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile);
using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) using var pp = new JpegImagePostProcessor(Configuration.Default, decoder);
using (var image = new Image<Rgba32>(decoder.ImageWidth, decoder.ImageHeight)) using var image = new Image<Rgba32>(decoder.ImageWidth, decoder.ImageHeight);
{
pp.PostProcess(image.Frames.RootFrame); pp.PostProcess(image.Frames.RootFrame);
image.DebugSave(provider); image.DebugSave(provider);
@ -79,9 +74,8 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
testUtil.TestGroupName = nameof(JpegDecoderTests); testUtil.TestGroupName = nameof(JpegDecoderTests);
testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName; testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName;
using (Image<TPixel> referenceImage = using Image<TPixel> referenceImage =
provider.GetReferenceOutputImage<TPixel>(appendPixelTypeToFileName: false)) provider.GetReferenceOutputImage<TPixel>(appendPixelTypeToFileName: false);
{
ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image); ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image);
this.Output.WriteLine($"*** {imageFile} ***"); this.Output.WriteLine($"*** {imageFile} ***");
@ -92,5 +86,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}
}

12
tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs

@ -32,17 +32,14 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
{ {
var expectedColorSpace = (JpegColorSpace)expectedColorSpaceValue; var expectedColorSpace = (JpegColorSpace)expectedColorSpaceValue;
using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile);
{
Assert.Equal(expectedColorSpace, decoder.ColorSpace); Assert.Equal(expectedColorSpace, decoder.ColorSpace);
} }
}
[Fact] [Fact]
public void ComponentScalingIsCorrect_1ChannelJpeg() public void ComponentScalingIsCorrect_1ChannelJpeg()
{ {
using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400)) using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400);
{
Assert.Equal(1, decoder.ComponentCount); Assert.Equal(1, decoder.ComponentCount);
Assert.Equal(1, decoder.Components.Length); Assert.Equal(1, decoder.Components.Length);
@ -54,7 +51,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
JpegComponent c0 = decoder.Components[0]; JpegComponent c0 = decoder.Components[0];
VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1); VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1);
} }
}
[Theory] [Theory]
[InlineData(TestImages.Jpeg.Baseline.Jpeg444)] [InlineData(TestImages.Jpeg.Baseline.Jpeg444)]
@ -104,8 +100,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
var fLuma = (Size)expectedLumaFactors; var fLuma = (Size)expectedLumaFactors;
var fChroma = (Size)expectedChromaFactors; var fChroma = (Size)expectedChromaFactors;
using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile);
{
Assert.Equal(componentCount, decoder.ComponentCount); Assert.Equal(componentCount, decoder.ComponentCount);
Assert.Equal(componentCount, decoder.Components.Length); Assert.Equal(componentCount, decoder.Components.Length);
@ -133,4 +128,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
} }
} }
} }
}

8
tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs

@ -50,14 +50,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes; byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes;
using (var ms = new MemoryStream(sourceBytes)) using var ms = new MemoryStream(sourceBytes);
{
decoder.ParseStream(ms); decoder.ParseStream(ms);
var data = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); var data = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder);
VerifyJpeg.SaveSpectralImage(provider, data); VerifyJpeg.SaveSpectralImage(provider, data);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(AllTestJpegs), PixelTypes.Rgba32)] [WithFileCollection(nameof(AllTestJpegs), PixelTypes.Rgba32)]
@ -73,14 +71,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg
byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes; byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes;
using (var ms = new MemoryStream(sourceBytes)) using var ms = new MemoryStream(sourceBytes);
{
decoder.ParseStream(ms); decoder.ParseStream(ms);
var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder);
this.VerifySpectralCorrectnessImpl(provider, imageSharpData); this.VerifySpectralCorrectnessImpl(provider, imageSharpData);
} }
}
private void VerifySpectralCorrectnessImpl<TPixel>( private void VerifySpectralCorrectnessImpl<TPixel>(
TestImageProvider<TPixel> provider, TestImageProvider<TPixel> provider,

4
tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs

@ -192,12 +192,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils
internal static JpegDecoderCore ParseJpegStream(string testFileName, bool metaDataOnly = false) internal static JpegDecoderCore ParseJpegStream(string testFileName, bool metaDataOnly = false)
{ {
byte[] bytes = TestFile.Create(testFileName).Bytes; byte[] bytes = TestFile.Create(testFileName).Bytes;
using (var ms = new MemoryStream(bytes)) using var ms = new MemoryStream(bytes);
{
var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder());
decoder.ParseStream(ms, metaDataOnly); decoder.ParseStream(ms, metaDataOnly);
return decoder; return decoder;
} }
} }
} }
}

6
tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs

@ -98,9 +98,8 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils
{ {
RunDumpJpegCoeffsTool(testFile.FullPath, coeffFileFullPath); RunDumpJpegCoeffsTool(testFile.FullPath, coeffFileFullPath);
using (var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open)) using var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open);
using (var rdr = new BinaryReader(dumpStream)) using var rdr = new BinaryReader(dumpStream);
{
int componentCount = rdr.ReadInt16(); int componentCount = rdr.ReadInt16();
var result = new ComponentData[componentCount]; var result = new ComponentData[componentCount];
@ -132,7 +131,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils
return new SpectralData(result); return new SpectralData(result);
} }
}
finally finally
{ {
if (File.Exists(coeffFileFullPath)) if (File.Exists(coeffFileFullPath))

4
tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs

@ -59,12 +59,10 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils
output?.WriteLine("Min: " + comp.MinVal); output?.WriteLine("Min: " + comp.MinVal);
output?.WriteLine("Max: " + comp.MaxVal); output?.WriteLine("Max: " + comp.MaxVal);
using (Image<Rgba32> image = comp.CreateGrayScaleImage()) using Image<Rgba32> image = comp.CreateGrayScaleImage();
{
string details = $"C{comp.Index}"; string details = $"C{comp.Index}";
image.DebugSave(provider, details, appendPixelTypeToFileName: false); image.DebugSave(provider, details, appendPixelTypeToFileName: false);
} }
}
Image<Rgba32> fullImage = data.TryCreateRGBSpectralImage(); Image<Rgba32> fullImage = data.TryCreateRGBSpectralImage();

4
tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs

@ -63,8 +63,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
{ {
string chunkName = GetChunkTypeName(chunkType); string chunkName = GetChunkTypeName(chunkType);
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
WriteHeaderChunk(memStream); WriteHeaderChunk(memStream);
WriteChunk(memStream, chunkName); WriteChunk(memStream, chunkName);
WriteDataChunk(memStream); WriteDataChunk(memStream);
@ -76,7 +75,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.Equal($"CRC Error. PNG {chunkName} chunk is corrupt!", exception.Message); Assert.Equal($"CRC Error. PNG {chunkName} chunk is corrupt!", exception.Message);
} }
}
private static string GetChunkTypeName(uint value) private static string GetChunkTypeName(uint value)
{ {

44
tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs

@ -87,8 +87,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
public void Decode<TPixel>(TestImageProvider<TPixel> provider) public void Decode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
// We don't have another x-plat reference decoder that can be compared for this image. // We don't have another x-plat reference decoder that can be compared for this image.
@ -104,103 +103,86 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Interlaced, PixelTypes.Rgba32)] [WithFile(TestImages.Png.Interlaced, PixelTypes.Rgba32)]
public void Decode_Interlaced_ImageIsCorrect<TPixel>(TestImageProvider<TPixel> provider) public void Decode_Interlaced_ImageIsCorrect<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImages48Bpp), PixelTypes.Rgb48)] [WithFileCollection(nameof(TestImages48Bpp), PixelTypes.Rgb48)]
public void Decode_48Bpp<TPixel>(TestImageProvider<TPixel> provider) public void Decode_48Bpp<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImages64Bpp), PixelTypes.Rgba64)] [WithFileCollection(nameof(TestImages64Bpp), PixelTypes.Rgba64)]
public void Decode_64Bpp<TPixel>(TestImageProvider<TPixel> provider) public void Decode_64Bpp<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImagesL8BitInterlaced), PixelTypes.Rgba32)] [WithFileCollection(nameof(TestImagesL8BitInterlaced), PixelTypes.Rgba32)]
public void Decoder_L8bitInterlaced<TPixel>(TestImageProvider<TPixel> provider) public void Decoder_L8bitInterlaced<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImagesL16Bit), PixelTypes.Rgb48)] [WithFileCollection(nameof(TestImagesL16Bit), PixelTypes.Rgb48)]
public void Decode_L16Bit<TPixel>(TestImageProvider<TPixel> provider) public void Decode_L16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImagesGrayAlpha16Bit), PixelTypes.Rgba64)] [WithFileCollection(nameof(TestImagesGrayAlpha16Bit), PixelTypes.Rgba64)]
public void Decode_GrayAlpha16Bit<TPixel>(TestImageProvider<TPixel> provider) public void Decode_GrayAlpha16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.GrayA8BitInterlaced, PixelTypes)] [WithFile(TestImages.Png.GrayA8BitInterlaced, PixelTypes)]
public void Decoder_CanDecodeGrey8bitWithAlpha<TPixel>(TestImageProvider<TPixel> provider) public void Decoder_CanDecodeGrey8bitWithAlpha<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Splash, PixelTypes)] [WithFile(TestImages.Png.Splash, PixelTypes)]
public void Decoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void Decoder_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
[Theory] [Theory]
[InlineData(TestImages.Png.Bpp1, 1)] [InlineData(TestImages.Png.Bpp1, 1)]
@ -213,11 +195,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
public void Identify(string imagePath, int expectedPixelSize) public void Identify(string imagePath, int expectedPixelSize)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImagesIssue1014), PixelTypes.Rgba32)] [WithFileCollection(nameof(TestImagesIssue1014), PixelTypes.Rgba32)]
@ -227,11 +207,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
System.Exception ex = Record.Exception( System.Exception ex = Record.Exception(
() => () =>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
}
}); });
Assert.Null(ex); Assert.Null(ex);
} }

52
tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs

@ -230,9 +230,8 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
public void WritesFileMarker<TPixel>(TestImageProvider<TPixel> provider) public void WritesFileMarker<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (var ms = new MemoryStream()) using var ms = new MemoryStream();
{
image.Save(ms, new PngEncoder()); image.Save(ms, new PngEncoder());
byte[] data = ms.ToArray().Take(8).ToArray(); byte[] data = ms.ToArray().Take(8).ToArray();
@ -250,7 +249,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.Equal(expected, data); Assert.Equal(expected, data);
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
@ -259,23 +257,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
var options = new PngEncoder(); var options = new PngEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
ImageMetadata meta = output.Metadata; ImageMetadata meta = output.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
}
[Theory] [Theory]
[MemberData(nameof(PngBitDepthFiles))] [MemberData(nameof(PngBitDepthFiles))]
@ -284,22 +276,16 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
var options = new PngEncoder(); var options = new PngEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
PngMetadata meta = output.Metadata.GetPngMetadata(); PngMetadata meta = output.Metadata.GetPngMetadata();
Assert.Equal(pngBitDepth, meta.BitDepth); Assert.Equal(pngBitDepth, meta.BitDepth);
} }
}
}
}
[Theory] [Theory]
[MemberData(nameof(PngTrnsFiles))] [MemberData(nameof(PngTrnsFiles))]
@ -308,17 +294,14 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
var options = new PngEncoder(); var options = new PngEncoder();
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{
PngMetadata inMeta = input.Metadata.GetPngMetadata(); PngMetadata inMeta = input.Metadata.GetPngMetadata();
Assert.True(inMeta.HasTransparency); Assert.True(inMeta.HasTransparency);
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
PngMetadata outMeta = output.Metadata.GetPngMetadata(); PngMetadata outMeta = output.Metadata.GetPngMetadata();
Assert.True(outMeta.HasTransparency); Assert.True(outMeta.HasTransparency);
@ -352,9 +335,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
break; break;
} }
} }
}
}
}
private static void TestPngEncoderCore<TPixel>( private static void TestPngEncoderCore<TPixel>(
TestImageProvider<TPixel> provider, TestImageProvider<TPixel> provider,
@ -372,8 +352,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
bool appendPngBitDepth = false) bool appendPngBitDepth = false)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new PngEncoder var encoder = new PngEncoder
{ {
ColorType = pngColorType, ColorType = pngColorType,
@ -401,12 +380,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
// We compare using both our decoder and the reference decoder as pixel transformation // We compare using both our decoder and the reference decoder as pixel transformation
// occurs within the encoder itself leaving the input image unaffected. // occurs within the encoder itself leaving the input image unaffected.
// This means we are benefiting from testing our decoder also. // This means we are benefiting from testing our decoder also.
using (var imageSharpImage = Image.Load<TPixel>(actualOutputFile, new PngDecoder())) using var imageSharpImage = Image.Load<TPixel>(actualOutputFile, new PngDecoder());
using (var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder)) using var referenceImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder);
{
ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage); ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage);
} }
} }
} }
}
}

49
tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs

@ -53,8 +53,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
public void Decoder_CanReadTextData<TPixel>(TestImageProvider<TPixel> provider) public void Decoder_CanReadTextData<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.Contains(meta.TextData, m => m.Keyword.Equals("Comment") && m.Value.Equals("comment")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("Comment") && m.Value.Equals("comment"));
Assert.Contains(meta.TextData, m => m.Keyword.Equals("Author") && m.Value.Equals("ImageSharp")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("Author") && m.Value.Equals("ImageSharp"));
@ -68,7 +67,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoLang") && m.Value.Equals("this text chunk is missing a language tag")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoLang") && m.Value.Equals("this text chunk is missing a language tag"));
Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoTranslatedKeyword") && m.Value.Equals("dieser chunk hat kein übersetztes Schlüßelwort")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoTranslatedKeyword") && m.Value.Equals("dieser chunk hat kein übersetztes Schlüßelwort"));
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.PngWithMetadata, PixelTypes.Rgba32)] [WithFile(TestImages.Png.PngWithMetadata, PixelTypes.Rgba32)]
@ -76,14 +74,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
var decoder = new PngDecoder(); var decoder = new PngDecoder();
using (Image<TPixel> input = provider.GetImage(decoder)) using Image<TPixel> input = provider.GetImage(decoder);
using (var memoryStream = new MemoryStream()) using var memoryStream = new MemoryStream();
{
input.Save(memoryStream, new PngEncoder()); input.Save(memoryStream, new PngEncoder());
memoryStream.Position = 0; memoryStream.Position = 0;
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream);
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.Contains(meta.TextData, m => m.Keyword.Equals("Comment") && m.Value.Equals("comment")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("Comment") && m.Value.Equals("comment"));
Assert.Contains(meta.TextData, m => m.Keyword.Equals("Author") && m.Value.Equals("ImageSharp")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("Author") && m.Value.Equals("ImageSharp"));
@ -97,16 +93,13 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoLang") && m.Value.Equals("this text chunk is missing a language tag")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoLang") && m.Value.Equals("this text chunk is missing a language tag"));
Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoTranslatedKeyword") && m.Value.Equals("dieser chunk hat kein übersetztes Schlüßelwort")); Assert.Contains(meta.TextData, m => m.Keyword.Equals("NoTranslatedKeyword") && m.Value.Equals("dieser chunk hat kein übersetztes Schlüßelwort"));
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Png.InvalidTextData, PixelTypes.Rgba32)] [WithFile(TestImages.Png.InvalidTextData, PixelTypes.Rgba32)]
public void Decoder_IgnoresInvalidTextData<TPixel>(TestImageProvider<TPixel> provider) public void Decoder_IgnoresInvalidTextData<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new PngDecoder())) using Image<TPixel> image = provider.GetImage(new PngDecoder());
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("leading space")); Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("leading space"));
Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("trailing space")); Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("trailing space"));
@ -115,7 +108,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters")); Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters"));
Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large")); Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large"));
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.PngWithMetadata, PixelTypes.Rgba32)] [WithFile(TestImages.Png.PngWithMetadata, PixelTypes.Rgba32)]
@ -123,9 +115,9 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
var decoder = new PngDecoder(); var decoder = new PngDecoder();
using (Image<TPixel> input = provider.GetImage(decoder)) using Image<TPixel> input = provider.GetImage(decoder);
using (var memoryStream = new MemoryStream()) using var memoryStream = new MemoryStream();
{
// This will be a zTXt chunk. // This will be a zTXt chunk.
var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty); var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty);
@ -140,14 +132,11 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
}); });
memoryStream.Position = 0; memoryStream.Position = 0;
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, memoryStream);
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.Contains(meta.TextData, m => m.Equals(expectedText)); Assert.Contains(meta.TextData, m => m.Equals(expectedText));
Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin)); Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin));
} }
}
}
[Fact] [Fact]
public void Decode_IgnoreMetadataIsFalse_TextChunkIsRead() public void Decode_IgnoreMetadataIsFalse_TextChunkIsRead()
@ -159,8 +148,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
var testFile = TestFile.Create(TestImages.Png.Blur); var testFile = TestFile.Create(TestImages.Png.Blur);
using (Image<Rgba32> image = testFile.CreateRgba32Image(options)) using Image<Rgba32> image = testFile.CreateRgba32Image(options);
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.Equal(1, meta.TextData.Count); Assert.Equal(1, meta.TextData.Count);
@ -168,7 +156,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value); Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value);
Assert.Equal(0.4545d, meta.Gamma, precision: 4); Assert.Equal(0.4545d, meta.Gamma, precision: 4);
} }
}
[Fact] [Fact]
public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored() public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored()
@ -180,38 +167,31 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
var testFile = TestFile.Create(TestImages.Png.Blur); var testFile = TestFile.Create(TestImages.Png.Blur);
using (Image<Rgba32> image = testFile.CreateRgba32Image(options)) using Image<Rgba32> image = testFile.CreateRgba32Image(options);
{
PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
Assert.Equal(0, meta.TextData.Count); Assert.Equal(0, meta.TextData.Count);
} }
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new PngDecoder(); var decoder = new PngDecoder();
using (Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream)) using Image<Rgba32> image = decoder.Decode<Rgba32>(Configuration.Default, stream);
{
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(xResolution, meta.HorizontalResolution);
Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(yResolution, meta.VerticalResolution);
Assert.Equal(resolutionUnit, meta.ResolutionUnits); Assert.Equal(resolutionUnit, meta.ResolutionUnits);
} }
}
}
[Theory] [Theory]
[MemberData(nameof(RatioFiles))] [MemberData(nameof(RatioFiles))]
public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
{ {
var testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (var stream = new MemoryStream(testFile.Bytes, false)) using var stream = new MemoryStream(testFile.Bytes, false);
{
var decoder = new PngDecoder(); var decoder = new PngDecoder();
IImageInfo image = decoder.Identify(Configuration.Default, stream); IImageInfo image = decoder.Identify(Configuration.Default, stream);
ImageMetadata meta = image.Metadata; ImageMetadata meta = image.Metadata;
@ -221,4 +201,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
} }
} }
} }
}

22
tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs

@ -18,20 +18,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
// does saving a file then reopening mean both files are identical??? // does saving a file then reopening mean both files are identical???
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (var ms = new MemoryStream()) using var ms = new MemoryStream();
{
// image.Save(provider.Utility.GetTestOutputFileName("bmp")); // image.Save(provider.Utility.GetTestOutputFileName("bmp"));
image.Save(ms, new PngEncoder()); image.Save(ms, new PngEncoder());
ms.Position = 0; ms.Position = 0;
using (var img2 = Image.Load<Rgba32>(ms, new PngDecoder())) using var img2 = Image.Load<Rgba32>(ms, new PngDecoder());
{
ImageComparer.Tolerant().VerifySimilarity(image, img2); ImageComparer.Tolerant().VerifySimilarity(image, img2);
// img2.Save(provider.Utility.GetTestOutputFileName("bmp", "_loaded"), new BmpEncoder()); // img2.Save(provider.Utility.GetTestOutputFileName("bmp", "_loaded"), new BmpEncoder());
} }
}
}
/* JJS: Disabled for now as the decoder now correctly decodes the full pixel components if the /* JJS: Disabled for now as the decoder now correctly decodes the full pixel components if the
paletted image has alpha of 0 paletted image has alpha of 0
@ -103,20 +100,17 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
// does saving a file then reopening mean both files are identical??? // does saving a file then reopening mean both files are identical???
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (var ms = new MemoryStream()) using var ms = new MemoryStream();
{
// image.Save(provider.Utility.GetTestOutputFileName("png")); // image.Save(provider.Utility.GetTestOutputFileName("png"));
image.Mutate(x => x.Resize(100, 100)); image.Mutate(x => x.Resize(100, 100));
// image.Save(provider.Utility.GetTestOutputFileName("png", "resize")); // image.Save(provider.Utility.GetTestOutputFileName("png", "resize"));
image.Save(ms, new PngEncoder()); image.Save(ms, new PngEncoder());
ms.Position = 0; ms.Position = 0;
using (var img2 = Image.Load<Rgba32>(ms, new PngDecoder())) using var img2 = Image.Load<Rgba32>(ms, new PngDecoder());
{
ImageComparer.Tolerant().VerifySimilarity(image, img2); ImageComparer.Tolerant().VerifySimilarity(image, img2);
} }
} }
} }
}
}

60
tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs

@ -18,179 +18,149 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
public void TgaDecoder_CanDecode_Uncompressed_MonoChrome<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Uncompressed_MonoChrome<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit15, PixelTypes.Rgba32)] [WithFile(Bit15, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_Uncompressed_15Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Uncompressed_15Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit15Rle, PixelTypes.Rgba32)] [WithFile(Bit15Rle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_15Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_15Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit16, PixelTypes.Rgba32)] [WithFile(Bit16, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_Uncompressed_16Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Uncompressed_16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit16PalRle, PixelTypes.Rgba32)] [WithFile(Bit16PalRle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_WithPalette_16Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_WithPalette_16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit24, PixelTypes.Rgba32)] [WithFile(Bit24, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_Uncompressed_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Uncompressed_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit24RleTopLeft, PixelTypes.Rgba32)] [WithFile(Bit24RleTopLeft, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_WithTopLeftOrigin_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_WithTopLeftOrigin_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit24TopLeft, PixelTypes.Rgba32)] [WithFile(Bit24TopLeft, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_Palette_WithTopLeftOrigin_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Palette_WithTopLeftOrigin_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit32, PixelTypes.Rgba32)] [WithFile(Bit32, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_Uncompressed_32Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_Uncompressed_32Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(GreyRle, PixelTypes.Rgba32)] [WithFile(GreyRle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_MonoChrome<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_MonoChrome<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit16Rle, PixelTypes.Rgba32)] [WithFile(Bit16Rle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit24Rle, PixelTypes.Rgba32)] [WithFile(Bit24Rle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit32Rle, PixelTypes.Rgba32)] [WithFile(Bit32Rle, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit16Pal, PixelTypes.Rgba32)] [WithFile(Bit16Pal, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_WithPalette_16Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_WithPalette_16Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
}
[Theory] [Theory]
[WithFile(Bit24Pal, PixelTypes.Rgba32)] [WithFile(Bit24Pal, PixelTypes.Rgba32)]
public void TgaDecoder_CanDecode_WithPalette_24Bit<TPixel>(TestImageProvider<TPixel> provider) public void TgaDecoder_CanDecode_WithPalette_24Bit<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage(new TgaDecoder())) using Image<TPixel> image = provider.GetImage(new TgaDecoder());
{
image.DebugSave(provider); image.DebugSave(provider);
TgaTestUtils.CompareWithReferenceDecoder(provider, image); TgaTestUtils.CompareWithReferenceDecoder(provider, image);
} }
} }
} }
}

40
tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs

@ -37,21 +37,15 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
{ {
var options = new TgaEncoder(); var options = new TgaEncoder();
TestFile testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (Image<Rgba32> output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
TgaMetadata meta = output.Metadata.GetTgaMetadata(); TgaMetadata meta = output.Metadata.GetTgaMetadata();
Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel);
} }
}
}
}
[Theory] [Theory]
[MemberData(nameof(TgaBitsPerPixelFiles))] [MemberData(nameof(TgaBitsPerPixelFiles))]
@ -62,21 +56,15 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
Compression = TgaCompression.RunLength Compression = TgaCompression.RunLength
}; };
TestFile testFile = TestFile.Create(imagePath); var testFile = TestFile.Create(imagePath);
using (Image<Rgba32> input = testFile.CreateRgba32Image()) using Image<Rgba32> input = testFile.CreateRgba32Image();
{ using var memStream = new MemoryStream();
using (var memStream = new MemoryStream())
{
input.Save(memStream, options); input.Save(memStream, options);
memStream.Position = 0; memStream.Position = 0;
using (var output = Image.Load<Rgba32>(memStream)) using var output = Image.Load<Rgba32>(memStream);
{
TgaMetadata meta = output.Metadata.GetTgaMetadata(); TgaMetadata meta = output.Metadata.GetTgaMetadata();
Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel);
} }
}
}
}
[Theory] [Theory]
[WithFile(Bit32, PixelTypes.Rgba32)] [WithFile(Bit32, PixelTypes.Rgba32)]
@ -130,20 +118,14 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
float compareTolerance = 0.01f) float compareTolerance = 0.01f)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression };
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
image.Save(memStream, encoder); image.Save(memStream, encoder);
memStream.Position = 0; memStream.Position = 0;
using (var encodedImage = (Image<TPixel>)Image.Load(memStream)) using var encodedImage = (Image<TPixel>)Image.Load(memStream);
{
TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance); TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance);
} }
} }
} }
}
}
}

4
tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs

@ -42,8 +42,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
public static Image<TPixel> DecodeWithMagick<TPixel>(Configuration configuration, FileInfo fileInfo) public static Image<TPixel> DecodeWithMagick<TPixel>(Configuration configuration, FileInfo fileInfo)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (var magickImage = new MagickImage(fileInfo)) using var magickImage = new MagickImage(fileInfo);
{
var result = new Image<TPixel>(configuration, magickImage.Width, magickImage.Height); var result = new Image<TPixel>(configuration, magickImage.Width, magickImage.Height);
Span<TPixel> resultPixels = result.GetPixelSpan(); Span<TPixel> resultPixels = result.GetPixelSpan();
@ -62,4 +61,3 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga
} }
} }
} }
}

6
tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs

@ -297,9 +297,8 @@ namespace SixLabors.ImageSharp.Tests.Helpers
{ {
MemoryAllocator memoryAllocator = Configuration.Default.MemoryAllocator; MemoryAllocator memoryAllocator = Configuration.Default.MemoryAllocator;
using (Buffer2D<Point> expected = memoryAllocator.Allocate2D<Point>(bufferWidth, bufferHeight, AllocationOptions.Clean)) using Buffer2D<Point> expected = memoryAllocator.Allocate2D<Point>(bufferWidth, bufferHeight, AllocationOptions.Clean);
using (Buffer2D<Point> actual = memoryAllocator.Allocate2D<Point>(bufferWidth, bufferHeight, AllocationOptions.Clean)) using Buffer2D<Point> actual = memoryAllocator.Allocate2D<Point>(bufferWidth, bufferHeight, AllocationOptions.Clean);
{
var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight); var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight);
void FillRow(int y, Buffer2D<Point> buffer) void FillRow(int y, Buffer2D<Point> buffer)
@ -334,7 +333,6 @@ namespace SixLabors.ImageSharp.Tests.Helpers
// Assert: // Assert:
TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan()); TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan());
} }
}
[Theory] [Theory]
[InlineData(0, 10)] [InlineData(0, 10)]

4
tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs

@ -19,8 +19,7 @@ namespace SixLabors.ImageSharp.Tests.Helpers
[InlineData(10, 20, 0, 1)] [InlineData(10, 20, 0, 1)]
public void GetMultiRowSpan(int width, int height, int min, int max) public void GetMultiRowSpan(int width, int height, int min, int max)
{ {
using (Buffer2D<int> buffer = Configuration.Default.MemoryAllocator.Allocate2D<int>(width, height)) using Buffer2D<int> buffer = Configuration.Default.MemoryAllocator.Allocate2D<int>(width, height);
{
var rows = new RowInterval(min, max); var rows = new RowInterval(min, max);
Span<int> span = buffer.GetMultiRowSpan(rows); Span<int> span = buffer.GetMultiRowSpan(rows);
@ -33,7 +32,6 @@ namespace SixLabors.ImageSharp.Tests.Helpers
Assert.Equal(span.Length, expectedLength); Assert.Equal(span.Length, expectedLength);
Assert.True(Unsafe.AreSame(ref expected0, ref actual0)); Assert.True(Unsafe.AreSame(ref expected0, ref actual0));
} }
}
[Fact] [Fact]
public void Slice1() public void Slice1()

24
tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs

@ -16,8 +16,7 @@ namespace SixLabors.ImageSharp.Tests.IO
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanReadSingleByteFromOrigin() public void DoubleBufferedStreamReaderCanReadSingleByteFromOrigin()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -27,13 +26,11 @@ namespace SixLabors.ImageSharp.Tests.IO
Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength);
Assert.Equal(1, reader.Position); Assert.Equal(1, reader.Position);
} }
}
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanReadSingleByteFromOffset() public void DoubleBufferedStreamReaderCanReadSingleByteFromOffset()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
const int offset = 5; const int offset = 5;
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -45,13 +42,11 @@ namespace SixLabors.ImageSharp.Tests.IO
Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset); Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset);
Assert.Equal(offset + 1, reader.Position); Assert.Equal(offset + 1, reader.Position);
} }
}
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly() public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -76,13 +71,11 @@ namespace SixLabors.ImageSharp.Tests.IO
} }
} }
} }
}
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanReadMultipleBytesFromOrigin() public void DoubleBufferedStreamReaderCanReadMultipleBytesFromOrigin()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
var buffer = new byte[2]; var buffer = new byte[2];
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -95,13 +88,11 @@ namespace SixLabors.ImageSharp.Tests.IO
Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength);
Assert.Equal(buffer.Length, reader.Position); Assert.Equal(buffer.Length, reader.Position);
} }
}
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
var buffer = new byte[2]; var buffer = new byte[2];
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -130,13 +121,11 @@ namespace SixLabors.ImageSharp.Tests.IO
} }
} }
} }
}
[Fact] [Fact]
public void DoubleBufferedStreamReaderCanSkip() public void DoubleBufferedStreamReaderCanSkip()
{ {
using (MemoryStream stream = this.CreateTestStream()) using MemoryStream stream = this.CreateTestStream();
{
byte[] expected = stream.ToArray(); byte[] expected = stream.ToArray();
var reader = new DoubleBufferedStreamReader(this.allocator, stream); var reader = new DoubleBufferedStreamReader(this.allocator, stream);
@ -162,7 +151,6 @@ namespace SixLabors.ImageSharp.Tests.IO
Assert.Equal(stream.Position, reader.Position); Assert.Equal(stream.Position, reader.Position);
Assert.Equal(expected[position], reader.ReadByte()); Assert.Equal(expected[position], reader.ReadByte());
} }
}
private MemoryStream CreateTestStream() private MemoryStream CreateTestStream()
{ {

24
tests/ImageSharp.Tests/Image/ImageCloneTests.cs

@ -32,9 +32,8 @@ namespace SixLabors.ImageSharp.Tests
[WithTestPatternImage(9, 9, PixelTypes.Rgba32)] [WithTestPatternImage(9, 9, PixelTypes.Rgba32)]
public void CloneAs_ToBgra32(TestImageProvider<Rgba32> provider) public void CloneAs_ToBgra32(TestImageProvider<Rgba32> provider)
{ {
using (Image<Rgba32> image = provider.GetImage()) using Image<Rgba32> image = provider.GetImage();
using (Image<Bgra32> clone = image.CloneAs<Bgra32>()) using Image<Bgra32> clone = image.CloneAs<Bgra32>();
{
for (int y = 0; y < image.Height; y++) for (int y = 0; y < image.Height; y++)
{ {
Span<Rgba32> row = image.GetPixelRowSpan(y); Span<Rgba32> row = image.GetPixelRowSpan(y);
@ -52,15 +51,13 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}
[Theory] [Theory]
[WithTestPatternImage(9, 9, PixelTypes.Rgba32)] [WithTestPatternImage(9, 9, PixelTypes.Rgba32)]
public void CloneAs_ToBgr24(TestImageProvider<Rgba32> provider) public void CloneAs_ToBgr24(TestImageProvider<Rgba32> provider)
{ {
using (Image<Rgba32> image = provider.GetImage()) using Image<Rgba32> image = provider.GetImage();
using (Image<Bgr24> clone = image.CloneAs<Bgr24>()) using Image<Bgr24> clone = image.CloneAs<Bgr24>();
{
for (int y = 0; y < image.Height; y++) for (int y = 0; y < image.Height; y++)
{ {
Span<Rgba32> row = image.GetPixelRowSpan(y); Span<Rgba32> row = image.GetPixelRowSpan(y);
@ -77,15 +74,13 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}
[Theory] [Theory]
[WithTestPatternImage(9, 9, PixelTypes.Rgba32)] [WithTestPatternImage(9, 9, PixelTypes.Rgba32)]
public void CloneAs_ToArgb32(TestImageProvider<Rgba32> provider) public void CloneAs_ToArgb32(TestImageProvider<Rgba32> provider)
{ {
using (Image<Rgba32> image = provider.GetImage()) using Image<Rgba32> image = provider.GetImage();
using (Image<Argb32> clone = image.CloneAs<Argb32>()) using Image<Argb32> clone = image.CloneAs<Argb32>();
{
for (int y = 0; y < image.Height; y++) for (int y = 0; y < image.Height; y++)
{ {
Span<Rgba32> row = image.GetPixelRowSpan(y); Span<Rgba32> row = image.GetPixelRowSpan(y);
@ -103,15 +98,13 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}
[Theory] [Theory]
[WithTestPatternImage(9, 9, PixelTypes.Rgba32)] [WithTestPatternImage(9, 9, PixelTypes.Rgba32)]
public void CloneAs_ToRgb24(TestImageProvider<Rgba32> provider) public void CloneAs_ToRgb24(TestImageProvider<Rgba32> provider)
{ {
using (Image<Rgba32> image = provider.GetImage()) using Image<Rgba32> image = provider.GetImage();
using (Image<Rgb24> clone = image.CloneAs<Rgb24>()) using Image<Rgb24> clone = image.CloneAs<Rgb24>();
{
for (int y = 0; y < image.Height; y++) for (int y = 0; y < image.Height; y++)
{ {
Span<Rgba32> row = image.GetPixelRowSpan(y); Span<Rgba32> row = image.GetPixelRowSpan(y);
@ -130,4 +123,3 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}

16
tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs

@ -192,34 +192,26 @@ namespace SixLabors.ImageSharp.Tests
public void CloneFrame<TPixel>(TestImageProvider<TPixel> provider) public void CloneFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
img.Frames.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); // add a frame anyway img.Frames.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); // add a frame anyway
using (Image<TPixel> cloned = img.Frames.CloneFrame(0)) using Image<TPixel> cloned = img.Frames.CloneFrame(0);
{
Assert.Equal(2, img.Frames.Count); Assert.Equal(2, img.Frames.Count);
cloned.ComparePixelBufferTo(img.GetPixelSpan()); cloned.ComparePixelBufferTo(img.GetPixelSpan());
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(10, 10, PixelTypes.Rgba32)] [WithTestPatternImage(10, 10, PixelTypes.Rgba32)]
public void ExtractFrame<TPixel>(TestImageProvider<TPixel> provider) public void ExtractFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
var sourcePixelData = img.GetPixelSpan().ToArray(); var sourcePixelData = img.GetPixelSpan().ToArray();
img.Frames.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); img.Frames.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10));
using (Image<TPixel> cloned = img.Frames.ExportFrame(0)) using Image<TPixel> cloned = img.Frames.ExportFrame(0);
{
Assert.Equal(1, img.Frames.Count); Assert.Equal(1, img.Frames.Count);
cloned.ComparePixelBufferTo(sourcePixelData); cloned.ComparePixelBufferTo(sourcePixelData);
} }
}
}
[Fact] [Fact]
public void CreateFrame_Default() public void CreateFrame_Default()

31
tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs

@ -148,43 +148,35 @@ namespace SixLabors.ImageSharp.Tests
public void CloneFrame<TPixel>(TestImageProvider<TPixel> provider) public void CloneFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
ImageFrameCollection nonGenericFrameCollection = img.Frames; ImageFrameCollection nonGenericFrameCollection = img.Frames;
nonGenericFrameCollection.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); // add a frame anyway nonGenericFrameCollection.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); // add a frame anyway
using (Image cloned = nonGenericFrameCollection.CloneFrame(0)) using Image cloned = nonGenericFrameCollection.CloneFrame(0);
{
Assert.Equal(2, img.Frames.Count); Assert.Equal(2, img.Frames.Count);
var expectedClone = (Image<TPixel>)cloned; var expectedClone = (Image<TPixel>)cloned;
expectedClone.ComparePixelBufferTo(img.GetPixelSpan()); expectedClone.ComparePixelBufferTo(img.GetPixelSpan());
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(10, 10, PixelTypes.Rgba32)] [WithTestPatternImage(10, 10, PixelTypes.Rgba32)]
public void ExtractFrame<TPixel>(TestImageProvider<TPixel> provider) public void ExtractFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
var sourcePixelData = img.GetPixelSpan().ToArray(); var sourcePixelData = img.GetPixelSpan().ToArray();
ImageFrameCollection nonGenericFrameCollection = img.Frames; ImageFrameCollection nonGenericFrameCollection = img.Frames;
nonGenericFrameCollection.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10)); nonGenericFrameCollection.AddFrame(new ImageFrame<TPixel>(Configuration.Default, 10, 10));
using (Image cloned = nonGenericFrameCollection.ExportFrame(0)) using Image cloned = nonGenericFrameCollection.ExportFrame(0);
{
Assert.Equal(1, img.Frames.Count); Assert.Equal(1, img.Frames.Count);
var expectedClone = (Image<TPixel>)cloned; var expectedClone = (Image<TPixel>)cloned;
expectedClone.ComparePixelBufferTo(sourcePixelData); expectedClone.ComparePixelBufferTo(sourcePixelData);
} }
}
}
[Fact] [Fact]
public void CreateFrame_Default() public void CreateFrame_Default()
@ -270,9 +262,9 @@ namespace SixLabors.ImageSharp.Tests
public void ConstructGif_FromDifferentPixelTypes<TPixel>(TestImageProvider<TPixel> provider) public void ConstructGif_FromDifferentPixelTypes<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image source = provider.GetImage()) using Image source = provider.GetImage();
using (var dest = new Image<TPixel>(source.GetConfiguration(), source.Width, source.Height)) using var dest = new Image<TPixel>(source.GetConfiguration(), source.Width, source.Height);
{
// Giphy.gif has 5 frames // Giphy.gif has 5 frames
ImportFrameAs<Bgra32>(source.Frames, dest.Frames, 0); ImportFrameAs<Bgra32>(source.Frames, dest.Frames, 0);
ImportFrameAs<Argb32>(source.Frames, dest.Frames, 1); ImportFrameAs<Argb32>(source.Frames, dest.Frames, 1);
@ -291,19 +283,14 @@ namespace SixLabors.ImageSharp.Tests
CompareGifMetadata(source.Frames[i], dest.Frames[i]); CompareGifMetadata(source.Frames[i], dest.Frames[i]);
} }
} }
}
private static void ImportFrameAs<TPixel>(ImageFrameCollection source, ImageFrameCollection destination, int index) private static void ImportFrameAs<TPixel>(ImageFrameCollection source, ImageFrameCollection destination, int index)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image temp = source.CloneFrame(index)) using Image temp = source.CloneFrame(index);
{ using Image<TPixel> temp2 = temp.CloneAs<TPixel>();
using (Image<TPixel> temp2 = temp.CloneAs<TPixel>())
{
destination.AddFrame(temp2.Frames.RootFrame); destination.AddFrame(temp2.Frames.RootFrame);
} }
}
}
private static void CompareGifMetadata(ImageFrame a, ImageFrame b) private static void CompareGifMetadata(ImageFrame a, ImageFrame b)
{ {

6
tests/ImageSharp.Tests/Image/ImageRotationTests.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0. // Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats;
@ -48,12 +48,10 @@ namespace SixLabors.ImageSharp.Tests
private static (Size original, Size rotated) Rotate(int angle) private static (Size original, Size rotated) Rotate(int angle)
{ {
var file = TestFile.Create(TestImages.Bmp.Car); var file = TestFile.Create(TestImages.Bmp.Car);
using (var image = Image.Load<Rgba32>(file.FullPath)) using var image = Image.Load<Rgba32>(file.FullPath);
{
Size original = image.Size(); Size original = image.Size();
image.Mutate(x => x.Rotate(angle)); image.Mutate(x => x.Rotate(angle));
return (original, image.Size()); return (original, image.Size());
} }
} }
} }
}

4
tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs

@ -71,12 +71,10 @@ namespace SixLabors.ImageSharp.Tests
[Fact] [Fact]
public void FromStream_GlobalConfiguration() public void FromStream_GlobalConfiguration()
{ {
using (var stream = new MemoryStream(this.ActualImageBytes)) using var stream = new MemoryStream(this.ActualImageBytes);
{
IImageFormat type = Image.DetectFormat(stream); IImageFormat type = Image.DetectFormat(stream);
Assert.Equal(ExpectedGlobalFormat, type); Assert.Equal(ExpectedGlobalFormat, type);
} }
}
[Fact] [Fact]
public void FromStream_CustomConfiguration() public void FromStream_CustomConfiguration()

14
tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0. // Licensed under the Apache License, Version 2.0.
using System; using System;
@ -18,10 +18,9 @@ namespace SixLabors.ImageSharp.Tests
{ {
Rgba32[] data = { Rgba32.Black, Rgba32.White, Rgba32.White, Rgba32.Black, }; Rgba32[] data = { Rgba32.Black, Rgba32.White, Rgba32.White, Rgba32.Black, };
using (Image<Rgba32> img = useSpan using Image<Rgba32> img = useSpan
? Image.LoadPixelData<Rgba32>(data.AsSpan(), 2, 2) ? Image.LoadPixelData<Rgba32>(data.AsSpan(), 2, 2)
: Image.LoadPixelData<Rgba32>(data, 2, 2)) : Image.LoadPixelData<Rgba32>(data, 2, 2);
{
Assert.NotNull(img); Assert.NotNull(img);
Assert.Equal(Rgba32.Black, img[0, 0]); Assert.Equal(Rgba32.Black, img[0, 0]);
Assert.Equal(Rgba32.White, img[0, 1]); Assert.Equal(Rgba32.White, img[0, 1]);
@ -29,7 +28,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(Rgba32.White, img[1, 0]); Assert.Equal(Rgba32.White, img[1, 0]);
Assert.Equal(Rgba32.Black, img[1, 1]); Assert.Equal(Rgba32.Black, img[1, 1]);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
@ -43,10 +41,9 @@ namespace SixLabors.ImageSharp.Tests
255, 255, 255, 255, // 1,0 255, 255, 255, 255, // 1,0
0, 0, 0, 255, // 1,1 0, 0, 0, 255, // 1,1
}; };
using (Image<Rgba32> img = useSpan using Image<Rgba32> img = useSpan
? Image.LoadPixelData<Rgba32>(data.AsSpan(), 2, 2) ? Image.LoadPixelData<Rgba32>(data.AsSpan(), 2, 2)
: Image.LoadPixelData<Rgba32>(data, 2, 2)) : Image.LoadPixelData<Rgba32>(data, 2, 2);
{
Assert.NotNull(img); Assert.NotNull(img);
Assert.Equal(Rgba32.Black, img[0, 0]); Assert.Equal(Rgba32.Black, img[0, 0]);
Assert.Equal(Rgba32.White, img[0, 1]); Assert.Equal(Rgba32.White, img[0, 1]);
@ -57,4 +54,3 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}

24
tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs

@ -26,58 +26,46 @@ namespace SixLabors.ImageSharp.Tests
[Fact] [Fact]
public void Path_Specific() public void Path_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Path)) using var img = Image.Load<Rgba32>(this.Path);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Path_Agnostic() public void Path_Agnostic()
{ {
using (var img = Image.Load(this.Path)) using var img = Image.Load(this.Path);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Path_Decoder_Specific() public void Path_Decoder_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Path, new BmpDecoder())) using var img = Image.Load<Rgba32>(this.Path, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Path_Decoder_Agnostic() public void Path_Decoder_Agnostic()
{ {
using (var img = Image.Load(this.Path, new BmpDecoder())) using var img = Image.Load(this.Path, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Path_OutFormat_Specific() public void Path_OutFormat_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Path, out IImageFormat format)) using var img = Image.Load<Rgba32>(this.Path, out IImageFormat format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
}
[Fact] [Fact]
public void Path_OutFormat_Agnostic() public void Path_OutFormat_Agnostic()
{ {
using (var img = Image.Load(this.Path, out IImageFormat format)) using var img = Image.Load(this.Path, out IImageFormat format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
}
[Fact] [Fact]
public void WhenFileNotFound_Throws() public void WhenFileNotFound_Throws()

24
tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs

@ -30,44 +30,36 @@ namespace SixLabors.ImageSharp.Tests
[InlineData(true)] [InlineData(true)]
public void Bytes_Specific(bool useSpan) public void Bytes_Specific(bool useSpan)
{ {
using (var img = useSpan ? Image.Load<Rgba32>(ByteSpan) : Image.Load<Rgba32>(ByteArray)) using var img = useSpan ? Image.Load<Rgba32>(ByteSpan) : Image.Load<Rgba32>(ByteArray);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
[InlineData(true)] [InlineData(true)]
public void Bytes_Agnostic(bool useSpan) public void Bytes_Agnostic(bool useSpan)
{ {
using (var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray)) using var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
[InlineData(true)] [InlineData(true)]
public void Bytes_Decoder_Specific(bool useSpan) public void Bytes_Decoder_Specific(bool useSpan)
{ {
using (var img = useSpan ? Image.Load<Rgba32>(ByteSpan, new BmpDecoder()) : Image.Load<Rgba32>(ByteArray, new BmpDecoder())) using var img = useSpan ? Image.Load<Rgba32>(ByteSpan, new BmpDecoder()) : Image.Load<Rgba32>(ByteArray, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
[InlineData(true)] [InlineData(true)]
public void Bytes_Decoder_Agnostic(bool useSpan) public void Bytes_Decoder_Agnostic(bool useSpan)
{ {
using (var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder())) using var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
@ -75,12 +67,10 @@ namespace SixLabors.ImageSharp.Tests
public void Bytes_OutFormat_Specific(bool useSpan) public void Bytes_OutFormat_Specific(bool useSpan)
{ {
IImageFormat format; IImageFormat format;
using (var img = useSpan ? Image.Load<Rgba32>(ByteSpan, out format) : Image.Load<Rgba32>(ByteArray, out format)) using var img = useSpan ? Image.Load<Rgba32>(ByteSpan, out format) : Image.Load<Rgba32>(ByteArray, out format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
}
[Theory] [Theory]
[InlineData(false)] [InlineData(false)]
@ -88,12 +78,10 @@ namespace SixLabors.ImageSharp.Tests
public void Bytes_OutFormat_Agnostic(bool useSpan) public void Bytes_OutFormat_Agnostic(bool useSpan)
{ {
IImageFormat format; IImageFormat format;
using (var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format)) using var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
} }
} }
} }
}

24
tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs

@ -29,58 +29,46 @@ namespace SixLabors.ImageSharp.Tests
[Fact] [Fact]
public void Stream_Specific() public void Stream_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Stream)) using var img = Image.Load<Rgba32>(this.Stream);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Stream_Agnostic() public void Stream_Agnostic()
{ {
using (var img = Image.Load(this.Stream)) using var img = Image.Load(this.Stream);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Stream_OutFormat_Specific() public void Stream_OutFormat_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Stream, out IImageFormat format)) using var img = Image.Load<Rgba32>(this.Stream, out IImageFormat format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
}
[Fact] [Fact]
public void Stream_Decoder_Specific() public void Stream_Decoder_Specific()
{ {
using (var img = Image.Load<Rgba32>(this.Stream, new BmpDecoder())) using var img = Image.Load<Rgba32>(this.Stream, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Stream_Decoder_Agnostic() public void Stream_Decoder_Agnostic()
{ {
using (var img = Image.Load(this.Stream, new BmpDecoder())) using var img = Image.Load(this.Stream, new BmpDecoder());
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
} }
}
[Fact] [Fact]
public void Stream_OutFormat_Agnostic() public void Stream_OutFormat_Agnostic()
{ {
using (var img = Image.Load(this.Stream, out IImageFormat format)) using var img = Image.Load(this.Stream, out IImageFormat format);
{
VerifyDecodedImage(img); VerifyDecodedImage(img);
Assert.IsType<BmpFormat>(format); Assert.IsType<BmpFormat>(format);
} }
}
public void Dispose() public void Dispose()
{ {

16
tests/ImageSharp.Tests/Image/ImageTests.Save.cs

@ -45,10 +45,8 @@ namespace SixLabors.ImageSharp.Tests
Assert.Throws<NotSupportedException>( Assert.Throws<NotSupportedException>(
() => () =>
{ {
using (var image = new Image<Rgba32>(10, 10)) using var image = new Image<Rgba32>(10, 10);
{
image.Save(file); image.Save(file);
}
}); });
} }
@ -58,16 +56,12 @@ namespace SixLabors.ImageSharp.Tests
string dir = TestEnvironment.CreateOutputDirectory(nameof(ImageTests)); string dir = TestEnvironment.CreateOutputDirectory(nameof(ImageTests));
string file = System.IO.Path.Combine(dir, "SetEncoding.dat"); string file = System.IO.Path.Combine(dir, "SetEncoding.dat");
using (var image = new Image<Rgba32>(10, 10)) using var image = new Image<Rgba32>(10, 10);
{
image.Save(file, new PngEncoder()); image.Save(file, new PngEncoder());
}
using (Image.Load(file, out var mime)) using var load = Image.Load(file, out var mime);
{
Assert.Equal("image/png", mime.DefaultMimeType); Assert.Equal("image/png", mime.DefaultMimeType);
} }
}
[Fact] [Fact]
public void ThrowsWhenDisposed() public void ThrowsWhenDisposed()
@ -75,11 +69,9 @@ namespace SixLabors.ImageSharp.Tests
var image = new Image<Rgba32>(5, 5); var image = new Image<Rgba32>(5, 5);
image.Dispose(); image.Dispose();
IImageEncoder encoder = Mock.Of<IImageEncoder>(); IImageEncoder encoder = Mock.Of<IImageEncoder>();
using (var stream = new MemoryStream()) using var stream = new MemoryStream();
{
Assert.Throws<ObjectDisposedException>(() => image.Save(stream, encoder)); Assert.Throws<ObjectDisposedException>(() => image.Save(stream, encoder));
} }
} }
} }
} }
}

20
tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs

@ -88,15 +88,13 @@ namespace SixLabors.ImageSharp.Tests
var array = new Rgba32[25]; var array = new Rgba32[25];
var memory = new Memory<Rgba32>(array); var memory = new Memory<Rgba32>(array);
using (var image = Image.WrapMemory(cfg, memory, 5, 5, metaData)) using var image = Image.WrapMemory(cfg, memory, 5, 5, metaData);
{
ref Rgba32 pixel0 = ref image.GetPixelSpan()[0]; ref Rgba32 pixel0 = ref image.GetPixelSpan()[0];
Assert.True(Unsafe.AreSame(ref array[0], ref pixel0)); Assert.True(Unsafe.AreSame(ref array[0], ref pixel0));
Assert.Equal(cfg, image.GetConfiguration()); Assert.Equal(cfg, image.GetConfiguration());
Assert.Equal(metaData, image.Metadata); Assert.Equal(metaData, image.Metadata);
} }
}
[Fact] [Fact]
public void WrapSystemDrawingBitmap_WhenObserved() public void WrapSystemDrawingBitmap_WhenObserved()
@ -106,26 +104,21 @@ namespace SixLabors.ImageSharp.Tests
return; return;
} }
using (var bmp = new Bitmap(51, 23)) using var bmp = new Bitmap(51, 23);
{ using var memoryManager = new BitmapMemoryManager(bmp);
using (var memoryManager = new BitmapMemoryManager(bmp))
{
Memory<Bgra32> memory = memoryManager.Memory; Memory<Bgra32> memory = memoryManager.Memory;
Bgra32 bg = Color.Red; Bgra32 bg = Color.Red;
Bgra32 fg = Color.Green; Bgra32 fg = Color.Green;
using (var image = Image.WrapMemory(memory, bmp.Width, bmp.Height)) using var image = Image.WrapMemory(memory, bmp.Width, bmp.Height);
{
Assert.Equal(memory, image.GetPixelMemory()); Assert.Equal(memory, image.GetPixelMemory());
image.GetPixelSpan().Fill(bg); image.GetPixelSpan().Fill(bg);
for (var i = 10; i < 20; i++) for (var i = 10; i < 20; i++)
{ {
image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg);
} }
}
Assert.False(memoryManager.IsDisposed); Assert.False(memoryManager.IsDisposed);
}
string fn = System.IO.Path.Combine( string fn = System.IO.Path.Combine(
TestEnvironment.ActualOutputDirectoryFullPath, TestEnvironment.ActualOutputDirectoryFullPath,
@ -133,7 +126,6 @@ namespace SixLabors.ImageSharp.Tests
bmp.Save(fn, ImageFormat.Bmp); bmp.Save(fn, ImageFormat.Bmp);
} }
}
[Fact] [Fact]
public void WrapSystemDrawingBitmap_WhenOwned() public void WrapSystemDrawingBitmap_WhenOwned()
@ -143,8 +135,7 @@ namespace SixLabors.ImageSharp.Tests
return; return;
} }
using (var bmp = new Bitmap(51, 23)) using var bmp = new Bitmap(51, 23);
{
var memoryManager = new BitmapMemoryManager(bmp); var memoryManager = new BitmapMemoryManager(bmp);
Bgra32 bg = Color.Red; Bgra32 bg = Color.Red;
Bgra32 fg = Color.Green; Bgra32 fg = Color.Green;
@ -168,7 +159,6 @@ namespace SixLabors.ImageSharp.Tests
bmp.Save(fn, ImageFormat.Bmp); bmp.Save(fn, ImageFormat.Bmp);
} }
}
private static bool ShouldSkipBitmapTest => private static bool ShouldSkipBitmapTest =>
!TestEnvironment.Is64BitProcess || (TestHelpers.ImageSharpBuiltAgainst != "netcoreapp3.1" && TestHelpers.ImageSharpBuiltAgainst != "netcoreapp2.1"); !TestEnvironment.Is64BitProcess || (TestHelpers.ImageSharpBuiltAgainst != "netcoreapp3.1" && TestHelpers.ImageSharpBuiltAgainst != "netcoreapp2.1");

16
tests/ImageSharp.Tests/Image/ImageTests.cs

@ -21,8 +21,7 @@ namespace SixLabors.ImageSharp.Tests
[Fact] [Fact]
public void Width_Height() public void Width_Height()
{ {
using (var image = new Image<Rgba32>(11, 23)) using var image = new Image<Rgba32>(11, 23);
{
Assert.Equal(11, image.Width); Assert.Equal(11, image.Width);
Assert.Equal(23, image.Height); Assert.Equal(23, image.Height);
Assert.Equal(11 * 23, image.GetPixelSpan().Length); Assert.Equal(11 * 23, image.GetPixelSpan().Length);
@ -30,15 +29,13 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(Configuration.Default, image.GetConfiguration()); Assert.Equal(Configuration.Default, image.GetConfiguration());
} }
}
[Fact] [Fact]
public void Configuration_Width_Height() public void Configuration_Width_Height()
{ {
Configuration configuration = Configuration.Default.Clone(); Configuration configuration = Configuration.Default.Clone();
using (var image = new Image<Rgba32>(configuration, 11, 23)) using var image = new Image<Rgba32>(configuration, 11, 23);
{
Assert.Equal(11, image.Width); Assert.Equal(11, image.Width);
Assert.Equal(23, image.Height); Assert.Equal(23, image.Height);
Assert.Equal(11 * 23, image.GetPixelSpan().Length); Assert.Equal(11 * 23, image.GetPixelSpan().Length);
@ -46,7 +43,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(configuration, image.GetConfiguration()); Assert.Equal(configuration, image.GetConfiguration());
} }
}
[Fact] [Fact]
public void Configuration_Width_Height_BackgroundColor() public void Configuration_Width_Height_BackgroundColor()
@ -54,8 +50,7 @@ namespace SixLabors.ImageSharp.Tests
Configuration configuration = Configuration.Default.Clone(); Configuration configuration = Configuration.Default.Clone();
Rgba32 color = Rgba32.Aquamarine; Rgba32 color = Rgba32.Aquamarine;
using (var image = new Image<Rgba32>(configuration, 11, 23, color)) using var image = new Image<Rgba32>(configuration, 11, 23, color);
{
Assert.Equal(11, image.Width); Assert.Equal(11, image.Width);
Assert.Equal(23, image.Height); Assert.Equal(23, image.Height);
Assert.Equal(11 * 23, image.GetPixelSpan().Length); Assert.Equal(11 * 23, image.GetPixelSpan().Length);
@ -63,7 +58,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(configuration, image.GetConfiguration()); Assert.Equal(configuration, image.GetConfiguration());
} }
}
[Fact] [Fact]
public void CreateUninitialized() public void CreateUninitialized()
@ -74,8 +68,7 @@ namespace SixLabors.ImageSharp.Tests
configuration.MemoryAllocator = new TestMemoryAllocator(dirtyValue); configuration.MemoryAllocator = new TestMemoryAllocator(dirtyValue);
var metadata = new ImageMetadata(); var metadata = new ImageMetadata();
using (var image = Image.CreateUninitialized<L8>(configuration, 21, 22, metadata)) using var image = Image.CreateUninitialized<L8>(configuration, 21, 22, metadata);
{
Assert.Equal(21, image.Width); Assert.Equal(21, image.Width);
Assert.Equal(22, image.Height); Assert.Equal(22, image.Height);
Assert.Same(configuration, image.GetConfiguration()); Assert.Same(configuration, image.GetConfiguration());
@ -86,4 +79,3 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}

30
tests/ImageSharp.Tests/Memory/Buffer2DTests.cs

@ -37,26 +37,22 @@ namespace SixLabors.ImageSharp.Tests.Memory
[InlineData(1025, 17)] [InlineData(1025, 17)]
public void Construct(int width, int height) public void Construct(int width, int height)
{ {
using (Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height)) using Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height);
{
Assert.Equal(width, buffer.Width); Assert.Equal(width, buffer.Width);
Assert.Equal(height, buffer.Height); Assert.Equal(height, buffer.Height);
Assert.Equal(width * height, buffer.GetMemory().Length); Assert.Equal(width * height, buffer.GetMemory().Length);
} }
}
[Fact] [Fact]
public void CreateClean() public void CreateClean()
{ {
using (Buffer2D<int> buffer = this.MemoryAllocator.Allocate2D<int>(42, 42, AllocationOptions.Clean)) using Buffer2D<int> buffer = this.MemoryAllocator.Allocate2D<int>(42, 42, AllocationOptions.Clean);
{
Span<int> span = buffer.GetSpan(); Span<int> span = buffer.GetSpan();
for (int j = 0; j < span.Length; j++) for (int j = 0; j < span.Length; j++)
{ {
Assert.Equal(0, span[j]); Assert.Equal(0, span[j]);
} }
} }
}
[Theory] [Theory]
[InlineData(7, 42, 0)] [InlineData(7, 42, 0)]
@ -64,15 +60,13 @@ namespace SixLabors.ImageSharp.Tests.Memory
[InlineData(17, 42, 41)] [InlineData(17, 42, 41)]
public void GetRowSpanY(int width, int height, int y) public void GetRowSpanY(int width, int height, int y)
{ {
using (Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height)) using Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height);
{
Span<TestStructs.Foo> span = buffer.GetRowSpan(y); Span<TestStructs.Foo> span = buffer.GetRowSpan(y);
// Assert.Equal(width * y, span.Start); // Assert.Equal(width * y, span.Start);
Assert.Equal(width, span.Length); Assert.Equal(width, span.Length);
Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y); Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y);
} }
}
[Theory] [Theory]
[InlineData(42, 8, 0, 0)] [InlineData(42, 8, 0, 0)]
@ -80,8 +74,7 @@ namespace SixLabors.ImageSharp.Tests.Memory
[InlineData(99, 88, 98, 87)] [InlineData(99, 88, 98, 87)]
public void Indexer(int width, int height, int x, int y) public void Indexer(int width, int height, int x, int y)
{ {
using (Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height)) using Buffer2D<TestStructs.Foo> buffer = this.MemoryAllocator.Allocate2D<TestStructs.Foo>(width, height);
{
Span<TestStructs.Foo> span = buffer.MemorySource.GetSpan(); Span<TestStructs.Foo> span = buffer.MemorySource.GetSpan();
ref TestStructs.Foo actual = ref buffer[x, y]; ref TestStructs.Foo actual = ref buffer[x, y];
@ -90,14 +83,12 @@ namespace SixLabors.ImageSharp.Tests.Memory
Assert.True(Unsafe.AreSame(ref expected, ref actual)); Assert.True(Unsafe.AreSame(ref expected, ref actual));
} }
}
[Fact] [Fact]
public void SwapOrCopyContent() public void SwapOrCopyContent()
{ {
using (Buffer2D<int> a = this.MemoryAllocator.Allocate2D<int>(10, 5)) using Buffer2D<int> a = this.MemoryAllocator.Allocate2D<int>(10, 5);
using (Buffer2D<int> b = this.MemoryAllocator.Allocate2D<int>(3, 7)) using Buffer2D<int> b = this.MemoryAllocator.Allocate2D<int>(3, 7);
{
IMemoryOwner<int> aa = a.MemorySource.MemoryOwner; IMemoryOwner<int> aa = a.MemorySource.MemoryOwner;
IMemoryOwner<int> bb = b.MemorySource.MemoryOwner; IMemoryOwner<int> bb = b.MemorySource.MemoryOwner;
@ -109,7 +100,6 @@ namespace SixLabors.ImageSharp.Tests.Memory
Assert.Equal(new Size(3, 7), a.Size()); Assert.Equal(new Size(3, 7), a.Size());
Assert.Equal(new Size(10, 5), b.Size()); Assert.Equal(new Size(10, 5), b.Size());
} }
}
[Theory] [Theory]
[InlineData(100, 20, 0, 90, 10)] [InlineData(100, 20, 0, 90, 10)]
@ -121,8 +111,7 @@ namespace SixLabors.ImageSharp.Tests.Memory
public void CopyColumns(int width, int height, int startIndex, int destIndex, int columnCount) public void CopyColumns(int width, int height, int startIndex, int destIndex, int columnCount)
{ {
var rnd = new Random(123); var rnd = new Random(123);
using (Buffer2D<float> b = this.MemoryAllocator.Allocate2D<float>(width, height)) using Buffer2D<float> b = this.MemoryAllocator.Allocate2D<float>(width, height);
{
rnd.RandomFill(b.GetSpan(), 0, 1); rnd.RandomFill(b.GetSpan(), 0, 1);
b.CopyColumns(startIndex, destIndex, columnCount); b.CopyColumns(startIndex, destIndex, columnCount);
@ -137,14 +126,12 @@ namespace SixLabors.ImageSharp.Tests.Memory
Xunit.Assert.True(s.SequenceEqual(d)); Xunit.Assert.True(s.SequenceEqual(d));
} }
} }
}
[Fact] [Fact]
public void CopyColumns_InvokeMultipleTimes() public void CopyColumns_InvokeMultipleTimes()
{ {
var rnd = new Random(123); var rnd = new Random(123);
using (Buffer2D<float> b = this.MemoryAllocator.Allocate2D<float>(100, 100)) using Buffer2D<float> b = this.MemoryAllocator.Allocate2D<float>(100, 100);
{
rnd.RandomFill(b.GetSpan(), 0, 1); rnd.RandomFill(b.GetSpan(), 0, 1);
b.CopyColumns(0, 50, 22); b.CopyColumns(0, 50, 22);
@ -162,4 +149,3 @@ namespace SixLabors.ImageSharp.Tests.Memory
} }
} }
} }
}

28
tests/ImageSharp.Tests/Memory/BufferAreaTests.cs

@ -13,15 +13,13 @@ namespace SixLabors.ImageSharp.Tests.Memory
[Fact] [Fact]
public void Construct() public void Construct()
{ {
using (var buffer = Configuration.Default.MemoryAllocator.Allocate2D<int>(10, 20)) using var buffer = Configuration.Default.MemoryAllocator.Allocate2D<int>(10, 20);
{
var rectangle = new Rectangle(3, 2, 5, 6); var rectangle = new Rectangle(3, 2, 5, 6);
var area = new BufferArea<int>(buffer, rectangle); var area = new BufferArea<int>(buffer, rectangle);
Assert.Equal(buffer, area.DestinationBuffer); Assert.Equal(buffer, area.DestinationBuffer);
Assert.Equal(rectangle, area.Rectangle); Assert.Equal(rectangle, area.Rectangle);
} }
}
private static Buffer2D<int> CreateTestBuffer(int w, int h) private static Buffer2D<int> CreateTestBuffer(int w, int h)
{ {
@ -42,8 +40,7 @@ namespace SixLabors.ImageSharp.Tests.Memory
[InlineData(5, 4, 3, 2)] [InlineData(5, 4, 3, 2)]
public void Indexer(int rx, int ry, int x, int y) public void Indexer(int rx, int ry, int x, int y)
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(20, 30)) using Buffer2D<int> buffer = CreateTestBuffer(20, 30);
{
var r = new Rectangle(rx, ry, 5, 6); var r = new Rectangle(rx, ry, 5, 6);
BufferArea<int> area = buffer.GetArea(r); BufferArea<int> area = buffer.GetArea(r);
@ -52,15 +49,13 @@ namespace SixLabors.ImageSharp.Tests.Memory
int expected = ((ry + y) * 100) + rx + x; int expected = ((ry + y) * 100) + rx + x;
Assert.Equal(expected, value); Assert.Equal(expected, value);
} }
}
[Theory] [Theory]
[InlineData(2, 3, 2, 5, 6)] [InlineData(2, 3, 2, 5, 6)]
[InlineData(5, 4, 3, 6, 5)] [InlineData(5, 4, 3, 6, 5)]
public void GetRowSpan(int rx, int ry, int y, int w, int h) public void GetRowSpan(int rx, int ry, int y, int w, int h)
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(20, 30)) using Buffer2D<int> buffer = CreateTestBuffer(20, 30);
{
var r = new Rectangle(rx, ry, w, h); var r = new Rectangle(rx, ry, w, h);
BufferArea<int> area = buffer.GetArea(r); BufferArea<int> area = buffer.GetArea(r);
@ -77,13 +72,11 @@ namespace SixLabors.ImageSharp.Tests.Memory
Assert.Equal(expected, value); Assert.Equal(expected, value);
} }
} }
}
[Fact] [Fact]
public void GetSubArea() public void GetSubArea()
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(20, 30)) using Buffer2D<int> buffer = CreateTestBuffer(20, 30);
{
BufferArea<int> area0 = buffer.GetArea(6, 8, 10, 10); BufferArea<int> area0 = buffer.GetArea(6, 8, 10, 10);
BufferArea<int> area1 = area0.GetSubArea(4, 4, 5, 5); BufferArea<int> area1 = area0.GetSubArea(4, 4, 5, 5);
@ -96,13 +89,11 @@ namespace SixLabors.ImageSharp.Tests.Memory
int value00 = (12 * 100) + 10; int value00 = (12 * 100) + 10;
Assert.Equal(value00, area1[0, 0]); Assert.Equal(value00, area1[0, 0]);
} }
}
[Fact] [Fact]
public void DangerousGetPinnableReference() public void DangerousGetPinnableReference()
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(20, 30)) using Buffer2D<int> buffer = CreateTestBuffer(20, 30);
{
BufferArea<int> area0 = buffer.GetArea(6, 8, 10, 10); BufferArea<int> area0 = buffer.GetArea(6, 8, 10, 10);
ref int r = ref area0.GetReferenceToOrigin(); ref int r = ref area0.GetReferenceToOrigin();
@ -110,24 +101,20 @@ namespace SixLabors.ImageSharp.Tests.Memory
int expected = buffer[6, 8]; int expected = buffer[6, 8];
Assert.Equal(expected, r); Assert.Equal(expected, r);
} }
}
[Fact] [Fact]
public void Clear_FullArea() public void Clear_FullArea()
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(22, 13)) using Buffer2D<int> buffer = CreateTestBuffer(22, 13);
{
buffer.GetArea().Clear(); buffer.GetArea().Clear();
Span<int> fullSpan = buffer.GetSpan(); Span<int> fullSpan = buffer.GetSpan();
Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length])); Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length]));
} }
}
[Fact] [Fact]
public void Clear_SubArea() public void Clear_SubArea()
{ {
using (Buffer2D<int> buffer = CreateTestBuffer(20, 30)) using Buffer2D<int> buffer = CreateTestBuffer(20, 30);
{
BufferArea<int> area = buffer.GetArea(5, 5, 10, 10); BufferArea<int> area = buffer.GetArea(5, 5, 10, 10);
area.Clear(); area.Clear();
@ -145,4 +132,3 @@ namespace SixLabors.ImageSharp.Tests.Memory
} }
} }
} }
}

4
tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs

@ -91,8 +91,7 @@ namespace SixLabors.ImageSharp.Tests.Metadata
exifProfile.SetValue(ExifTag.XResolution, new Rational(200)); exifProfile.SetValue(ExifTag.XResolution, new Rational(200));
exifProfile.SetValue(ExifTag.YResolution, new Rational(300)); exifProfile.SetValue(ExifTag.YResolution, new Rational(300));
using (var image = new Image<Rgba32>(1, 1)) using var image = new Image<Rgba32>(1, 1);
{
image.Metadata.ExifProfile = exifProfile; image.Metadata.ExifProfile = exifProfile;
image.Metadata.HorizontalResolution = 400; image.Metadata.HorizontalResolution = 400;
image.Metadata.VerticalResolution = 500; image.Metadata.VerticalResolution = 500;
@ -104,4 +103,3 @@ namespace SixLabors.ImageSharp.Tests.Metadata
} }
} }
} }
}

12
tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs

@ -95,8 +95,7 @@ namespace SixLabors.ImageSharp.Tests
[InlineData(TestImageWriteFormat.Png)] [InlineData(TestImageWriteFormat.Png)]
public void WriteFraction(TestImageWriteFormat imageFormat) public void WriteFraction(TestImageWriteFormat imageFormat)
{ {
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
double exposureTime = 1.0 / 1600; double exposureTime = 1.0 / 1600;
ExifProfile profile = GetExifProfile(); ExifProfile profile = GetExifProfile();
@ -131,7 +130,6 @@ namespace SixLabors.ImageSharp.Tests
image.Dispose(); image.Dispose();
} }
}
[Theory] [Theory]
[InlineData(TestImageWriteFormat.Jpeg)] [InlineData(TestImageWriteFormat.Jpeg)]
@ -454,27 +452,23 @@ namespace SixLabors.ImageSharp.Tests
private static Image<Rgba32> WriteAndReadJpeg(Image<Rgba32> image) private static Image<Rgba32> WriteAndReadJpeg(Image<Rgba32> image)
{ {
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
image.SaveAsJpeg(memStream); image.SaveAsJpeg(memStream);
image.Dispose(); image.Dispose();
memStream.Position = 0; memStream.Position = 0;
return Image.Load<Rgba32>(memStream); return Image.Load<Rgba32>(memStream);
} }
}
private static Image<Rgba32> WriteAndReadPng(Image<Rgba32> image) private static Image<Rgba32> WriteAndReadPng(Image<Rgba32> image)
{ {
using (var memStream = new MemoryStream()) using var memStream = new MemoryStream();
{
image.SaveAsPng(memStream); image.SaveAsPng(memStream);
image.Dispose(); image.Dispose();
memStream.Position = 0; memStream.Position = 0;
return Image.Load<Rgba32>(memStream); return Image.Load<Rgba32>(memStream);
} }
}
private static void TestProfile(ExifProfile profile) private static void TestProfile(ExifProfile profile)
{ {

4
tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs

@ -13,11 +13,9 @@ namespace SixLabors.ImageSharp.Tests
public ExifValueTests() public ExifValueTests()
{ {
using (Image<Rgba32> image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image()) using Image<Rgba32> image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image();
{
this.profile = image.Metadata.ExifProfile; this.profile = image.Metadata.ExifProfile;
} }
}
private IExifValue<string> GetExifValue() private IExifValue<string> GetExifValue()
{ {

10
tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs

@ -33,17 +33,15 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelBlenders
public void PorterDuffOutputIsCorrect(TestImageProvider<Rgba32> provider, PixelAlphaCompositionMode mode) public void PorterDuffOutputIsCorrect(TestImageProvider<Rgba32> provider, PixelAlphaCompositionMode mode)
{ {
var srcFile = TestFile.Create(TestImages.Png.PDSrc); var srcFile = TestFile.Create(TestImages.Png.PDSrc);
using (Image<Rgba32> src = srcFile.CreateRgba32Image()) using Image<Rgba32> src = srcFile.CreateRgba32Image();
using (Image<Rgba32> dest = provider.GetImage()) using Image<Rgba32> dest = provider.GetImage();
{
var options = new GraphicsOptions var options = new GraphicsOptions
{ {
Antialias = false, Antialias = false,
AlphaCompositionMode = mode AlphaCompositionMode = mode
}; };
using (Image<Rgba32> res = dest.Clone(x => x.DrawImage(src, options))) using Image<Rgba32> res = dest.Clone(x => x.DrawImage(src, options));
{
string combinedMode = mode.ToString(); string combinedMode = mode.ToString();
if (combinedMode != "Src" && combinedMode.StartsWith("Src")) if (combinedMode != "Src" && combinedMode.StartsWith("Src"))
@ -56,5 +54,3 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelBlenders
} }
} }
} }
}
}

8
tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0. // Licensed under the Apache License, Version 2.0.
using System.Buffers; using System.Buffers;
@ -30,9 +30,8 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelOperations
const int times = 200000; const int times = 200000;
const int count = 1024; const int count = 1024;
using (IMemoryOwner<Rgba32> source = Configuration.Default.MemoryAllocator.Allocate<Rgba32>(count)) using IMemoryOwner<Rgba32> source = Configuration.Default.MemoryAllocator.Allocate<Rgba32>(count);
using (IMemoryOwner<Vector4> dest = Configuration.Default.MemoryAllocator.Allocate<Vector4>(count)) using IMemoryOwner<Vector4> dest = Configuration.Default.MemoryAllocator.Allocate<Vector4>(count);
{
this.Measure( this.Measure(
times, times,
() => PixelOperations<Rgba32>.Instance.ToVector4( () => PixelOperations<Rgba32>.Instance.ToVector4(
@ -43,4 +42,3 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelOperations
} }
} }
} }
}

4
tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs

@ -997,12 +997,10 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelOperations
where TSource : struct where TSource : struct
where TDest : struct where TDest : struct
{ {
using (var buffers = new TestBuffers<TSource, TDest>(source, expected)) using var buffers = new TestBuffers<TSource, TDest>(source, expected);
{
action(buffers.SourceBuffer, buffers.ActualDestBuffer); action(buffers.SourceBuffer, buffers.ActualDestBuffer);
buffers.Verify(); buffers.Verify();
} }
}
internal static Vector4[] CreateVector4TestData(int length, RefAction<Vector4> vectorModifier = null) internal static Vector4[] CreateVector4TestData(int length, RefAction<Vector4> vectorModifier = null)
{ {

16
tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs

@ -32,8 +32,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
70, 87, 69, 68, 65, 73, 78, 90 70, 87, 69, 68, 65, 73, 78, 90
}; };
using (var image = new Image<Rgba32>(8, 8)) using var image = new Image<Rgba32>(8, 8);
{
for (int y = 0; y < 8; y++) for (int y = 0; y < 8; y++)
{ {
for (int x = 0; x < 8; x++) for (int x = 0; x < 8; x++)
@ -73,15 +72,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
} }
} }
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Baseline.LowContrast, PixelTypes.Rgba32)] [WithFile(TestImages.Jpeg.Baseline.LowContrast, PixelTypes.Rgba32)]
public void Adaptive_SlidingWindow_15Tiles_WithClipping<TPixel>(TestImageProvider<TPixel> provider) public void Adaptive_SlidingWindow_15Tiles_WithClipping<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new HistogramEqualizationOptions var options = new HistogramEqualizationOptions
{ {
Method = HistogramEqualizationMethod.AdaptiveSlidingWindow, Method = HistogramEqualizationMethod.AdaptiveSlidingWindow,
@ -93,15 +90,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Baseline.LowContrast, PixelTypes.Rgba32)] [WithFile(TestImages.Jpeg.Baseline.LowContrast, PixelTypes.Rgba32)]
public void Adaptive_TileInterpolation_10Tiles_WithClipping<TPixel>(TestImageProvider<TPixel> provider) public void Adaptive_TileInterpolation_10Tiles_WithClipping<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new HistogramEqualizationOptions var options = new HistogramEqualizationOptions
{ {
Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, Method = HistogramEqualizationMethod.AdaptiveTileInterpolation,
@ -113,7 +108,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
/// <summary> /// <summary>
/// This is regression test for a bug with the calculation of the y-start positions, /// This is regression test for a bug with the calculation of the y-start positions,
@ -127,8 +121,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
public void Issue984<TPixel>(TestImageProvider<TPixel> provider) public void Issue984<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new HistogramEqualizationOptions() var options = new HistogramEqualizationOptions()
{ {
Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, Method = HistogramEqualizationMethod.AdaptiveTileInterpolation,
@ -143,4 +136,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Normalization
} }
} }
} }
}

28
tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs

@ -52,12 +52,10 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
public void BinaryDitherFilter_WorksWithAllDitherers<TPixel>(TestImageProvider<TPixel> provider, string name, IOrderedDither ditherer) public void BinaryDitherFilter_WorksWithAllDitherers<TPixel>(TestImageProvider<TPixel> provider, string name, IOrderedDither ditherer)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.BinaryDither(ditherer)); image.Mutate(x => x.BinaryDither(ditherer));
image.DebugSave(provider, name); image.DebugSave(provider, name);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), nameof(ErrorDiffusers), PixelTypes.Rgba32)] [WithFileCollection(nameof(CommonTestImages), nameof(ErrorDiffusers), PixelTypes.Rgba32)]
@ -65,45 +63,38 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
public void DiffusionFilter_WorksWithAllErrorDiffusers<TPixel>(TestImageProvider<TPixel> provider, string name, IErrorDiffuser diffuser) public void DiffusionFilter_WorksWithAllErrorDiffusers<TPixel>(TestImageProvider<TPixel> provider, string name, IErrorDiffuser diffuser)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.BinaryDiffuse(diffuser, .5F)); image.Mutate(x => x.BinaryDiffuse(diffuser, .5F));
image.DebugSave(provider, name); image.DebugSave(provider, name);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Bike, TestPixelTypes)] [WithFile(TestImages.Png.Bike, TestPixelTypes)]
public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.BinaryDither(DefaultDitherer)); image.Mutate(x => x.BinaryDither(DefaultDitherer));
image.DebugSave(provider); image.DebugSave(provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Bike, TestPixelTypes)] [WithFile(TestImages.Png.Bike, TestPixelTypes)]
public void DiffusionFilter_ShouldNotDependOnSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void DiffusionFilter_ShouldNotDependOnSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f)); image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f));
image.DebugSave(provider); image.DebugSave(provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)]
public void ApplyDitherFilterInBox<TPixel>(TestImageProvider<TPixel> provider) public void ApplyDitherFilterInBox<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> source = provider.GetImage()) using Image<TPixel> source = provider.GetImage();
using (Image<TPixel> image = source.Clone()) using Image<TPixel> image = source.Clone();
{
var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2);
image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds)); image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds));
@ -111,16 +102,14 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)]
public void ApplyDiffusionFilterInBox<TPixel>(TestImageProvider<TPixel> provider) public void ApplyDiffusionFilterInBox<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> source = provider.GetImage()) using Image<TPixel> source = provider.GetImage();
using (Image<TPixel> image = source.Clone()) using Image<TPixel> image = source.Clone();
{
var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2);
image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds)); image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds));
@ -130,4 +119,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
} }
} }
} }
}

10
tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs

@ -32,21 +32,18 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
public void ImageShouldApplyBinaryThresholdFilter<TPixel>(TestImageProvider<TPixel> provider, float value) public void ImageShouldApplyBinaryThresholdFilter<TPixel>(TestImageProvider<TPixel> provider, float value)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.BinaryThreshold(value)); image.Mutate(x => x.BinaryThreshold(value));
image.DebugSave(provider, value); image.DebugSave(provider, value);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), nameof(BinaryThresholdValues), PixelTypes.Rgba32)] [WithFileCollection(nameof(CommonTestImages), nameof(BinaryThresholdValues), PixelTypes.Rgba32)]
public void ImageShouldApplyBinaryThresholdInBox<TPixel>(TestImageProvider<TPixel> provider, float value) public void ImageShouldApplyBinaryThresholdInBox<TPixel>(TestImageProvider<TPixel> provider, float value)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> source = provider.GetImage()) using Image<TPixel> source = provider.GetImage();
using (var image = source.Clone()) using var image = source.Clone();
{
var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2);
image.Mutate(x => x.BinaryThreshold(value, bounds)); image.Mutate(x => x.BinaryThreshold(value, bounds));
@ -56,4 +53,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization
} }
} }
} }
}

8
tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs

@ -56,12 +56,10 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution
} }
// Make sure the kernel components are the same // Make sure the kernel components are the same
using (var image = new Image<Rgb24>(1, 1)) using var image = new Image<Rgb24>(1, 1);
{
Configuration configuration = image.GetConfiguration(); Configuration configuration = image.GetConfiguration();
var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma);
using (var processor = (BokehBlurProcessor<Rgb24>)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds())) using var processor = (BokehBlurProcessor<Rgb24>)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds());
{
Assert.Equal(components.Count, processor.Kernels.Count); Assert.Equal(components.Count, processor.Kernels.Count);
foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b)))
{ {
@ -74,8 +72,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution
} }
} }
} }
}
}
public sealed class BokehBlurInfo : IXunitSerializable public sealed class BokehBlurInfo : IXunitSerializable
{ {

16
tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs

@ -57,46 +57,39 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution
public void DetectEdges_WorksWithAllFilters<TPixel>(TestImageProvider<TPixel> provider, EdgeDetectionOperators detector) public void DetectEdges_WorksWithAllFilters<TPixel>(TestImageProvider<TPixel> provider, EdgeDetectionOperators detector)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.DetectEdges(detector)); image.Mutate(x => x.DetectEdges(detector));
image.DebugSave(provider, detector.ToString()); image.DebugSave(provider, detector.ToString());
image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString()); image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString());
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImages), CommonNonDefaultPixelTypes)] [WithFileCollection(nameof(TestImages), CommonNonDefaultPixelTypes)]
public void DetectEdges_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider) public void DetectEdges_IsNotBoundToSinglePixelType<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.DetectEdges()); image.Mutate(x => x.DetectEdges());
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFile(Tests.TestImages.Gif.Giphy, PixelTypes.Rgba32)] [WithFile(Tests.TestImages.Gif.Giphy, PixelTypes.Rgba32)]
public void DetectEdges_IsAppliedToAllFrames<TPixel>(TestImageProvider<TPixel> provider) public void DetectEdges_IsAppliedToAllFrames<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.DetectEdges()); image.Mutate(x => x.DetectEdges());
image.DebugSave(provider, extension: "gif"); image.DebugSave(provider, extension: "gif");
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(TestImages), PixelTypes.Rgba32)] [WithFileCollection(nameof(TestImages), PixelTypes.Rgba32)]
public void DetectEdges_InBox<TPixel>(TestImageProvider<TPixel> provider) public void DetectEdges_InBox<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2);
image.Mutate(x => x.DetectEdges(bounds)); image.Mutate(x => x.DetectEdges(bounds));
@ -105,4 +98,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution
} }
} }
} }
}

10
tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs

@ -44,8 +44,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void AutoOrient_WorksForAllExifOrientations<TPixel>(TestImageProvider<TPixel> provider, ushort orientation) public void AutoOrient_WorksForAllExifOrientations<TPixel>(TestImageProvider<TPixel> provider, ushort orientation)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Metadata.ExifProfile = new ExifProfile(); image.Metadata.ExifProfile = new ExifProfile();
image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation); image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation);
@ -53,7 +52,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider, orientation, appendPixelTypeToFileName: false); image.DebugSave(provider, orientation, appendPixelTypeToFileName: false);
image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false); image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false);
} }
}
[Theory] [Theory]
[WithFile(FlipTestFile, nameof(InvalidOrientationValues), PixelTypes.Rgba32)] [WithFile(FlipTestFile, nameof(InvalidOrientationValues), PixelTypes.Rgba32)]
@ -80,9 +78,8 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
ulong orientationCode = BitConverter.ToUInt64(orientationCodeData, 0); ulong orientationCode = BitConverter.ToUInt64(orientationCodeData, 0);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
using (Image<TPixel> reference = image.Clone()) using Image<TPixel> reference = image.Clone();
{
image.Metadata.ExifProfile = new ExifProfile(bytes); image.Metadata.ExifProfile = new ExifProfile(bytes);
image.Mutate(x => x.AutoOrient()); image.Mutate(x => x.AutoOrient());
image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false); image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false);
@ -90,4 +87,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
} }
} }
} }
}

8
tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs

@ -19,8 +19,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void ImageShouldPad<TPixel>(TestImageProvider<TPixel> provider) public void ImageShouldPad<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50)); image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50));
image.DebugSave(provider); image.DebugSave(provider);
@ -33,7 +32,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
} }
} }
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), PixelTypes.Rgba32)] [WithFileCollection(nameof(CommonTestImages), PixelTypes.Rgba32)]
@ -42,8 +40,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
{ {
var color = Color.Red; var color = Color.Red;
TPixel expected = color.ToPixel<TPixel>(); TPixel expected = color.ToPixel<TPixel>();
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color)); image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color));
image.DebugSave(provider); image.DebugSave(provider);
@ -58,4 +55,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
} }
} }
} }
}

97
tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs

@ -45,8 +45,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
{ {
var filePath = TestFile.GetInputFileFullPath(TestImages.Jpeg.Baseline.Calliphora); var filePath = TestFile.GetInputFileFullPath(TestImages.Jpeg.Baseline.Calliphora);
using (var image = Image.Load(filePath)) using var image = Image.Load(filePath);
{
image.Mutate(x => x.Resize(image.Size() / 2)); image.Mutate(x => x.Resize(image.Size() / 2));
string path = System.IO.Path.Combine( string path = System.IO.Path.Combine(
TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)), TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)),
@ -54,7 +53,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.Save(path); image.Save(path);
} }
}
[Theory(Skip = "Debug only, enable manually")] [Theory(Skip = "Debug only, enable manually")]
[WithTestPatternImage(4000, 4000, PixelTypes.Rgba32, 300, 1024)] [WithTestPatternImage(4000, 4000, PixelTypes.Rgba32, 300, 1024)]
@ -70,12 +68,10 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
provider.Configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInKilobytes * 1024; provider.Configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInKilobytes * 1024;
using (var image = provider.GetImage()) using var image = provider.GetImage();
{
image.Mutate(x => x.Resize(destSize, destSize)); image.Mutate(x => x.Resize(destSize, destSize));
image.DebugSave(provider, appendPixelTypeToFileName: false); image.DebugSave(provider, appendPixelTypeToFileName: false);
} }
}
[Theory] [Theory]
[WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)]
@ -88,15 +84,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
// [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] means: // [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] means:
// resizing: (15, 12) -> (10, 6) // resizing: (15, 12) -> (10, 6)
// kernel dimensions: (3, 4) // kernel dimensions: (3, 4)
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD);
image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false));
FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})"; FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})";
image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false); image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false);
image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false); image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false);
} }
}
private static readonly int SizeOfVector4 = Unsafe.SizeOf<Vector4>(); private static readonly int SizeOfVector4 = Unsafe.SizeOf<Vector4>();
@ -113,14 +107,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
int workingBufferLimitInRows) int workingBufferLimitInRows)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image0 = provider.GetImage()) using Image<TPixel> image0 = provider.GetImage();
{
Size destSize = image0.Size() / 4; Size destSize = image0.Size() / 4;
Configuration configuration = Configuration.CreateDefaultInstance(); var configuration = Configuration.CreateDefaultInstance();
int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4; int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4;
TestMemoryAllocator allocator = new TestMemoryAllocator(); var allocator = new TestMemoryAllocator();
configuration.MemoryAllocator = allocator; configuration.MemoryAllocator = allocator;
configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes; configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes;
@ -132,8 +125,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4; int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4;
verticalKernelMap.Dispose(); verticalKernelMap.Dispose();
using (Image<TPixel> image = image0.Clone(configuration)) using Image<TPixel> image = image0.Clone(configuration);
{
image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false));
image.DebugSave( image.DebugSave(
@ -153,22 +145,18 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes)); Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes));
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, DefaultPixelType)] [WithTestPatternImage(100, 100, DefaultPixelType)]
public void Resize_Compand<TPixel>(TestImageProvider<TPixel> provider) public void Resize_Compand<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(image.Size() / 2, true)); image.Mutate(x => x.Resize(image.Size() / 2, true));
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.Kaboom, DefaultPixelType, false)] [WithFile(TestImages.Png.Kaboom, DefaultPixelType, false)]
@ -190,14 +178,12 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void Resize_IsAppliedToAllFrames<TPixel>(TestImageProvider<TPixel> provider) public void Resize_IsAppliedToAllFrames<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic)); image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic));
// Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :( // Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :(
image.DebugSave(provider, extension: "gif"); image.DebugSave(provider, extension: "gif");
} }
}
[Theory] [Theory]
[WithTestPatternImage(50, 50, CommonNonDefaultPixelTypes)] [WithTestPatternImage(50, 50, CommonNonDefaultPixelTypes)]
@ -212,17 +198,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void Resize_ThrowsForWrappedMemoryImage<TPixel>(TestImageProvider<TPixel> provider) public void Resize_ThrowsForWrappedMemoryImage<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image0 = provider.GetImage()) using Image<TPixel> image0 = provider.GetImage();
{
var mmg = TestMemoryManager<TPixel>.CreateAsCopyOf(image0.GetPixelSpan()); var mmg = TestMemoryManager<TPixel>.CreateAsCopyOf(image0.GetPixelSpan());
using (var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height)) using var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height);
{
Assert.ThrowsAny<Exception>( Assert.ThrowsAny<Exception>(
() => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); }); () => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); });
} }
}
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType, 1)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType, 1)]
@ -328,8 +310,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void ResizeFromSourceRectangle<TPixel>(TestImageProvider<TPixel> provider) public void ResizeFromSourceRectangle<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var sourceRectangle = new Rectangle( var sourceRectangle = new Rectangle(
image.Width / 8, image.Width / 8,
image.Height / 8, image.Height / 8,
@ -349,69 +330,59 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeHeightAndKeepAspect<TPixel>(TestImageProvider<TPixel> provider) public void ResizeHeightAndKeepAspect<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(0, image.Height / 3, false)); image.Mutate(x => x.Resize(0, image.Height / 3, false));
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithTestPatternImage(10, 100, DefaultPixelType)] [WithTestPatternImage(10, 100, DefaultPixelType)]
public void ResizeHeightCannotKeepAspectKeepsOnePixel<TPixel>(TestImageProvider<TPixel> provider) public void ResizeHeightCannotKeepAspectKeepsOnePixel<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(0, 5)); image.Mutate(x => x.Resize(0, 5));
Assert.Equal(1, image.Width); Assert.Equal(1, image.Width);
Assert.Equal(5, image.Height); Assert.Equal(5, image.Height);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWidthAndKeepAspect<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWidthAndKeepAspect<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(image.Width / 3, 0, false)); image.Mutate(x => x.Resize(image.Width / 3, 0, false));
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithTestPatternImage(100, 10, DefaultPixelType)] [WithTestPatternImage(100, 10, DefaultPixelType)]
public void ResizeWidthCannotKeepAspectKeepsOnePixel<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWidthCannotKeepAspectKeepsOnePixel<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.Resize(5, 0)); image.Mutate(x => x.Resize(5, 0));
Assert.Equal(5, image.Width); Assert.Equal(5, image.Width);
Assert.Equal(1, image.Height); Assert.Equal(1, image.Height);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithBoxPadMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithBoxPadMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions var options = new ResizeOptions
{ {
Size = new Size(image.Width + 200, image.Height + 200), Size = new Size(image.Width + 200, image.Height + 200),
@ -423,15 +394,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithCropHeightMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithCropHeightMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) }; var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) };
image.Mutate(x => x.Resize(options)); image.Mutate(x => x.Resize(options));
@ -439,15 +408,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithCropWidthMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithCropWidthMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) }; var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) };
image.Mutate(x => x.Resize(options)); image.Mutate(x => x.Resize(options));
@ -455,15 +422,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Issues.IncorrectResize1006, DefaultPixelType)] [WithFile(TestImages.Jpeg.Issues.IncorrectResize1006, DefaultPixelType)]
public void CanResizeLargeImageWithCropMode<TPixel>(TestImageProvider<TPixel> provider) public void CanResizeLargeImageWithCropMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions var options = new ResizeOptions
{ {
Size = new Size(480, 600), Size = new Size(480, 600),
@ -475,15 +440,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithMaxMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithMaxMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max }; var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max };
image.Mutate(x => x.Resize(options)); image.Mutate(x => x.Resize(options));
@ -491,15 +454,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithMinMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithMinMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions var options = new ResizeOptions
{ {
Size = new Size( Size = new Size(
@ -513,15 +474,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithPadMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithPadMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions var options = new ResizeOptions
{ {
Size = new Size(image.Width + 200, image.Height), Size = new Size(image.Width + 200, image.Height),
@ -533,15 +492,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFileCollection(nameof(CommonTestImages), DefaultPixelType)] [WithFileCollection(nameof(CommonTestImages), DefaultPixelType)]
public void ResizeWithStretchMode<TPixel>(TestImageProvider<TPixel> provider) public void ResizeWithStretchMode<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
var options = new ResizeOptions var options = new ResizeOptions
{ {
Size = new Size(image.Width / 2, image.Height), Size = new Size(image.Width / 2, image.Height),
@ -553,7 +510,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Issues.ExifDecodeOutOfRange694, DefaultPixelType)] [WithFile(TestImages.Jpeg.Issues.ExifDecodeOutOfRange694, DefaultPixelType)]
@ -568,11 +524,10 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
return; return;
} }
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
// Don't bother saving, we're testing the EXIF metadata updates. // Don't bother saving, we're testing the EXIF metadata updates.
image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2)); image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2));
} }
} }
} }
}

6
tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0. // Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats;
@ -29,11 +29,9 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms
public void RotateFlip<TPixel>(TestImageProvider<TPixel> provider, RotateMode rotateType, FlipMode flipType) public void RotateFlip<TPixel>(TestImageProvider<TPixel> provider, RotateMode rotateType, FlipMode flipType)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.Mutate(x => x.RotateFlip(rotateType, flipType)); image.Mutate(x => x.RotateFlip(rotateType, flipType));
image.DebugSave(provider, string.Join("_", rotateType, flipType)); image.DebugSave(provider, string.Join("_", rotateType, flipType));
} }
} }
} }
}

24
tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs

@ -81,8 +81,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
IResampler resampler = GetResampler(resamplerName); IResampler resampler = GetResampler(resamplerName);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(30); .AppendRotationDegrees(30);
@ -91,7 +90,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
VerifyAllPixelsAreWhiteOrTransparent(image); VerifyAllPixelsAreWhiteOrTransparent(image);
} }
}
[Theory] [Theory]
[WithTestPatternImage(nameof(TransformValues), 100, 50, PixelTypes.Rgba32)] [WithTestPatternImage(nameof(TransformValues), 100, 50, PixelTypes.Rgba32)]
@ -104,8 +102,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
float ty) float ty)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.DebugSave(provider, $"_original"); image.DebugSave(provider, $"_original");
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(angleDeg) .AppendRotationDegrees(angleDeg)
@ -120,15 +117,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider, testOutputDetails); image.DebugSave(provider, testOutputDetails);
image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails);
} }
}
[Theory] [Theory]
[WithTestPatternImage(96, 96, PixelTypes.Rgba32, 50, 0.8f)] [WithTestPatternImage(96, 96, PixelTypes.Rgba32, 50, 0.8f)]
public void Transform_RotateScale_ManuallyCentered<TPixel>(TestImageProvider<TPixel> provider, float angleDeg, float s) public void Transform_RotateScale_ManuallyCentered<TPixel>(TestImageProvider<TPixel> provider, float angleDeg, float s)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(angleDeg) .AppendRotationDegrees(angleDeg)
.AppendScale(new SizeF(s, s)); .AppendScale(new SizeF(s, s));
@ -139,7 +134,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider, testOutputDetails); image.DebugSave(provider, testOutputDetails);
image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails);
} }
}
public static readonly TheoryData<int, int, int, int> Transform_IntoRectangle_Data = public static readonly TheoryData<int, int, int, int> Transform_IntoRectangle_Data =
new TheoryData<int, int, int, int> new TheoryData<int, int, int, int>
@ -163,8 +157,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
{ {
var rectangle = new Rectangle(48, 0, 48, 24); var rectangle = new Rectangle(48, 0, 48, 24);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.DebugSave(provider, $"_original"); image.DebugSave(provider, $"_original");
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendScale(new SizeF(2, 1.5F)); .AppendScale(new SizeF(2, 1.5F));
@ -174,7 +167,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithTestPatternImage(96, 48, PixelTypes.Rgba32)] [WithTestPatternImage(96, 48, PixelTypes.Rgba32)]
@ -183,8 +175,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
{ {
var rectangle = new Rectangle(0, 24, 48, 24); var rectangle = new Rectangle(0, 24, 48, 24);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendScale(new SizeF(1F, 2F)); .AppendScale(new SizeF(1F, 2F));
@ -193,7 +184,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider); image.CompareToReferenceOutput(ValidatorComparer, provider);
} }
}
[Theory] [Theory]
[WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] [WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)]
@ -201,8 +191,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
IResampler sampler = GetResampler(resamplerName); IResampler sampler = GetResampler(resamplerName);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
AffineTransformBuilder builder = new AffineTransformBuilder() AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(50) .AppendRotationDegrees(50)
.AppendScale(new SizeF(.6F, .6F)); .AppendScale(new SizeF(.6F, .6F));
@ -212,7 +201,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider, resamplerName); image.DebugSave(provider, resamplerName);
image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName);
} }
}
private static IResampler GetResampler(string name) private static IResampler GetResampler(string name)
{ {

16
tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs

@ -64,8 +64,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
IResampler sampler = GetResampler(resamplerName); IResampler sampler = GetResampler(resamplerName);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder()
.AppendTaper(TaperSide.Right, TaperCorner.Both, .5F); .AppendTaper(TaperSide.Right, TaperCorner.Both, .5F);
@ -74,15 +73,13 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider, resamplerName); image.DebugSave(provider, resamplerName);
image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(nameof(TaperMatrixData), 30, 30, nameof(Rgba32.Red), PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(TaperMatrixData), 30, 30, nameof(Rgba32.Red), PixelTypes.Rgba32)]
public void Transform_WithTaperMatrix<TPixel>(TestImageProvider<TPixel> provider, TaperSide taperSide, TaperCorner taperCorner) public void Transform_WithTaperMatrix<TPixel>(TestImageProvider<TPixel> provider, TaperSide taperSide, TaperCorner taperCorner)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder()
.AppendTaper(taperSide, taperCorner, .5F); .AppendTaper(taperSide, taperCorner, .5F);
@ -92,7 +89,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider, testOutputDetails); image.DebugSave(provider, testOutputDetails);
image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails); image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(100, 100, 0, 0, 255, PixelTypes.Rgba32)] [WithSolidFilledImages(100, 100, 0, 0, 255, PixelTypes.Rgba32)]
@ -104,8 +100,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
// This test matches the output described in the example at // This test matches the output described in the example at
// https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/non-affine // https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/non-affine
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Matrix4x4 matrix = Matrix4x4.Identity; Matrix4x4 matrix = Matrix4x4.Identity;
matrix.M14 = 0.01F; matrix.M14 = 0.01F;
@ -117,7 +112,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(TolerantComparer, provider); image.CompareToReferenceOutput(TolerantComparer, provider);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(290, 154, 0, 0, 255, PixelTypes.Rgba32)] [WithSolidFilledImages(290, 154, 0, 0, 255, PixelTypes.Rgba32)]
@ -126,8 +120,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
{ {
// https://jsfiddle.net/dFrHS/545/ // https://jsfiddle.net/dFrHS/545/
// https://github.com/SixLabors/ImageSharp/issues/787 // https://github.com/SixLabors/ImageSharp/issues/787
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
#pragma warning disable SA1117 // Parameters should be on same line or separate lines #pragma warning disable SA1117 // Parameters should be on same line or separate lines
var matrix = new Matrix4x4( var matrix = new Matrix4x4(
0.260987f, -0.434909f, 0, -0.0022184f, 0.260987f, -0.434909f, 0, -0.0022184f,
@ -144,7 +137,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
image.DebugSave(provider); image.DebugSave(provider);
image.CompareToReferenceOutput(TolerantComparer, provider); image.CompareToReferenceOutput(TolerantComparer, provider);
} }
}
private static IResampler GetResampler(string name) private static IResampler GetResampler(string name)
{ {

4
tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs

@ -15,8 +15,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
{ {
int xy = 1; int xy = 1;
using (var img = new Image<A8>(xy, xy)) using var img = new Image<A8>(xy, xy);
{
var profile = new ExifProfile(); var profile = new ExifProfile();
img.Metadata.ExifProfile = profile; img.Metadata.ExifProfile = profile;
profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue); profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue);
@ -32,4 +31,3 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms
} }
} }
} }
}

4
tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs

@ -26,8 +26,7 @@ namespace SixLabors.ImageSharp.Tests.ProfilingBenchmarks
byte[] imageBytes = TestFile.Create(imagePath).Bytes; byte[] imageBytes = TestFile.Create(imagePath).Bytes;
using (var ms = new MemoryStream()) using var ms = new MemoryStream();
{
this.Measure( this.Measure(
30, 30,
() => () =>
@ -43,4 +42,3 @@ namespace SixLabors.ImageSharp.Tests.ProfilingBenchmarks
} }
} }
} }
}

4
tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs

@ -30,10 +30,8 @@ namespace SixLabors.ImageSharp.Tests.ProfilingBenchmarks
this.ExecutionCount, this.ExecutionCount,
() => () =>
{ {
using (var image = new Image<Rgba32>(this.configuration, width, height)) using var image = new Image<Rgba32>(this.configuration, width, height);
{
image.Mutate(x => x.Resize(width / 5, height / 5)); image.Mutate(x => x.Resize(width / 5, height / 5));
}
}); });
} }
} }

8
tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs

@ -41,8 +41,7 @@ namespace SixLabors.ImageSharp.Tests
bool dither) bool dither)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.True(image[0, 0].Equals(default(TPixel))); Assert.True(image[0, 0].Equals(default(TPixel)));
var quantizer = new OctreeQuantizer(dither); var quantizer = new OctreeQuantizer(dither);
@ -56,7 +55,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(index, quantized.GetPixelSpan()[0]); Assert.Equal(index, quantized.GetPixelSpan()[0]);
} }
} }
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, true)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32, true)]
@ -64,8 +62,7 @@ namespace SixLabors.ImageSharp.Tests
public void WuQuantizerYieldsCorrectTransparentPixel<TPixel>(TestImageProvider<TPixel> provider, bool dither) public void WuQuantizerYieldsCorrectTransparentPixel<TPixel>(TestImageProvider<TPixel> provider, bool dither)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.True(image[0, 0].Equals(default(TPixel))); Assert.True(image[0, 0].Equals(default(TPixel)));
var quantizer = new WuQuantizer(dither); var quantizer = new WuQuantizer(dither);
@ -79,7 +76,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.Equal(index, quantized.GetPixelSpan()[0]); Assert.Equal(index, quantized.GetPixelSpan()[0]);
} }
} }
}
private int GetTransparentIndex<TPixel>(IQuantizedFrame<TPixel> quantized) private int GetTransparentIndex<TPixel>(IQuantizedFrame<TPixel> quantized)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>

46
tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs

@ -17,16 +17,14 @@ namespace SixLabors.ImageSharp.Tests.Quantization
Configuration config = Configuration.Default; Configuration config = Configuration.Default;
var quantizer = new WuQuantizer(false); var quantizer = new WuQuantizer(false);
using (var image = new Image<Rgba32>(config, 1, 1, Rgba32.Black)) using var image = new Image<Rgba32>(config, 1, 1, Rgba32.Black);
using (IQuantizedFrame<Rgba32> result = quantizer.CreateFrameQuantizer<Rgba32>(config).QuantizeFrame(image.Frames[0])) using IQuantizedFrame<Rgba32> result = quantizer.CreateFrameQuantizer<Rgba32>(config).QuantizeFrame(image.Frames[0]);
{
Assert.Equal(1, result.Palette.Length); Assert.Equal(1, result.Palette.Length);
Assert.Equal(1, result.GetPixelSpan().Length); Assert.Equal(1, result.GetPixelSpan().Length);
Assert.Equal(Rgba32.Black, result.Palette.Span[0]); Assert.Equal(Rgba32.Black, result.Palette.Span[0]);
Assert.Equal(0, result.GetPixelSpan()[0]); Assert.Equal(0, result.GetPixelSpan()[0]);
} }
}
[Fact] [Fact]
public void SinglePixelTransparent() public void SinglePixelTransparent()
@ -34,16 +32,14 @@ namespace SixLabors.ImageSharp.Tests.Quantization
Configuration config = Configuration.Default; Configuration config = Configuration.Default;
var quantizer = new WuQuantizer(false); var quantizer = new WuQuantizer(false);
using (var image = new Image<Rgba32>(config, 1, 1, default(Rgba32))) using var image = new Image<Rgba32>(config, 1, 1, default(Rgba32));
using (IQuantizedFrame<Rgba32> result = quantizer.CreateFrameQuantizer<Rgba32>(config).QuantizeFrame(image.Frames[0])) using IQuantizedFrame<Rgba32> result = quantizer.CreateFrameQuantizer<Rgba32>(config).QuantizeFrame(image.Frames[0]);
{
Assert.Equal(1, result.Palette.Length); Assert.Equal(1, result.Palette.Length);
Assert.Equal(1, result.GetPixelSpan().Length); Assert.Equal(1, result.GetPixelSpan().Length);
Assert.Equal(default, result.Palette.Span[0]); Assert.Equal(default, result.Palette.Span[0]);
Assert.Equal(0, result.GetPixelSpan()[0]); Assert.Equal(0, result.GetPixelSpan()[0]);
} }
}
[Fact] [Fact]
public void GrayScale() => TestScale(c => new Rgba32(c, c, c, 128)); public void GrayScale() => TestScale(c => new Rgba32(c, c, c, 128));
@ -63,8 +59,7 @@ namespace SixLabors.ImageSharp.Tests.Quantization
[Fact] [Fact]
public void Palette256() public void Palette256()
{ {
using (var image = new Image<Rgba32>(1, 256)) using var image = new Image<Rgba32>(1, 256);
{
for (int i = 0; i < 256; i++) for (int i = 0; i < 256; i++)
{ {
byte r = (byte)((i % 4) * 85); byte r = (byte)((i % 4) * 85);
@ -77,9 +72,8 @@ namespace SixLabors.ImageSharp.Tests.Quantization
Configuration config = Configuration.Default; Configuration config = Configuration.Default;
var quantizer = new WuQuantizer(false); var quantizer = new WuQuantizer(false);
using (IFrameQuantizer<Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer<Rgba32>(config)) using IFrameQuantizer<Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer<Rgba32>(config);
using (IQuantizedFrame<Rgba32> result = frameQuantizer.QuantizeFrame(image.Frames[0])) using IQuantizedFrame<Rgba32> result = frameQuantizer.QuantizeFrame(image.Frames[0]);
{
Assert.Equal(256, result.Palette.Length); Assert.Equal(256, result.Palette.Length);
Assert.Equal(256, result.GetPixelSpan().Length); Assert.Equal(256, result.GetPixelSpan().Length);
@ -102,8 +96,6 @@ namespace SixLabors.ImageSharp.Tests.Quantization
Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan()));
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Png.LowColorVariance, PixelTypes.Rgba32)] [WithFile(TestImages.Png.LowColorVariance, PixelTypes.Rgba32)]
@ -111,24 +103,19 @@ namespace SixLabors.ImageSharp.Tests.Quantization
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
// See https://github.com/SixLabors/ImageSharp/issues/866 // See https://github.com/SixLabors/ImageSharp/issues/866
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Configuration config = Configuration.Default; Configuration config = Configuration.Default;
var quantizer = new WuQuantizer(false); var quantizer = new WuQuantizer(false);
using (IFrameQuantizer<TPixel> frameQuantizer = quantizer.CreateFrameQuantizer<TPixel>(config)) using IFrameQuantizer<TPixel> frameQuantizer = quantizer.CreateFrameQuantizer<TPixel>(config);
using (IQuantizedFrame<TPixel> result = frameQuantizer.QuantizeFrame(image.Frames[0])) using IQuantizedFrame<TPixel> result = frameQuantizer.QuantizeFrame(image.Frames[0]);
{
Assert.Equal(48, result.Palette.Length); Assert.Equal(48, result.Palette.Length);
} }
}
}
private static void TestScale(Func<byte, Rgba32> pixelBuilder) private static void TestScale(Func<byte, Rgba32> pixelBuilder)
{ {
using (var image = new Image<Rgba32>(1, 256)) using var image = new Image<Rgba32>(1, 256);
using (var expectedImage = new Image<Rgba32>(1, 256)) using var expectedImage = new Image<Rgba32>(1, 256);
using (var actualImage = new Image<Rgba32>(1, 256)) using var actualImage = new Image<Rgba32>(1, 256);
{
for (int i = 0; i < 256; i++) for (int i = 0; i < 256; i++)
{ {
byte c = (byte)i; byte c = (byte)i;
@ -144,9 +131,8 @@ namespace SixLabors.ImageSharp.Tests.Quantization
Configuration config = Configuration.Default; Configuration config = Configuration.Default;
var quantizer = new WuQuantizer(false); var quantizer = new WuQuantizer(false);
using (IFrameQuantizer<Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer<Rgba32>(config)) using IFrameQuantizer<Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer<Rgba32>(config);
using (IQuantizedFrame<Rgba32> result = frameQuantizer.QuantizeFrame(image.Frames[0])) using IQuantizedFrame<Rgba32> result = frameQuantizer.QuantizeFrame(image.Frames[0]);
{
Assert.Equal(4 * 8, result.Palette.Length); Assert.Equal(4 * 8, result.Palette.Length);
Assert.Equal(256, result.GetPixelSpan().Length); Assert.Equal(256, result.GetPixelSpan().Length);
@ -164,10 +150,8 @@ namespace SixLabors.ImageSharp.Tests.Quantization
row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])];
} }
} }
}
Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan()));
} }
} }
} }
}

0
tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs → tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs

8
tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs

@ -223,15 +223,11 @@ namespace SixLabors.ImageSharp.Tests
for (int i = 0; i < image.Frames.Count; i++) for (int i = 0; i < image.Frames.Count; i++)
{ {
using (Image<TPixel> frameImage = image.Frames.CloneFrame(i)) using Image<TPixel> frameImage = image.Frames.CloneFrame(i);
{
string filePath = files[i]; string filePath = files[i];
using (FileStream stream = File.OpenWrite(filePath)) using FileStream stream = File.OpenWrite(filePath);
{
frameImage.Save(stream, encoder); frameImage.Save(stream, encoder);
} }
}
}
return files; return files;
} }

8
tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs

@ -20,13 +20,11 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
public Image<TPixel> Decode<TPixel>(Configuration configuration, Stream stream) public Image<TPixel> Decode<TPixel>(Configuration configuration, Stream stream)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (var magickImage = new MagickImage(stream)) using var magickImage = new MagickImage(stream);
{
var result = new Image<TPixel>(configuration, magickImage.Width, magickImage.Height); var result = new Image<TPixel>(configuration, magickImage.Width, magickImage.Height);
Span<TPixel> resultPixels = result.GetPixelSpan(); Span<TPixel> resultPixels = result.GetPixelSpan();
using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) using IPixelCollection pixels = magickImage.GetPixelsUnsafe();
{
if (magickImage.Depth == 8) if (magickImage.Depth == 8)
{ {
byte[] data = pixels.ToByteArray(PixelMapping.RGBA); byte[] data = pixels.ToByteArray(PixelMapping.RGBA);
@ -52,11 +50,9 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
} }
}
return result; return result;
} }
}
public Image Decode(Configuration configuration, Stream stream) => this.Decode<Rgba32>(configuration, stream); public Image Decode(Configuration configuration, Stream stream) => this.Decode<Rgba32>(configuration, stream);
} }

12
tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs

@ -49,8 +49,7 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
Configuration configuration = image.GetConfiguration(); Configuration configuration = image.GetConfiguration();
using (IMemoryOwner<Bgra32> workBuffer = Configuration.Default.MemoryAllocator.Allocate<Bgra32>(w)) using IMemoryOwner<Bgra32> workBuffer = Configuration.Default.MemoryAllocator.Allocate<Bgra32>(w);
{
fixed (Bgra32* destPtr = &workBuffer.GetReference()) fixed (Bgra32* destPtr = &workBuffer.GetReference())
{ {
for (int y = 0; y < h; y++) for (int y = 0; y < h; y++)
@ -67,7 +66,6 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
} }
} }
} }
}
finally finally
{ {
bmp.UnlockBits(data); bmp.UnlockBits(data);
@ -108,8 +106,7 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
Configuration configuration = image.GetConfiguration(); Configuration configuration = image.GetConfiguration();
using (IMemoryOwner<Bgr24> workBuffer = Configuration.Default.MemoryAllocator.Allocate<Bgr24>(w)) using IMemoryOwner<Bgr24> workBuffer = Configuration.Default.MemoryAllocator.Allocate<Bgr24>(w);
{
fixed (Bgr24* destPtr = &workBuffer.GetReference()) fixed (Bgr24* destPtr = &workBuffer.GetReference())
{ {
for (int y = 0; y < h; y++) for (int y = 0; y < h; y++)
@ -123,7 +120,6 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
} }
} }
} }
}
finally finally
{ {
bmp.UnlockBits(data); bmp.UnlockBits(data);
@ -149,8 +145,7 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
long destRowByteCount = data.Stride; long destRowByteCount = data.Stride;
long sourceRowByteCount = w * sizeof(Bgra32); long sourceRowByteCount = w * sizeof(Bgra32);
using (IMemoryOwner<Bgra32> workBuffer = image.GetConfiguration().MemoryAllocator.Allocate<Bgra32>(w)) using IMemoryOwner<Bgra32> workBuffer = image.GetConfiguration().MemoryAllocator.Allocate<Bgra32>(w);
{
fixed (Bgra32* sourcePtr = &workBuffer.GetReference()) fixed (Bgra32* sourcePtr = &workBuffer.GetReference())
{ {
for (int y = 0; y < h; y++) for (int y = 0; y < h; y++)
@ -163,7 +158,6 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
} }
} }
} }
}
finally finally
{ {
resultBitmap.UnlockBits(data); resultBitmap.UnlockBits(data);

18
tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs

@ -16,41 +16,33 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
public Image<TPixel> Decode<TPixel>(Configuration configuration, Stream stream) public Image<TPixel> Decode<TPixel>(Configuration configuration, Stream stream)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (var sourceBitmap = new System.Drawing.Bitmap(stream)) using var sourceBitmap = new System.Drawing.Bitmap(stream);
{
if (sourceBitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) if (sourceBitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{ {
return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sourceBitmap); return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sourceBitmap);
} }
using (var convertedBitmap = new System.Drawing.Bitmap( using var convertedBitmap = new System.Drawing.Bitmap(
sourceBitmap.Width, sourceBitmap.Width,
sourceBitmap.Height, sourceBitmap.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb)) System.Drawing.Imaging.PixelFormat.Format32bppArgb);
{ using var g = System.Drawing.Graphics.FromImage(convertedBitmap);
using (var g = System.Drawing.Graphics.FromImage(convertedBitmap))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height); g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height);
}
return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(convertedBitmap); return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(convertedBitmap);
} }
}
}
public IImageInfo Identify(Configuration configuration, Stream stream) public IImageInfo Identify(Configuration configuration, Stream stream)
{ {
using (var sourceBitmap = new System.Drawing.Bitmap(stream)) using var sourceBitmap = new System.Drawing.Bitmap(stream);
{
var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat)); var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat));
return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata()); return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata());
} }
}
public Image Decode(Configuration configuration, Stream stream) => this.Decode<Rgba32>(configuration, stream); public Image Decode(Configuration configuration, Stream stream) => this.Decode<Rgba32>(configuration, stream);
} }

6
tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs

@ -1,4 +1,4 @@
// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0. // Licensed under the Apache License, Version 2.0.
using System.Drawing.Imaging; using System.Drawing.Imaging;
@ -25,10 +25,8 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs
public void Encode<TPixel>(Image<TPixel> image, Stream stream) public void Encode<TPixel>(Image<TPixel> image, Stream stream)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image)) using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image);
{
sdBitmap.Save(stream, this.imageFormat); sdBitmap.Save(stream, this.imageFormat);
} }
} }
} }
}

22
tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs

@ -287,19 +287,17 @@ namespace SixLabors.ImageSharp.Tests
bool appendSourceFileOrDescription = true) bool appendSourceFileOrDescription = true)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (var firstFrameOnlyImage = new Image<TPixel>(image.Width, image.Height)) using var firstFrameOnlyImage = new Image<TPixel>(image.Width, image.Height);
using (Image<TPixel> referenceImage = GetReferenceOutputImage<TPixel>( using Image<TPixel> referenceImage = GetReferenceOutputImage<TPixel>(
provider, provider,
testOutputDetails, testOutputDetails,
extension, extension,
appendPixelTypeToFileName, appendPixelTypeToFileName,
appendSourceFileOrDescription)) appendSourceFileOrDescription);
{
firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame); firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame);
firstFrameOnlyImage.Frames.RemoveFrame(0); firstFrameOnlyImage.Frames.RemoveFrame(0);
comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage); comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage);
}
return image; return image;
} }
@ -405,14 +403,12 @@ namespace SixLabors.ImageSharp.Tests
bool appendPixelTypeToFileName = true) bool appendPixelTypeToFileName = true)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> referenceImage = provider.GetReferenceOutputImage<TPixel>( using Image<TPixel> referenceImage = provider.GetReferenceOutputImage<TPixel>(
testOutputDetails, testOutputDetails,
extension, extension,
appendPixelTypeToFileName)) appendPixelTypeToFileName);
{
return comparer.CompareImages(referenceImage, image); return comparer.CompareImages(referenceImage, image);
} }
}
public static Image<TPixel> ComparePixelBufferTo<TPixel>( public static Image<TPixel> ComparePixelBufferTo<TPixel>(
this Image<TPixel> image, this Image<TPixel> image,
@ -556,8 +552,7 @@ namespace SixLabors.ImageSharp.Tests
bool appendSourceFileOrDescription = true) bool appendSourceFileOrDescription = true)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
operation(image); operation(image);
image.DebugSave( image.DebugSave(
@ -573,7 +568,6 @@ namespace SixLabors.ImageSharp.Tests
appendPixelTypeToFileName: appendPixelTypeToFileName, appendPixelTypeToFileName: appendPixelTypeToFileName,
appendSourceFileOrDescription: appendSourceFileOrDescription); appendSourceFileOrDescription: appendSourceFileOrDescription);
} }
}
/// <summary> /// <summary>
/// Utility method for doing the following in one step: /// Utility method for doing the following in one step:
@ -660,12 +654,10 @@ namespace SixLabors.ImageSharp.Tests
referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile); referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile);
using (var actualImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder)) using var actualImage = Image.Load<TPixel>(actualOutputFile, referenceDecoder);
{
ImageComparer comparer = customComparer ?? ImageComparer.Exact; ImageComparer comparer = customComparer ?? ImageComparer.Exact;
comparer.VerifySimilarity(actualImage, image); comparer.VerifySimilarity(actualImage, image);
} }
}
internal static Image<Rgba32> ToGrayscaleImage(this Buffer2D<float> buffer, float scale) internal static Image<Rgba32> ToGrayscaleImage(this Buffer2D<float> buffer, float scale)
{ {

48
tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs

@ -34,42 +34,32 @@ namespace SixLabors.ImageSharp.Tests
int pixelThreshold) int pixelThreshold)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold); var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold);
comparer.VerifySimilarity(image, clone); comparer.VerifySimilarity(image, clone);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(110, 110, PixelTypes.Rgba32)] [WithTestPatternImage(110, 110, PixelTypes.Rgba32)]
public void TolerantImageComparer_ApprovesSimilarityBelowTolerance<TPixel>(TestImageProvider<TPixel> provider) public void TolerantImageComparer_ApprovesSimilarityBelowTolerance<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1);
var comparer = ImageComparer.Tolerant(); var comparer = ImageComparer.Tolerant();
comparer.VerifySimilarity(image, clone); comparer.VerifySimilarity(image, clone);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgba32)] [WithTestPatternImage(100, 100, PixelTypes.Rgba32)]
public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance<TPixel>(TestImageProvider<TPixel> provider) public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
byte perChannelChange = 20; byte perChannelChange = 20;
ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange); ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange);
@ -81,18 +71,14 @@ namespace SixLabors.ImageSharp.Tests
PixelDifference diff = ex.Reports.Single().Differences.Single(); PixelDifference diff = ex.Reports.Single().Differences.Single();
Assert.Equal(new Point(3, 1), diff.Position); Assert.Equal(new Point(3, 1), diff.Position);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgba64)] [WithTestPatternImage(100, 100, PixelTypes.Rgba64)]
public void TolerantImageComparer_TestPerPixelThreshold<TPixel>(TestImageProvider<TPixel> provider) public void TolerantImageComparer_TestPerPixelThreshold<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1);
ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1); ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1);
ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1); ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1);
@ -100,8 +86,6 @@ namespace SixLabors.ImageSharp.Tests
var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3); var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3);
comparer.VerifySimilarity(image, clone); comparer.VerifySimilarity(image, clone);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgba32, 99, 100)] [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 99, 100)]
@ -109,10 +93,8 @@ namespace SixLabors.ImageSharp.Tests
public void VerifySimilarity_ThrowsOnSizeMismatch<TPixel>(TestImageProvider<TPixel> provider, int w, int h) public void VerifySimilarity_ThrowsOnSizeMismatch<TPixel>(TestImageProvider<TPixel> provider, int w, int h)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone(ctx => ctx.Resize(w, h));
using (Image<TPixel> clone = image.Clone(ctx => ctx.Resize(w, h)))
{
ImageDimensionsMismatchException ex = Assert.ThrowsAny<ImageDimensionsMismatchException>( ImageDimensionsMismatchException ex = Assert.ThrowsAny<ImageDimensionsMismatchException>(
() => () =>
{ {
@ -121,18 +103,14 @@ namespace SixLabors.ImageSharp.Tests
}); });
this.Output.WriteLine(ex.Message); this.Output.WriteLine(ex.Message);
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)]
public void VerifySimilarity_WhenAnImageFrameIsDifferent_Reports<TPixel>(TestImageProvider<TPixel> provider) public void VerifySimilarity_WhenAnImageFrameIsDifferent_Reports<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1); ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1);
IEnumerable<ImageSimilarityReport> reports = ImageComparer.Exact.CompareImages(image, clone); IEnumerable<ImageSimilarityReport> reports = ImageComparer.Exact.CompareImages(image, clone);
@ -140,8 +118,6 @@ namespace SixLabors.ImageSharp.Tests
PixelDifference difference = reports.Single().Differences.Single(); PixelDifference difference = reports.Single().Differences.Single();
Assert.Equal(new Point(42, 43), difference.Position); Assert.Equal(new Point(42, 43), difference.Position);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgba32)] [WithTestPatternImage(100, 100, PixelTypes.Rgba32)]

12
tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs

@ -39,9 +39,8 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
ImageComparer comparer = ImageComparer.Exact; ImageComparer comparer = ImageComparer.Exact;
using (var mImage = Image.Load<TPixel>(path, magickDecoder)) using var mImage = Image.Load<TPixel>(path, magickDecoder);
using (var sdImage = Image.Load<TPixel>(path, sdDecoder)) using var sdImage = Image.Load<TPixel>(path, sdDecoder);
{
ImageSimilarityReport<TPixel, TPixel> report = comparer.CompareImagesOrFrames(mImage, sdImage); ImageSimilarityReport<TPixel, TPixel> report = comparer.CompareImagesOrFrames(mImage, sdImage);
mImage.DebugSave(dummyProvider); mImage.DebugSave(dummyProvider);
@ -51,7 +50,6 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
Assert.True(report.IsEmpty); Assert.True(report.IsEmpty);
} }
} }
}
[Theory] [Theory]
[WithBlankImages(1, 1, PixelTypesToTest64, TestImages.Png.Rgba64Bpp)] [WithBlankImages(1, 1, PixelTypesToTest64, TestImages.Png.Rgba64Bpp)]
@ -70,9 +68,8 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
// 1020 == 4 * 255 (Equivalent to manhattan distance of 1+1+1+1=4 in Rgba32 space) // 1020 == 4 * 255 (Equivalent to manhattan distance of 1+1+1+1=4 in Rgba32 space)
var comparer = ImageComparer.TolerantPercentage(1, 1020); var comparer = ImageComparer.TolerantPercentage(1, 1020);
using (var mImage = Image.Load<TPixel>(path, magickDecoder)) using var mImage = Image.Load<TPixel>(path, magickDecoder);
using (var sdImage = Image.Load<TPixel>(path, sdDecoder)) using var sdImage = Image.Load<TPixel>(path, sdDecoder);
{
ImageSimilarityReport<TPixel, TPixel> report = comparer.CompareImagesOrFrames(mImage, sdImage); ImageSimilarityReport<TPixel, TPixel> report = comparer.CompareImagesOrFrames(mImage, sdImage);
mImage.DebugSave(dummyProvider); mImage.DebugSave(dummyProvider);
@ -84,4 +81,3 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
} }
} }
} }
}

50
tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs

@ -26,15 +26,11 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
public void To32bppArgbSystemDrawingBitmap<TPixel>(TestImageProvider<TPixel> provider) public void To32bppArgbSystemDrawingBitmap<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image);
using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image))
{
string fileName = provider.Utility.GetTestOutputFileName("png"); string fileName = provider.Utility.GetTestOutputFileName("png");
sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
} }
}
}
[Theory] [Theory]
[WithBlankImages(1, 1, PixelTypes.Rgba32 | PixelTypes.Bgra32)] [WithBlankImages(1, 1, PixelTypes.Rgba32 | PixelTypes.Bgra32)]
@ -43,20 +39,15 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
{ {
string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash);
using (var sdBitmap = new System.Drawing.Bitmap(path)) using var sdBitmap = new System.Drawing.Bitmap(path);
{ using Image<TPixel> image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sdBitmap);
using (Image<TPixel> image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sdBitmap))
{
image.DebugSave(dummyProvider); image.DebugSave(dummyProvider);
} }
}
}
private static string SavePng<TPixel>(TestImageProvider<TPixel> provider, PngColorType pngColorType) private static string SavePng<TPixel>(TestImageProvider<TPixel> provider, PngColorType pngColorType)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> sourceImage = provider.GetImage()) using Image<TPixel> sourceImage = provider.GetImage();
{
if (pngColorType != PngColorType.RgbWithAlpha) if (pngColorType != PngColorType.RgbWithAlpha)
{ {
sourceImage.Mutate(c => c.MakeOpaque()); sourceImage.Mutate(c => c.MakeOpaque());
@ -65,7 +56,6 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
var encoder = new PngEncoder { ColorType = pngColorType }; var encoder = new PngEncoder { ColorType = pngColorType };
return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder); return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder);
} }
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgba32)] [WithTestPatternImage(100, 100, PixelTypes.Rgba32)]
@ -79,16 +69,12 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
string path = SavePng(provider, PngColorType.RgbWithAlpha); string path = SavePng(provider, PngColorType.RgbWithAlpha);
using (var sdBitmap = new System.Drawing.Bitmap(path)) using var sdBitmap = new System.Drawing.Bitmap(path);
{ using Image<TPixel> original = provider.GetImage();
using (Image<TPixel> original = provider.GetImage()) using Image<TPixel> resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sdBitmap);
using (Image<TPixel> resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap<TPixel>(sdBitmap))
{
ImageComparer comparer = ImageComparer.Exact; ImageComparer comparer = ImageComparer.Exact;
comparer.VerifySimilarity(original, resaved); comparer.VerifySimilarity(original, resaved);
} }
}
}
[Theory] [Theory]
[WithTestPatternImage(100, 100, PixelTypes.Rgb24)] [WithTestPatternImage(100, 100, PixelTypes.Rgb24)]
@ -97,18 +83,12 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
{ {
string path = SavePng(provider, PngColorType.Rgb); string path = SavePng(provider, PngColorType.Rgb);
using (Image<TPixel> original = provider.GetImage()) using Image<TPixel> original = provider.GetImage();
{ using var sdBitmap = new System.Drawing.Bitmap(path);
using (var sdBitmap = new System.Drawing.Bitmap(path)) using Image<TPixel> resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap<TPixel>(sdBitmap);
{
using (Image<TPixel> resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap<TPixel>(sdBitmap))
{
ImageComparer comparer = ImageComparer.Exact; ImageComparer comparer = ImageComparer.Exact;
comparer.VerifySimilarity(original, resaved); comparer.VerifySimilarity(original, resaved);
} }
}
}
}
[Theory] [Theory]
[WithBlankImages(1, 1, PixelTypes.Rgba32 | PixelTypes.Bgra32)] [WithBlankImages(1, 1, PixelTypes.Rgba32 | PixelTypes.Bgra32)]
@ -116,21 +96,17 @@ namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash);
using (var image = Image.Load<TPixel>(path, SystemDrawingReferenceDecoder.Instance)) using var image = Image.Load<TPixel>(path, SystemDrawingReferenceDecoder.Instance);
{
image.DebugSave(dummyProvider); image.DebugSave(dummyProvider);
} }
}
[Theory] [Theory]
[WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)] [WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)]
public void SaveWithReferenceEncoder<TPixel>(TestImageProvider<TPixel> provider) public void SaveWithReferenceEncoder<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png); provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png);
} }
} }
} }
}

32
tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs

@ -20,11 +20,9 @@ namespace SixLabors.ImageSharp.Tests
TestImageProvider<TPixel> provider) TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.CompareToReferenceOutput(provider); image.CompareToReferenceOutput(provider);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)] [WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)]
@ -32,11 +30,9 @@ namespace SixLabors.ImageSharp.Tests
TestImageProvider<TPixel> provider) TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.ThrowsAny<Exception>(() => image.CompareToReferenceOutput(provider)); Assert.ThrowsAny<Exception>(() => image.CompareToReferenceOutput(provider));
} }
}
[Theory] [Theory]
[WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)] [WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)]
@ -44,45 +40,36 @@ namespace SixLabors.ImageSharp.Tests
TestImageProvider<TPixel> provider) TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
image.DebugSave(provider, appendPixelTypeToFileName: false); image.DebugSave(provider, appendPixelTypeToFileName: false);
image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false); image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false);
} }
}
[Theory] [Theory]
[WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)] [WithSolidFilledImages(10, 10, 0, 0, 255, PixelTypes.Rgba32)]
public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws<TPixel>(TestImageProvider<TPixel> provider) public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.ThrowsAny<Exception>(() => image.CompareToReferenceOutput(provider)); Assert.ThrowsAny<Exception>(() => image.CompareToReferenceOutput(provider));
} }
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)]
public void CompareToOriginal_WhenSimilar<TPixel>(TestImageProvider<TPixel> provider) public void CompareToOriginal_WhenSimilar<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{ using Image<TPixel> clone = image.Clone();
using (Image<TPixel> clone = image.Clone())
{
clone.CompareToOriginal(provider, ImageComparer.Exact); clone.CompareToOriginal(provider, ImageComparer.Exact);
} }
}
}
[Theory] [Theory]
[WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, PixelTypes.Rgba32)]
public void CompareToOriginal_WhenDifferent_Throws<TPixel>(TestImageProvider<TPixel> provider) public void CompareToOriginal_WhenDifferent_Throws<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1); ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1);
Assert.ThrowsAny<ImageDifferenceIsOverThresholdException>(() => Assert.ThrowsAny<ImageDifferenceIsOverThresholdException>(() =>
@ -90,15 +77,13 @@ namespace SixLabors.ImageSharp.Tests
image.CompareToOriginal(provider, ImageComparer.Exact); image.CompareToOriginal(provider, ImageComparer.Exact);
}); });
} }
}
[Theory] [Theory]
[WithBlankImages(10, 10, PixelTypes.Rgba32)] [WithBlankImages(10, 10, PixelTypes.Rgba32)]
public void CompareToOriginal_WhenInputIsNotFromFile_Throws<TPixel>(TestImageProvider<TPixel> provider) public void CompareToOriginal_WhenInputIsNotFromFile_Throws<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
Assert.ThrowsAny<Exception>(() => Assert.ThrowsAny<Exception>(() =>
{ {
image.CompareToOriginal(provider, Mock.Of<ImageComparer>()); image.CompareToOriginal(provider, Mock.Of<ImageComparer>());
@ -106,4 +91,3 @@ namespace SixLabors.ImageSharp.Tests
} }
} }
} }
}

22
tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs

@ -179,8 +179,7 @@ namespace SixLabors.ImageSharp.Tests
public void SaveTestOutputFileMultiFrame<TPixel>(TestImageProvider<TPixel> provider) public void SaveTestOutputFileMultiFrame<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image); string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image);
Assert.True(files.Length > 2); Assert.True(files.Length > 2);
@ -190,7 +189,6 @@ namespace SixLabors.ImageSharp.Tests
Assert.True(File.Exists(path)); Assert.True(File.Exists(path));
} }
} }
}
[Theory] [Theory]
[WithBasicTestPatternImages(50, 100, PixelTypes.Rgba32)] [WithBasicTestPatternImages(50, 100, PixelTypes.Rgba32)]
@ -199,11 +197,9 @@ namespace SixLabors.ImageSharp.Tests
public void Use_WithBasicTestPatternImages<TPixel>(TestImageProvider<TPixel> provider) public void Use_WithBasicTestPatternImages<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
img.DebugSave(provider); img.DebugSave(provider);
} }
}
[Theory] [Theory]
[WithBlankImages(42, 666, PixelTypes.All, "hello")] [WithBlankImages(42, 666, PixelTypes.All, "hello")]
@ -238,8 +234,7 @@ namespace SixLabors.ImageSharp.Tests
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
Assert.NotNull(provider.Utility.SourceFileOrDescription); Assert.NotNull(provider.Utility.SourceFileOrDescription);
using (Image<TPixel> img = provider.GetImage()) using Image<TPixel> img = provider.GetImage();
{
Assert.True(img.Width * img.Height > 0); Assert.True(img.Width * img.Height > 0);
Assert.Equal(123, yo); Assert.Equal(123, yo);
@ -247,7 +242,6 @@ namespace SixLabors.ImageSharp.Tests
string fn = provider.Utility.GetTestOutputFileName("jpg"); string fn = provider.Utility.GetTestOutputFileName("jpg");
this.Output.WriteLine(fn); this.Output.WriteLine(fn);
} }
}
[Theory] [Theory]
[WithFile(TestImages.Jpeg.Baseline.Testorig420, PixelTypes.Rgba32)] [WithFile(TestImages.Jpeg.Baseline.Testorig420, PixelTypes.Rgba32)]
@ -263,11 +257,9 @@ namespace SixLabors.ImageSharp.Tests
where TPixel : struct, IPixel<TPixel> where TPixel : struct, IPixel<TPixel>
{ {
Assert.NotNull(provider.Utility.SourceFileOrDescription); Assert.NotNull(provider.Utility.SourceFileOrDescription);
using (Image<TPixel> image = provider.GetImage()) using Image<TPixel> image = provider.GetImage();
{
provider.Utility.SaveTestOutputFile(image, "png"); provider.Utility.SaveTestOutputFile(image, "png");
} }
}
[Theory] [Theory]
[WithMemberFactory(nameof(CreateTestImage), PixelTypes.All)] [WithMemberFactory(nameof(CreateTestImage), PixelTypes.All)]
@ -334,14 +326,12 @@ namespace SixLabors.ImageSharp.Tests
var customConfiguration = Configuration.CreateDefaultInstance(); var customConfiguration = Configuration.CreateDefaultInstance();
provider.Configuration = customConfiguration; provider.Configuration = customConfiguration;
using (Image<TPixel> image2 = provider.GetImage()) using Image<TPixel> image2 = provider.GetImage();
using (Image<TPixel> image3 = provider.GetImage()) using Image<TPixel> image3 = provider.GetImage();
{
Assert.Same(customConfiguration, image2.GetConfiguration()); Assert.Same(customConfiguration, image2.GetConfiguration());
Assert.Same(customConfiguration, image3.GetConfiguration()); Assert.Same(customConfiguration, image3.GetConfiguration());
} }
} }
}
private class TestDecoder : IImageDecoder private class TestDecoder : IImageDecoder
{ {

Loading…
Cancel
Save