From 43cbdab113147901f2f685fc5b72d918e944a39b Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Tue, 21 Jan 2020 20:24:29 +0100 Subject: [PATCH 01/15] Fix stylecop warnings in the test project --- Directory.Build.props | 3 +- src/Directory.Build.props | 3 - .../DataReader/IccDataReader.TagDataEntry.cs | 28 +- .../TagDataEntries/IccLutAToBTagDataEntry.cs | 2 +- .../TagDataEntries/IccLutBToATagDataEntry.cs | 2 +- .../ImageSharp.Benchmarks/Codecs/DecodeTga.cs | 23 +- .../Codecs/EncodeBmpMultiple.cs | 16 +- .../Codecs/EncodeGifMultiple.cs | 13 +- .../ImageSharp.Benchmarks/Codecs/EncodeTga.cs | 2 +- .../Codecs/ImageBenchmarkTests.cs | 5 +- .../BlockOperations/Block8x8F_CopyTo1x1.cs | 6 +- .../BlockOperations/Block8x8F_CopyTo2x2.cs | 7 +- .../BlockOperations/Block8x8F_DivideRound.cs | 19 +- .../Block8x8F_LoadFromInt16.cs | 7 +- .../Jpeg/BlockOperations/Block8x8F_Round.cs | 3 +- .../Codecs/Jpeg/DecodeJpegParseStreamOnly.cs | 3 +- .../Codecs/Jpeg/DecodeJpeg_Aggregate.cs | 6 +- .../Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs | 51 +- .../Codecs/Jpeg/DoubleBufferedStreams.cs | 49 +- .../Codecs/Jpeg/EncodeJpeg.cs | 9 +- .../Codecs/Jpeg/EncodeJpegMultiple.cs | 16 +- .../Codecs/Jpeg/LoadResizeSave_Aggregate.cs | 6 +- .../Jpeg/LoadResizeSave_ImageSpecific.cs | 22 +- .../Codecs/Jpeg/YCbCrColorConversion.cs | 2 +- .../Codecs/MultiImageBenchmarkBase.cs | 55 +- .../Color/Bulk/FromRgba32Bytes.cs | 14 +- .../Color/Bulk/FromVector4.cs | 13 +- .../Color/Bulk/Rgb24Bytes.cs | 5 +- .../Color/Bulk/ToRgba32Bytes.cs | 5 +- .../Color/Bulk/ToVector4.cs | 18 +- .../Color/Bulk/ToVector4_Bgra32.cs | 5 +- .../Color/Bulk/ToVector4_Rgba32.cs | 68 +-- .../Color/ColorspaceCieXyzToCieLabConvert.cs | 8 +- .../ColorspaceCieXyzToHunterLabConvert.cs | 7 +- .../Color/ColorspaceCieXyzToLmsConvert.cs | 5 +- .../Color/ColorspaceCieXyzToRgbConvert.cs | 10 +- .../Color/RgbToYCbCr.LookupTables.cs | 7 +- .../ImageSharp.Benchmarks/Color/RgbToYCbCr.cs | 11 +- .../Color/RgbWorkingSpaceAdapt.cs | 5 +- .../ImageSharp.Benchmarks/Color/YcbCrToRgb.cs | 5 +- tests/ImageSharp.Benchmarks/Config.cs | 3 +- .../ImageSharp.Benchmarks/General/Array2D.cs | 16 +- .../General/ArrayReverse.cs | 21 +- .../General/BasicMath/Abs.cs | 5 +- .../General/BasicMath/ClampFloat.cs | 8 +- .../BasicMath/ModuloPowerOfTwoConstant.cs | 7 +- .../BasicMath/ModuloPowerOfTwoVariable.cs | 7 +- .../General/BasicMath/Pow.cs | 6 +- .../General/BasicMath/Round.cs | 11 +- .../General/CopyBuffers.cs | 2 - .../General/PixelConversion/ITestPixel.cs | 9 +- .../PixelConversion_ConvertFromRgba32.cs | 121 ++--- .../PixelConversion_ConvertFromVector4.cs | 19 +- .../PixelConversion_ConvertToRgba32.cs | 13 +- ...vertToRgba32_AsPartOfCompositeOperation.cs | 9 +- .../PixelConversion_ConvertToVector4.cs | 9 +- ...ertToVector4_AsPartOfCompositeOperation.cs | 9 +- .../PixelConversion_Rgba32_To_Argb32.cs | 12 +- .../PixelConversion_Rgba32_To_Bgra32.cs | 84 +-- .../General/PixelConversion/TestArgb.cs | 14 +- .../General/PixelConversion/TestRgba.cs | 16 +- .../General/StructCasting.cs | 5 +- .../General/Vector4Constants.cs | 22 +- .../General/Vectorization/BitwiseOrUint32.cs | 7 +- .../General/Vectorization/DivFloat.cs | 5 +- .../General/Vectorization/DivUInt32.cs | 5 +- .../General/Vectorization/Divide.cs | 9 +- .../General/Vectorization/MulFloat.cs | 3 + .../General/Vectorization/MulUInt32.cs | 3 + .../General/Vectorization/Multiply.cs | 7 +- .../General/Vectorization/Premultiply.cs | 7 +- .../Vectorization/ReinterpretUInt32AsFloat.cs | 17 +- .../Vectorization/SIMDBenchmarkBase.cs | 7 +- .../General/Vectorization/UInt32ToSingle.cs | 10 +- .../General/Vectorization/VectorFetching.cs | 7 +- .../Vectorization/WidenBytesToUInt32.cs | 7 +- tests/ImageSharp.Benchmarks/Samplers/Crop.cs | 10 +- .../Samplers/DetectEdges.cs | 7 +- .../ImageSharp.Benchmarks/Samplers/Diffuse.cs | 11 +- .../Samplers/GaussianBlur.cs | 3 + .../ImageSharp.Benchmarks/Samplers/Resize.cs | 39 +- .../ImageSharp.Benchmarks/Samplers/Rotate.cs | 48 +- tests/ImageSharp.Benchmarks/Samplers/Skew.cs | 48 +- .../ImageSharp.Sandbox46.csproj | 4 + tests/ImageSharp.Sandbox46/Program.cs | 4 +- .../Advanced/AdvancedImageExtensionsTests.cs | 15 +- .../Color/ColorTests.CastTo.cs | 4 +- tests/ImageSharp.Tests/Color/ColorTests.cs | 12 +- .../Color/ReferencePalette.cs | 6 +- .../Colorspaces/CieLabTests.cs | 10 +- .../CieXyChromaticityCoordinatesTests.cs | 10 +- .../ApproximateColorspaceComparer.cs | 10 +- .../CieLchAndCieXyyConversionTests.cs | 5 +- .../CieLchuvAndCieLuvConversionTests.cs | 5 +- .../CieLuvAndCieXyyConversionTests.cs | 5 +- .../Conversion/CieLuvAndHslConversionTests.cs | 5 +- .../Conversion/CieLuvAndHsvConversionTests.cs | 5 +- .../CieLuvAndHunterLabConversionTests.cs | 5 +- .../CieLuvAndLinearRgbConversionTests.cs | 5 +- .../Conversion/CieLuvAndLmsConversionTests.cs | 5 +- .../Conversion/CieLuvAndRgbConversionTests.cs | 5 +- .../CieLuvAndYCbCrConversionTests.cs | 5 +- .../Conversion/CieXyyAndHslConversionTests.cs | 7 +- .../Conversion/CieXyyAndHsvConversionTests.cs | 5 +- .../CieXyyAndHunterLabConversionTests.cs | 7 +- .../CieXyyAndLinearRgbConversionTests.cs | 5 +- .../Conversion/CieXyyAndLmsConversionTests.cs | 7 +- .../Conversion/CieXyyAndRgbConversionTests.cs | 7 +- .../CieXyyAndYCbCrConversionTests.cs | 7 +- .../CieXyzAndCieLchConversionTests.cs | 7 +- .../CieXyzAndCieLchuvConversionTests.cs | 7 +- .../Conversion/CieXyzAndHslConversionTests.cs | 5 +- .../Conversion/CieXyzAndHsvConversionTests.cs | 7 +- .../CieXyzAndYCbCrConversionTests.cs | 7 +- .../Conversion/RgbAndHslConversionTest.cs | 1 - .../VonKriesChromaticAdaptationTests.cs | 6 +- .../Colorspaces/HunterLabTests.cs | 8 +- .../ImageSharp.Tests/Colorspaces/LmsTests.cs | 16 +- .../Colorspaces/StringRepresentationTests.cs | 94 ++-- .../Common/EncoderExtensionsTests.cs | 4 +- .../ImageSharp.Tests/Common/SimdUtilsTests.cs | 33 +- .../Common/StreamExtensionsTests.cs | 17 +- tests/ImageSharp.Tests/Common/Tuple8.cs | 7 +- tests/ImageSharp.Tests/ConfigurationTests.cs | 12 +- .../Drawing/DrawImageTests.cs | 19 +- tests/ImageSharp.Tests/FileTestBase.cs | 36 +- .../Formats/Bmp/BmpDecoderTests.cs | 22 +- .../Formats/Bmp/BmpEncoderTests.cs | 22 +- .../Formats/Bmp/BmpMetadataTests.cs | 1 - .../Formats/Gif/GifEncoderTests.cs | 8 +- .../Formats/Gif/GifMetadataTests.cs | 4 +- .../Formats/ImageFormatManagerTests.cs | 4 +- .../Jpg/Block8x8FTests.CopyToBufferArea.cs | 11 +- .../Formats/Jpg/Block8x8FTests.cs | 42 +- .../Formats/Jpg/Block8x8Tests.cs | 4 +- .../ImageSharp.Tests/Formats/Jpg/DCTTests.cs | 43 +- .../Formats/Jpg/JpegColorConverterTests.cs | 19 +- .../Formats/Jpg/JpegDecoderTests.Baseline.cs | 3 +- .../Formats/Jpg/JpegDecoderTests.Images.cs | 5 +- .../Formats/Jpg/JpegDecoderTests.Metadata.cs | 23 +- .../Jpg/JpegDecoderTests.Progressive.cs | 4 +- .../Formats/Jpg/JpegDecoderTests.cs | 9 +- .../Formats/Jpg/JpegEncoderTests.cs | 19 +- .../Jpg/JpegImagePostProcessorTests.cs | 4 +- .../Formats/Jpg/LibJpegToolsTests.cs | 10 +- .../Formats/Jpg/ParseStreamTests.cs | 2 + ...plementationsTests.FastFloatingPointDCT.cs | 6 +- ...ImplementationsTests.StandardIntegerDCT.cs | 4 +- .../Formats/Jpg/SpectralJpegTests.cs | 10 +- .../Formats/Jpg/Utils/JpegFixture.cs | 33 +- .../Jpg/Utils/LibJpegTools.ComponentData.cs | 55 +- .../Jpg/Utils/LibJpegTools.SpectralData.cs | 25 +- .../Formats/Jpg/Utils/LibJpegTools.cs | 5 +- .../ReferenceImplementations.AccurateDCT.cs | 48 +- ...nceImplementations.GT_FloatingPoint_DCT.cs | 32 +- ...ceImplementations.LLM_FloatingPoint_DCT.cs | 294 ++++++----- ...renceImplementations.StandardIntegerDCT.cs | 154 +++--- .../Jpg/Utils/ReferenceImplementations.cs | 21 +- .../Formats/Jpg/Utils/VerifyJpeg.cs | 5 +- .../Formats/Png/PngChunkTypeTests.cs | 7 +- .../Formats/Png/PngDecoderTests.Chunks.cs | 15 +- .../Formats/Png/PngDecoderTests.cs | 5 +- .../Formats/Png/PngEncoderTests.cs | 52 +- .../Formats/Png/PngMetadataTests.cs | 9 +- .../Formats/Png/PngSmokeTests.cs | 145 +++--- .../Formats/Tga/TgaDecoderTests.cs | 3 +- .../Formats/Tga/TgaEncoderTests.cs | 13 +- .../Formats/Tga/TgaFileHeaderTests.cs | 5 +- .../Formats/Tga/TgaTestUtils.cs | 14 +- tests/ImageSharp.Tests/GlobalSuppressions.cs | 6 +- .../ImageSharp.Tests/GraphicsOptionsTests.cs | 6 +- .../Helpers/ParallelHelperTests.cs | 16 +- .../Helpers/TolerantMathTests.cs | 4 +- .../Helpers/Vector4UtilsTests.cs | 20 +- .../IO/DoubleBufferedStreamReaderTests.cs | 1 - ...lFileSystem.cs => LocalFileSystemTests.cs} | 0 .../ImageSharp.Tests/Image/ImageCloneTests.cs | 11 +- .../ImageFrameCollectionTests.Generic.cs | 46 +- .../ImageFrameCollectionTests.NonGeneric.cs | 14 +- .../Image/ImageFrameCollectionTests.cs | 6 +- .../ImageSharp.Tests/Image/ImageSaveTests.cs | 34 +- .../Image/ImageTests.DetectFormat.cs | 2 +- .../Image/ImageTests.ImageLoadTestBase.cs | 19 +- ...d_FileSystemPath_PassLocalConfiguration.cs | 6 +- ..._FileSystemPath_UseDefaultConfiguration.cs | 18 +- ...s.Load_FromBytes_UseGlobalConfiguration.cs | 9 +- ...Load_FromStream_UseDefaultConfiguration.cs | 18 +- .../ImageSharp.Tests/Image/ImageTests.Save.cs | 3 +- .../Image/ImageTests.WrapMemory.cs | 3 +- tests/ImageSharp.Tests/Image/ImageTests.cs | 8 +- tests/ImageSharp.Tests/Issues/Issue594.cs | 201 ++++---- .../ImageSharp.Tests/Memory/Buffer2DTests.cs | 3 +- .../Memory/BufferAreaTests.cs | 8 +- .../Memory/MemorySourceTests.cs | 6 +- tests/ImageSharp.Tests/Memory/TestStructs.cs | 19 +- .../Profiles/Exif/ExifProfileTests.cs | 19 +- .../Exif/ExifTagDescriptionAttributeTests.cs | 2 +- .../Profiles/Exif/Values/ExifValuesTests.cs | 3 + ...esTests.cs => IccDataReaderCurvesTests.cs} | 14 +- ...r.LutTests.cs => IccDataReaderLutTests.cs} | 14 +- ...ixTests.cs => IccDataReaderMatrixTests.cs} | 6 +- ... IccDataReaderMultiProcessElementTests.cs} | 18 +- ....cs => IccDataReaderNonPrimitivesTests.cs} | 22 +- ...sts.cs => IccDataReaderPrimitivesTests.cs} | 16 +- ...s.cs => IccDataReaderTagDataEntryTests.cs} | 2 +- ...esTests.cs => IccDataWriterCurvesTests.cs} | 14 +- ...r.LutTests.cs => IccDataWriterLutTests.cs} | 14 +- .../ICC/DataWriter/IccDataWriterLutTests1.cs | 88 ++++ .../ICC/DataWriter/IccDataWriterLutTests2.cs | 88 ++++ ...ixTests.cs => IccDataWriterMatrixTests.cs} | 12 +- ... IccDataWriterMultiProcessElementTests.cs} | 18 +- ....cs => IccDataWriterNonPrimitivesTests.cs} | 20 +- ...sts.cs => IccDataWriterPrimitivesTests.cs} | 18 +- ...s.cs => IccDataWriterTagDataEntryTests.cs} | 70 +-- .../ICC/DataWriter/IccDataWriterTests.cs | 18 +- .../Metadata/Profiles/ICC/IccReaderTests.cs | 7 +- .../Metadata/Profiles/ICC/IccWriterTests.cs | 4 +- .../PixelFormats/Argb32Tests.cs | 4 +- .../PixelFormats/Bgr24Tests.cs | 3 +- .../PixelFormats/Bgr565Tests.cs | 7 +- .../PixelFormats/Bgra32Tests.cs | 3 +- .../PixelFormats/Bgra5551Tests.cs | 12 +- .../PixelFormats/Byte4Tests.cs | 12 +- .../PixelFormats/HalfSingleTests.cs | 6 +- .../PixelFormats/HalfVector2Tests.cs | 4 +- .../PixelFormats/HalfVector4Tests.cs | 6 +- .../ImageSharp.Tests/PixelFormats/L8Tests.cs | 12 +- .../PixelFormats/La16Tests.cs | 10 +- .../PixelFormats/NormalizedByte4Tests.cs | 10 +- .../PixelFormats/NormalizedShort2Tests.cs | 11 +- .../PixelFormats/NormalizedShort4Tests.cs | 10 +- ...sTests.Blender.cs => PixelBlenderTests.cs} | 9 +- .../PorterDuffCompositorTests.cs | 7 +- .../PixelBlenders/PorterDuffFunctionsTests.cs | 119 ++--- ...l.cs => PorterDuffFunctionsTestsTPixel.cs} | 111 ++-- ...ConverterTests.ReferenceImplementations.cs | 22 +- .../PixelFormats/PixelConverterTests.cs | 5 +- ...PixelConversionModifiersExtensionsTests.cs | 13 +- ...elOperationsTests.Argb32OperationsTests.cs | 5 +- ...PixelOperationsTests.L16OperationsTests.cs | 3 +- ...ixelOperationsTests.La16OperationsTests.cs | 1 - ...ixelOperationsTests.La32OperationsTests.cs | 1 - .../PixelOperations/PixelOperationsTests.cs | 204 +++----- .../PixelFormats/Rg32Tests.cs | 6 +- .../PixelFormats/Rgb48Tests.cs | 6 +- .../PixelFormats/Rgba1010102Tests.cs | 8 +- .../PixelFormats/Rgba32Tests.cs | 9 +- .../PixelFormats/Rgba64Tests.cs | 20 +- .../PixelFormats/Short2Tests.cs | 21 +- .../PixelFormats/Short4Tests.cs | 12 +- .../Primitives/ColorMatrixTests.cs | 25 +- .../Binarization/BinaryDitherTest.cs | 6 +- .../Binarization/OrderedDitherFactoryTests.cs | 7 +- .../Processing/Convolution/DetectEdgesTest.cs | 29 +- .../Processors/LaplacianKernelFactoryTests.cs | 14 +- .../Processing/Dithering/DitherTest.cs | 22 +- .../Processing/Effects/BackgroundColorTest.cs | 10 +- .../Processing/Effects/OilPaintTest.cs | 3 +- .../Processing/FakeImageOperationsProvider.cs | 11 +- .../Processing/Filters/ColorBlindnessTest.cs | 22 +- .../Processing/Filters/GrayscaleTest.cs | 7 +- .../Processing/ImageOperationTests.cs | 12 +- .../HistogramEqualizationTests.cs | 5 +- .../Processing/Overlays/GlowTest.cs | 10 +- .../Processing/Overlays/VignetteTest.cs | 10 +- .../Binarization/BinaryDitherTests.cs | 10 +- .../Binarization/BinaryThresholdTest.cs | 11 +- .../Basic1ParameterConvolutionTests.cs | 12 +- .../Processors/Convolution/BokehBlurTest.cs | 15 +- .../Processors/Convolution/DetectEdgesTest.cs | 10 +- .../Processors/Dithering/DitherTests.cs | 17 +- .../Processors/Effects/BackgroundColorTest.cs | 8 +- .../Processors/Effects/OilPaintTest.cs | 7 +- .../Processors/Effects/PixelateTest.cs | 2 +- .../Processors/Filters/BlackWhiteTest.cs | 2 +- .../Processors/Filters/BrightnessTest.cs | 8 +- .../Processors/Filters/ColorBlindnessTest.cs | 2 +- .../Processors/Filters/ContrastTest.cs | 8 +- .../Processors/Filters/FilterTest.cs | 9 +- .../Processors/Filters/GrayscaleTest.cs | 7 +- .../Processing/Processors/Filters/HueTest.cs | 8 +- .../Processors/Filters/InvertTest.cs | 2 +- .../Processors/Filters/KodachromeTest.cs | 2 +- .../Processors/Filters/LightnessTest.cs | 4 +- .../Processors/Filters/LomographTest.cs | 2 +- .../Processors/Filters/OpacityTest.cs | 10 +- .../Processors/Filters/PolaroidTest.cs | 2 +- .../Processors/Filters/SaturateTest.cs | 8 +- .../Processors/Filters/SepiaTest.cs | 2 +- .../Processors/Transforms/AutoOrientTests.cs | 7 +- .../Processors/Transforms/CropTest.cs | 4 +- .../Processors/Transforms/FlipTests.cs | 15 +- .../Processors/Transforms/ResamplerTests.cs | 4 +- ...ResizeKernelMapTests.ReferenceKernelMap.cs | 4 +- .../Transforms/ResizeKernelMapTests.cs | 18 +- .../Processors/Transforms/ResizeTests.cs | 48 +- .../Processors/Transforms/RotateFlipTests.cs | 4 +- .../Processors/Transforms/RotateTests.cs | 8 +- .../Processors/Transforms/SkewTests.cs | 2 +- .../Transforms/AffineTransformTests.cs | 33 +- .../Processing/Transforms/FlipTests.cs | 3 +- .../Transforms/ProjectiveTransformTests.cs | 10 +- .../Transforms/TransformBuilderTestBase.cs | 8 +- .../JpegProfilingBenchmarks.cs | 10 +- .../LoadResizeSaveProfilingBenchmarks.cs | 8 +- .../ProfilingBenchmarks/ProfilingSetup.cs | 5 +- .../ResizeProfilingBenchmarks.cs | 8 +- .../Quantization/WuQuantizerTests.cs | 7 +- .../TestDataIcc/IccTestDataArray.cs | 34 +- .../TestDataIcc/IccTestDataCurves.cs | 154 ++---- .../TestDataIcc/IccTestDataLut.cs | 101 ++-- .../TestDataIcc/IccTestDataMatrix.cs | 40 +- .../IccTestDataMultiProcessElements.cs | 44 +- .../TestDataIcc/IccTestDataNonPrimitives.cs | 132 +++-- .../TestDataIcc/IccTestDataPrimitives.cs | 11 +- .../TestDataIcc/IccTestDataProfiles.cs | 43 +- .../TestDataIcc/IccTestDataTagDataEntry.cs | 486 +++++++----------- tests/ImageSharp.Tests/TestFile.cs | 12 +- .../{TestFont.cs => TestFontUtilities.cs} | 9 +- tests/ImageSharp.Tests/TestFormat.cs | 131 +++-- tests/ImageSharp.Tests/TestImages.cs | 48 +- .../TestUtilities/ApproximateFloatComparer.cs | 8 +- .../TestUtilities/ArrayHelper.cs | 4 +- .../Attributes/GroupOutputAttribute.cs | 7 +- .../Attributes/ImageDataAttributeBase.cs | 24 +- ...tribute.cs => WithBlankImagesAttribute.cs} | 3 +- .../WithSolidFilledImagesAttribute.cs | 12 +- .../WithTestPatternImageAttribute.cs | 6 +- .../ImageComparison/ExactImageComparer.cs | 4 +- ...ImageDifferenceIsOverThresholdException.cs | 6 +- .../ImageDimensionsMismatchException.cs | 1 + .../Exceptions/ImagesSimilarityException.cs | 5 +- .../ImageComparison/ImageComparer.cs | 17 +- .../ImageComparison/ImageSimilarityReport.cs | 10 +- .../ImageComparison/PixelDifference.cs | 13 +- .../ImageComparison/TolerantImageComparer.cs | 4 +- .../ImageProviders/BlankProvider.cs | 5 +- .../ImageProviders/FileProvider.cs | 12 +- .../ImageProviders/SolidProvider.cs | 3 - .../ImageProviders/TestImageProvider.cs | 22 +- .../ImageProviders/TestPatternProvider.cs | 44 +- .../TestUtilities/ImagingTestCaseUtility.cs | 37 +- .../TestUtilities/MeasureFixture.cs | 6 +- .../TestUtilities/PixelTypes.cs | 7 +- .../ReferenceCodecs/MagickReferenceDecoder.cs | 4 +- .../ReferenceCodecs/SystemDrawingBridge.cs | 5 +- .../SystemDrawingReferenceDecoder.cs | 4 +- .../TestUtilities/TestEnvironment.Formats.cs | 3 +- .../TestUtilities/TestEnvironment.cs | 14 +- .../TestUtilities/TestImageExtensions.cs | 67 ++- .../TestUtilities/TestMemoryAllocator.cs | 12 +- .../TestUtilities/TestMemoryManager.cs | 9 +- .../TestUtilities/TestPixel.cs | 9 +- .../TestUtilities/TestUtils.cs | 16 +- .../TestUtilities/TestVector4.cs | 5 +- .../TestUtilities/Tests/GroupOutputTests.cs | 7 +- .../TestUtilities/Tests/ImageComparerTests.cs | 25 +- .../Tests/MagickReferenceCodecTests.cs | 6 +- .../Tests/ReferenceDecoderBenchmarks.cs | 3 +- .../Tests/SystemDrawingReferenceCodecTests.cs | 8 +- .../Tests/TestEnvironmentTests.cs | 23 +- .../Tests/TestImageExtensionsTests.cs | 5 +- .../Tests/TestImageProviderTests.cs | 27 +- .../Tests/TestUtilityExtensionsTests.cs | 3 +- tests/ImageSharp.Tests/VectorAssert.cs | 26 +- 365 files changed, 3606 insertions(+), 3320 deletions(-) rename tests/ImageSharp.Tests/IO/{LocalFileSystem.cs => LocalFileSystemTests.cs} (100%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.CurvesTests.cs => IccDataReaderCurvesTests.cs} (86%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.LutTests.cs => IccDataReaderLutTests.cs} (86%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.MatrixTests.cs => IccDataReaderMatrixTests.cs} (86%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.MultiProcessElementTests.cs => IccDataReaderMultiProcessElementTests.cs} (66%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.NonPrimitivesTests.cs => IccDataReaderNonPrimitivesTests.cs} (85%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.PrimitivesTests.cs => IccDataReaderPrimitivesTests.cs} (82%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/{IccDataReader.TagDataEntryTests.cs => IccDataReaderTagDataEntryTests.cs} (99%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.CurvesTests.cs => IccDataWriterCurvesTests.cs} (87%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.LutTests.cs => IccDataWriterLutTests.cs} (86%) create mode 100644 tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests1.cs create mode 100644 tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests2.cs rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.MatrixTests.cs => IccDataWriterMatrixTests.cs} (88%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.MultiProcessElementTests.cs => IccDataWriterMultiProcessElementTests.cs} (66%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.NonPrimitivesTests.cs => IccDataWriterNonPrimitivesTests.cs} (87%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.PrimitivesTests.cs => IccDataWriterPrimitivesTests.cs} (86%) rename tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/{IccDataWriter.TagDataEntryTests.cs => IccDataWriterTagDataEntryTests.cs} (88%) rename tests/ImageSharp.Tests/PixelFormats/{PixelOperationsTests.Blender.cs => PixelBlenderTests.cs} (98%) rename tests/ImageSharp.Tests/PixelFormats/PixelBlenders/{PorterDuffFunctionsTests_TPixel.cs => PorterDuffFunctionsTestsTPixel.cs} (80%) rename tests/ImageSharp.Tests/{TestFont.cs => TestFontUtilities.cs} (91%) rename tests/ImageSharp.Tests/TestUtilities/Attributes/{WithBlankImageAttribute.cs => WithBlankImagesAttribute.cs} (99%) diff --git a/Directory.Build.props b/Directory.Build.props index 346da14be8..cd2f7311ef 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -102,8 +102,7 @@ - - + diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 5e3f9b0618..bcf444c75b 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -27,9 +27,6 @@ - - - diff --git a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs index a0ee1d5e50..a30e45ddeb 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs @@ -153,7 +153,7 @@ public IccChromaticityTagDataEntry ReadChromaticityTagDataEntry() else { // The type is not know, so the values need be read - var values = new double[channelCount][]; + double[][] values = new double[channelCount][]; for (int i = 0; i < channelCount; i++) { values[i] = new double[] { this.ReadUFix16(), this.ReadUFix16() }; @@ -208,7 +208,7 @@ public IccCurveTagDataEntry ReadCurveTagDataEntry() return new IccCurveTagDataEntry(this.ReadUFix8()); } - var cdata = new float[pointCount]; + float[] cdata = new float[pointCount]; for (int i = 0; i < pointCount; i++) { cdata[i] = this.ReadUInt16() / 65535f; @@ -264,7 +264,7 @@ public IccLut16TagDataEntry ReadLut16TagDataEntry() // Input LUT var inValues = new IccLut[inChCount]; - var gridPointCount = new byte[inChCount]; + byte[] gridPointCount = new byte[inChCount]; for (int i = 0; i < inChCount; i++) { inValues[i] = this.ReadLut16(inTableCount); @@ -299,7 +299,7 @@ public IccLut8TagDataEntry ReadLut8TagDataEntry() // Input LUT var inValues = new IccLut[inChCount]; - var gridPointCount = new byte[inChCount]; + byte[] gridPointCount = new byte[inChCount]; for (int i = 0; i < inChCount; i++) { inValues[i] = this.ReadLut8(); @@ -464,8 +464,8 @@ public IccMultiLocalizedUnicodeTagDataEntry ReadMultiLocalizedUnicodeTagDataEntr var text = new IccLocalizedString[recordCount]; var culture = new CultureInfo[recordCount]; - var length = new uint[recordCount]; - var offset = new uint[recordCount]; + uint[] length = new uint[recordCount]; + uint[] offset = new uint[recordCount]; for (int i = 0; i < recordCount; i++) { @@ -627,7 +627,7 @@ public IccResponseCurveSet16TagDataEntry ReadResponseCurveSet16TagDataEntry() ushort channelCount = this.ReadUInt16(); ushort measurementCount = this.ReadUInt16(); - var offset = new uint[measurementCount]; + uint[] offset = new uint[measurementCount]; for (int i = 0; i < measurementCount; i++) { offset[i] = this.ReadUInt32(); @@ -651,7 +651,7 @@ public IccResponseCurveSet16TagDataEntry ReadResponseCurveSet16TagDataEntry() public IccFix16ArrayTagDataEntry ReadFix16ArrayTagDataEntry(uint size) { uint count = (size - 8) / 4; - var arrayData = new float[count]; + float[] arrayData = new float[count]; for (int i = 0; i < count; i++) { arrayData[i] = this.ReadFix16() / 256f; @@ -687,7 +687,7 @@ public IccTextTagDataEntry ReadTextTagDataEntry(uint size) public IccUFix16ArrayTagDataEntry ReadUFix16ArrayTagDataEntry(uint size) { uint count = (size - 8) / 4; - var arrayData = new float[count]; + float[] arrayData = new float[count]; for (int i = 0; i < count; i++) { arrayData[i] = this.ReadUFix16(); @@ -704,7 +704,7 @@ public IccUFix16ArrayTagDataEntry ReadUFix16ArrayTagDataEntry(uint size) public IccUInt16ArrayTagDataEntry ReadUInt16ArrayTagDataEntry(uint size) { uint count = (size - 8) / 2; - var arrayData = new ushort[count]; + ushort[] arrayData = new ushort[count]; for (int i = 0; i < count; i++) { arrayData[i] = this.ReadUInt16(); @@ -721,7 +721,7 @@ public IccUInt16ArrayTagDataEntry ReadUInt16ArrayTagDataEntry(uint size) public IccUInt32ArrayTagDataEntry ReadUInt32ArrayTagDataEntry(uint size) { uint count = (size - 8) / 4; - var arrayData = new uint[count]; + uint[] arrayData = new uint[count]; for (int i = 0; i < count; i++) { arrayData[i] = this.ReadUInt32(); @@ -738,7 +738,7 @@ public IccUInt32ArrayTagDataEntry ReadUInt32ArrayTagDataEntry(uint size) public IccUInt64ArrayTagDataEntry ReadUInt64ArrayTagDataEntry(uint size) { uint count = (size - 8) / 8; - var arrayData = new ulong[count]; + ulong[] arrayData = new ulong[count]; for (int i = 0; i < count; i++) { arrayData[i] = this.ReadUInt64(); @@ -878,14 +878,14 @@ public IccScreeningTagDataEntry ReadScreeningTagDataEntry() public IccUcrBgTagDataEntry ReadUcrBgTagDataEntry(uint size) { uint ucrCount = this.ReadUInt32(); - var ucrCurve = new ushort[ucrCount]; + ushort[] ucrCurve = new ushort[ucrCount]; for (int i = 0; i < ucrCurve.Length; i++) { ucrCurve[i] = this.ReadUInt16(); } uint bgCount = this.ReadUInt32(); - var bgCurve = new ushort[bgCount]; + ushort[] bgCurve = new ushort[bgCount]; for (int i = 0; i < bgCurve.Length; i++) { bgCurve[i] = this.ReadUInt16(); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs index 88e3c4cae2..0dfaef7d40 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.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. using System; diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs index f8bf3f0423..929a70ed86 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.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. using System; diff --git a/tests/ImageSharp.Benchmarks/Codecs/DecodeTga.cs b/tests/ImageSharp.Benchmarks/Codecs/DecodeTga.cs index 527b6bb8bc..3c8f45edb7 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/DecodeTga.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/DecodeTga.cs @@ -18,7 +18,9 @@ namespace SixLabors.ImageSharp.Benchmarks.Codecs public class DecodeTga : BenchmarkBase { private string TestImageFullPath => Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, this.TestImage); + private readonly PfimConfig pfimConfig = new PfimConfig(allocator: new PfimAllocator()); + private byte[] data; [Params(TestImages.Tga.Bit24)] @@ -77,15 +79,16 @@ public void Return(byte[] data) public int Rented => this.rented; } - // RESULTS (07/01/2020) - //| Method | Runtime | TestImage | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated | - //|------------------ |-------------- |-------------------- |-------------:|-------------:|-----------:|------:|-------:|------:|------:|----------:| - //| 'ImageMagick Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 1,778.965 us | 1,711.088 us | 93.7905 us | 1.000 | 1.9531 | - | - | 13668 B | - //| 'ImageSharp Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 38.659 us | 6.886 us | 0.3774 us | 0.022 | 0.3052 | - | - | 1316 B | - //| 'Pfim Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 6.752 us | 10.268 us | 0.5628 us | 0.004 | 0.0687 | - | - | 313 B | - //| | | | | | | | | | | | - //| 'ImageMagick Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 1,407.585 us | 124.215 us | 6.8087 us | 1.000 | 1.9531 | - | - | 13307 B | - //| 'ImageSharp Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 17.958 us | 9.352 us | 0.5126 us | 0.013 | 0.2747 | - | - | 1256 B | - //| 'Pfim Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 5.645 us | 2.279 us | 0.1249 us | 0.004 | 0.0610 | - | - | 280 B | + /* RESULTS (07/01/2020) + | Method | Runtime | TestImage | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated | + |------------------ |-------------- |-------------------- |-------------:|-------------:|-----------:|------:|-------:|------:|------:|----------:| + | 'ImageMagick Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 1,778.965 us | 1,711.088 us | 93.7905 us | 1.000 | 1.9531 | - | - | 13668 B | + | 'ImageSharp Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 38.659 us | 6.886 us | 0.3774 us | 0.022 | 0.3052 | - | - | 1316 B | + | 'Pfim Tga' | .NET 4.7.2 | Tga/targa_24bit.tga | 6.752 us | 10.268 us | 0.5628 us | 0.004 | 0.0687 | - | - | 313 B | + | | | | | | | | | | | | + | 'ImageMagick Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 1,407.585 us | 124.215 us | 6.8087 us | 1.000 | 1.9531 | - | - | 13307 B | + | 'ImageSharp Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 17.958 us | 9.352 us | 0.5126 us | 0.013 | 0.2747 | - | - | 1256 B | + | 'Pfim Tga' | .NET Core 2.1 | Tga/targa_24bit.tga | 5.645 us | 2.279 us | 0.1249 us | 0.004 | 0.0610 | - | - | 280 B | + */ } } diff --git a/tests/ImageSharp.Benchmarks/Codecs/EncodeBmpMultiple.cs b/tests/ImageSharp.Benchmarks/Codecs/EncodeBmpMultiple.cs index 379f8aa8bf..58e3e01e39 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/EncodeBmpMultiple.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/EncodeBmpMultiple.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. using System.Collections.Generic; @@ -16,13 +16,21 @@ public class EncodeBmpMultiple : MultiImageBenchmarkBase.WithImagesPreloaded [Benchmark(Description = "EncodeBmpMultiple - ImageSharp")] public void EncodeBmpImageSharp() { - this.ForEachImageSharpImage((img, ms) => { img.Save(ms, new BmpEncoder()); return null; }); + this.ForEachImageSharpImage((img, ms) => + { + img.Save(ms, new BmpEncoder()); + return null; + }); } [Benchmark(Baseline = true, Description = "EncodeBmpMultiple - System.Drawing")] public void EncodeBmpSystemDrawing() { - this.ForEachSystemDrawingImage((img, ms) => { img.Save(ms, ImageFormat.Bmp); return null; }); + this.ForEachSystemDrawingImage((img, ms) => + { + img.Save(ms, ImageFormat.Bmp); + return null; + }); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/EncodeGifMultiple.cs b/tests/ImageSharp.Benchmarks/Codecs/EncodeGifMultiple.cs index bf9627f4c1..4d93d89af2 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/EncodeGifMultiple.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/EncodeGifMultiple.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. using System.Collections.Generic; @@ -24,14 +24,19 @@ public void EncodeGifImageSharp() { // Try to get as close to System.Drawing's output as possible var options = new GifEncoder { Quantizer = new WebSafePaletteQuantizer(false) }; - img.Save(ms, options); return null; + img.Save(ms, options); + return null; }); } [Benchmark(Baseline = true, Description = "EncodeGifMultiple - System.Drawing")] public void EncodeGifSystemDrawing() { - this.ForEachSystemDrawingImage((img, ms) => { img.Save(ms, ImageFormat.Gif); return null; }); + this.ForEachSystemDrawingImage((img, ms) => + { + img.Save(ms, ImageFormat.Gif); + return null; + }); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/EncodeTga.cs b/tests/ImageSharp.Benchmarks/Codecs/EncodeTga.cs index ddcbec218e..7100ca6b7f 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/EncodeTga.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/EncodeTga.cs @@ -28,7 +28,7 @@ public void ReadImages() { if (this.tgaCore == null) { - this.tgaCore = Image.Load(TestImageFullPath); + this.tgaCore = Image.Load(this.TestImageFullPath); this.tgaMagick = new MagickImage(this.TestImageFullPath); } } diff --git a/tests/ImageSharp.Benchmarks/Codecs/ImageBenchmarkTests.cs b/tests/ImageSharp.Benchmarks/Codecs/ImageBenchmarkTests.cs index 7c3da90db6..4a9d709ee7 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/ImageBenchmarkTests.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/ImageBenchmarkTests.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. // This file contains small, cheap and "unit test" benchmarks to test MultiImageBenchmarkBase. @@ -6,7 +6,6 @@ // Uncomment this to enable benchmark testing // #define TEST - #if TEST // ReSharper disable InconsistentNaming @@ -76,4 +75,4 @@ public void Run() } } -#endif \ No newline at end of file +#endif diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo1x1.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo1x1.cs index bf9b1af338..21d114be38 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo1x1.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo1x1.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. using System; @@ -9,8 +9,8 @@ using SixLabors.ImageSharp.Formats.Jpeg.Components; using SixLabors.ImageSharp.Memory; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg.BlockOperations { public class Block8x8F_CopyTo1x1 @@ -130,4 +130,4 @@ public void UseVector8_V2() // Conclusion: // Doesn't worth to bother with this } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo2x2.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo2x2.cs index 3d9b54dffa..76068ab432 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo2x2.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_CopyTo2x2.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. using System.Numerics; @@ -8,8 +8,8 @@ using SixLabors.ImageSharp.Formats.Jpeg.Components; using SixLabors.ImageSharp.Memory; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg.BlockOperations { public class Block8x8F_CopyTo2x2 @@ -335,7 +335,6 @@ private static void WidenCopyImpl2x2_Vector4_SafeRightCorner(ref Block8x8F src, Unsafe.Add(ref dBottomLeft, 7) = wRight; } - [Benchmark] public void UseVector4_V2() { @@ -409,4 +408,4 @@ private static void WidenCopyImpl2x2_Vector4_V2(ref Block8x8F src, ref Vector2 d // UseVector4_SafeRightCorner | 58.97 ns | 0.4152 ns | 0.3884 ns | 0.64 | 0.02 | // UseVector4_V2 | 41.88 ns | 0.3531 ns | 0.3303 ns | 0.45 | 0.01 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_DivideRound.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_DivideRound.cs index 15a3c7eb7d..05b7156ffc 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_DivideRound.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_DivideRound.cs @@ -9,7 +9,6 @@ using SixLabors.ImageSharp.Formats.Jpeg.Components; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg.BlockOperations { /// @@ -32,7 +31,7 @@ public void Setup() { for (int i = 0; i < Block8x8F.Size; i++) { - this.inputDividend[i] = i*44.8f; + this.inputDividend[i] = i * 44.8f; this.inputDivisor[i] = 100 - i; } } @@ -54,10 +53,11 @@ public int ByRationalIntegers() sum = 0; for (int i = 0; i < Block8x8F.Size; i++) { - int a = (int) pDividend[i]; - int b = (int) pDivisor; + int a = (int)pDividend[i]; + int b = (int)pDivisor; result[i] = RationalRound(a, b); } + for (int i = 0; i < Block8x8F.Size; i++) { sum += result[i]; @@ -83,13 +83,15 @@ public int BySystemMathRound() for (int i = 0; i < Block8x8F.Size; i++) { double value = pDividend[i] / pDivisor[i]; - pDividend[i] = (float) System.Math.Round(value); + pDividend[i] = (float)System.Math.Round(value); } + for (int i = 0; i < Block8x8F.Size; i++) { - sum += (int) pDividend[i]; + sum += (int)pDividend[i]; } } + return sum; } @@ -111,6 +113,7 @@ public int BySimdMagic() sum += (int)pDividend[i]; } } + return sum; } @@ -138,10 +141,10 @@ private static void DivideRoundAll(ref Block8x8F a, ref Block8x8F b) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector4 DivideRound(Vector4 dividend, Vector4 divisor) { - Vector4 sign = Vector4.Min(dividend, Vector4.One); + var sign = Vector4.Min(dividend, Vector4.One); sign = Vector4.Max(sign, MinusOne); - return dividend / divisor + sign * Half; + return (dividend / divisor) + (sign * Half); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_LoadFromInt16.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_LoadFromInt16.cs index 29ee402a00..5dac391165 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_LoadFromInt16.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_LoadFromInt16.cs @@ -1,8 +1,6 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.Numerics; @@ -10,6 +8,7 @@ using SixLabors.ImageSharp.Formats.Jpeg.Components; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg.BlockOperations { public class Block8x8F_LoadFromInt16 @@ -50,4 +49,4 @@ public void ExtendedAvx2() // Scalar | 34.88 ns | 0.3296 ns | 0.3083 ns | 1.00 | // ExtendedAvx2 | 21.58 ns | 0.2125 ns | 0.1884 ns | 0.62 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_Round.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_Round.cs index 09e25827c7..bf6ea3dacf 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_Round.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_Round.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.Numerics; using System.Runtime.CompilerServices; @@ -11,6 +9,7 @@ using SixLabors.ImageSharp.Formats.Jpeg.Components; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg.BlockOperations { public class Block8x8F_Round diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpegParseStreamOnly.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpegParseStreamOnly.cs index f40c15cc14..d47edb645f 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpegParseStreamOnly.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpegParseStreamOnly.cs @@ -1,9 +1,10 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using BenchmarkDotNet.Attributes; using System.Drawing; using System.IO; +using BenchmarkDotNet.Attributes; + using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Tests; diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_Aggregate.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_Aggregate.cs index f8a7556ca5..06492bc92d 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_Aggregate.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_Aggregate.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. using System.Collections.Generic; @@ -10,8 +10,8 @@ using SixLabors.ImageSharp.Tests; using SDImage = System.Drawing.Image; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { /// @@ -45,4 +45,4 @@ public void SystemDrawing() this.ForEachStream(SDImage.FromStream); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs index 17ad79e585..96be94eba4 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs @@ -14,8 +14,8 @@ using SixLabors.ImageSharp.Tests; using CoreSize = SixLabors.Primitives.Size; using SDImage = System.Drawing.Image; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { /// @@ -35,10 +35,8 @@ public class ShortClr : Benchmarks.Config { public ShortClr() { - this.Add( - // Job.Default.With(ClrRuntime.Net472).WithLaunchCount(1).WithWarmupCount(2).WithIterationCount(3), - Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(2).WithIterationCount(3) - ); + // Job.Default.With(ClrRuntime.Net472).WithLaunchCount(1).WithWarmupCount(2).WithIterationCount(3), + this.Add(Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(2).WithIterationCount(3)); } } } @@ -50,18 +48,15 @@ public ShortClr() [Params( TestImages.Jpeg.BenchmarkSuite.Lake_Small444YCbCr, TestImages.Jpeg.BenchmarkSuite.BadRstProgressive518_Large444YCbCr, + /* The scaled result for the large image "ExifGetString750Transform_Huge420YCbCr" + is almost the same as the result for Jpeg420Exif, + which proves that the execution time for the most common YCbCr 420 path scales linearly. + TestImages.Jpeg.BenchmarkSuite.ExifGetString750Transform_Huge420YCbCr, + */ + TestImages.Jpeg.BenchmarkSuite.Jpeg420Exif_MidSizeYCbCr)] - // The scaled result for the large image "ExifGetString750Transform_Huge420YCbCr" - // is almost the same as the result for Jpeg420Exif, - // which proves that the execution time for the most common YCbCr 420 path scales linearly. - // - // TestImages.Jpeg.BenchmarkSuite.ExifGetString750Transform_Huge420YCbCr, - - TestImages.Jpeg.BenchmarkSuite.Jpeg420Exif_MidSizeYCbCr - )] public string TestImage { get; set; } - [GlobalSetup] public void ReadImages() { @@ -102,7 +97,7 @@ public CoreSize JpegImageSharp() // Frequency=2742191 Hz, Resolution=364.6719 ns, Timer=TSC // .NET Core SDK=2.1.403 // [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT - // + // // Method | TestImage | Mean | Error | StdDev | Scaled | ScaledSD | Gen 0 | Gen 1 | Gen 2 | Allocated | // ------------------------------- |-------------------------------------------- |-----------:|-----------:|----------:|-------:|---------:|----------:|---------:|---------:|------------:| // 'Decode Jpeg - System.Drawing' | Jpg/baseline/Lake.jpg | 6.117 ms | 0.3923 ms | 0.0222 ms | 1.00 | 0.00 | 62.5000 | - | - | 205.83 KB | @@ -119,21 +114,21 @@ public CoreSize JpegImageSharp() // RESULTS (2019 April 23): // - //BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17763.437 (1809/October2018Update/Redstone5) - //Intel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores - //.NET Core SDK=2.2.202 + // BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17763.437 (1809/October2018Update/Redstone5) + // Intel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores + // .NET Core SDK=2.2.202 // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // - //| Method | TestImage | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | - //|------------------------------- |--------------------- |-----------:|-----------:|-----------:|------:|--------:|----------:|------:|------:|------------:| - //| 'Decode Jpeg - System.Drawing' | Jpg/b(...)e.jpg [21] | 6.957 ms | 9.618 ms | 0.5272 ms | 1.00 | 0.00 | 93.7500 | - | - | 205.83 KB | - //| 'Decode Jpeg - ImageSharp' | Jpg/b(...)e.jpg [21] | 18.348 ms | 8.876 ms | 0.4865 ms | 2.65 | 0.23 | - | - | - | 14.49 KB | - //| | | | | | | | | | | | - //| 'Decode Jpeg - System.Drawing' | Jpg/b(...)f.jpg [28] | 18.687 ms | 11.632 ms | 0.6376 ms | 1.00 | 0.00 | 343.7500 | - | - | 757.04 KB | - //| 'Decode Jpeg - ImageSharp' | Jpg/b(...)f.jpg [28] | 41.990 ms | 25.514 ms | 1.3985 ms | 2.25 | 0.10 | - | - | - | 15.48 KB | - //| | | | | | | | | | | | - //| 'Decode Jpeg - System.Drawing' | Jpg/i(...)e.jpg [43] | 477.265 ms | 732.126 ms | 40.1303 ms | 1.00 | 0.00 | 3000.0000 | - | - | 7403.76 KB | - //| 'Decode Jpeg - ImageSharp' | Jpg/i(...)e.jpg [43] | 348.545 ms | 91.480 ms | 5.0143 ms | 0.73 | 0.06 | - | - | - | 35177.21 KB | + // | Method | TestImage | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | + // |------------------------------- |--------------------- |-----------:|-----------:|-----------:|------:|--------:|----------:|------:|------:|------------:| + // | 'Decode Jpeg - System.Drawing' | Jpg/b(...)e.jpg [21] | 6.957 ms | 9.618 ms | 0.5272 ms | 1.00 | 0.00 | 93.7500 | - | - | 205.83 KB | + // | 'Decode Jpeg - ImageSharp' | Jpg/b(...)e.jpg [21] | 18.348 ms | 8.876 ms | 0.4865 ms | 2.65 | 0.23 | - | - | - | 14.49 KB | + // | | | | | | | | | | | | + // | 'Decode Jpeg - System.Drawing' | Jpg/b(...)f.jpg [28] | 18.687 ms | 11.632 ms | 0.6376 ms | 1.00 | 0.00 | 343.7500 | - | - | 757.04 KB | + // | 'Decode Jpeg - ImageSharp' | Jpg/b(...)f.jpg [28] | 41.990 ms | 25.514 ms | 1.3985 ms | 2.25 | 0.10 | - | - | - | 15.48 KB | + // | | | | | | | | | | | | + // | 'Decode Jpeg - System.Drawing' | Jpg/i(...)e.jpg [43] | 477.265 ms | 732.126 ms | 40.1303 ms | 1.00 | 0.00 | 3000.0000 | - | - | 7403.76 KB | + // | 'Decode Jpeg - ImageSharp' | Jpg/i(...)e.jpg [43] | 348.545 ms | 91.480 ms | 5.0143 ms | 0.73 | 0.06 | - | - | - | 35177.21 KB | } } diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DoubleBufferedStreams.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DoubleBufferedStreams.cs index 6f2c492d0a..6f3ea0e142 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DoubleBufferedStreams.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DoubleBufferedStreams.cs @@ -125,28 +125,29 @@ private static byte[] CreateTestBytes() } } - // RESULTS (2019 April 24): - // - //BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17763.437 (1809/October2018Update/Redstone5) - //Intel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores - //.NET Core SDK=2.2.202 - // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0 - // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // - //IterationCount=3 LaunchCount=1 WarmupCount=3 - // - //| Method | Job | Runtime | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | - //|----------------------------- |----- |-------- |---------:|-----------:|----------:|------:|--------:|------:|------:|------:|----------:| - //| StandardStreamReadByte | Clr | Clr | 96.71 us | 5.9950 us | 0.3286 us | 1.00 | 0.00 | - | - | - | - | - //| StandardStreamRead | Clr | Clr | 77.73 us | 5.2284 us | 0.2866 us | 0.80 | 0.00 | - | - | - | - | - //| DoubleBufferedStreamReadByte | Clr | Clr | 23.17 us | 26.2354 us | 1.4381 us | 0.24 | 0.01 | - | - | - | - | - //| DoubleBufferedStreamRead | Clr | Clr | 33.35 us | 3.4071 us | 0.1868 us | 0.34 | 0.00 | - | - | - | - | - //| SimpleReadByte | Clr | Clr | 10.85 us | 0.4927 us | 0.0270 us | 0.11 | 0.00 | - | - | - | - | - //| | | | | | | | | | | | | - //| StandardStreamReadByte | Core | Core | 75.35 us | 12.9789 us | 0.7114 us | 1.00 | 0.00 | - | - | - | - | - //| StandardStreamRead | Core | Core | 55.36 us | 1.4432 us | 0.0791 us | 0.73 | 0.01 | - | - | - | - | - //| DoubleBufferedStreamReadByte | Core | Core | 21.47 us | 29.7076 us | 1.6284 us | 0.28 | 0.02 | - | - | - | - | - //| DoubleBufferedStreamRead | Core | Core | 29.67 us | 2.5988 us | 0.1424 us | 0.39 | 0.00 | - | - | - | - | - //| SimpleReadByte | Core | Core | 10.84 us | 0.7567 us | 0.0415 us | 0.14 | 0.00 | - | - | - | - | + /* RESULTS (2019 April 24): + + BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17763.437 (1809/October2018Update/Redstone5) + Intel Core i7-6600U CPU 2.60GHz (Skylake), 1 CPU, 4 logical and 2 physical cores + .NET Core SDK=2.2.202 + [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT + Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0 + Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT + + IterationCount=3 LaunchCount=1 WarmupCount=3 + + | Method | Job | Runtime | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | + |----------------------------- |----- |-------- |---------:|-----------:|----------:|------:|--------:|------:|------:|------:|----------:| + | StandardStreamReadByte | Clr | Clr | 96.71 us | 5.9950 us | 0.3286 us | 1.00 | 0.00 | - | - | - | - | + | StandardStreamRead | Clr | Clr | 77.73 us | 5.2284 us | 0.2866 us | 0.80 | 0.00 | - | - | - | - | + | DoubleBufferedStreamReadByte | Clr | Clr | 23.17 us | 26.2354 us | 1.4381 us | 0.24 | 0.01 | - | - | - | - | + | DoubleBufferedStreamRead | Clr | Clr | 33.35 us | 3.4071 us | 0.1868 us | 0.34 | 0.00 | - | - | - | - | + | SimpleReadByte | Clr | Clr | 10.85 us | 0.4927 us | 0.0270 us | 0.11 | 0.00 | - | - | - | - | + | | | | | | | | | | | | | + | StandardStreamReadByte | Core | Core | 75.35 us | 12.9789 us | 0.7114 us | 1.00 | 0.00 | - | - | - | - | + | StandardStreamRead | Core | Core | 55.36 us | 1.4432 us | 0.0791 us | 0.73 | 0.01 | - | - | - | - | + | DoubleBufferedStreamReadByte | Core | Core | 21.47 us | 29.7076 us | 1.6284 us | 0.28 | 0.02 | - | - | - | - | + | DoubleBufferedStreamRead | Core | Core | 29.67 us | 2.5988 us | 0.1424 us | 0.39 | 0.00 | - | - | - | - | + | SimpleReadByte | Core | Core | 10.84 us | 0.7567 us | 0.0415 us | 0.14 | 0.00 | - | - | - | - | + */ } diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpeg.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpeg.cs index c617d25c07..b64c86974a 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpeg.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpeg.cs @@ -1,16 +1,15 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using SixLabors.ImageSharp.PixelFormats; - using BenchmarkDotNet.Attributes; +using SixLabors.ImageSharp.PixelFormats; + namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { using System.Drawing; using System.Drawing.Imaging; using System.IO; - using CoreImage = SixLabors.ImageSharp.Image; public class EncodeJpeg : BenchmarkBase @@ -58,4 +57,4 @@ public void JpegCore() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpegMultiple.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpegMultiple.cs index afa2ad325a..a710fc1965 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpegMultiple.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/EncodeJpegMultiple.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. using System.Collections.Generic; @@ -18,13 +18,21 @@ public class EncodeJpegMultiple : MultiImageBenchmarkBase.WithImagesPreloaded [Benchmark(Description = "EncodeJpegMultiple - ImageSharp")] public void EncodeJpegImageSharp() { - this.ForEachImageSharpImage((img, ms) => { img.Save(ms, new JpegEncoder()); return null; }); + this.ForEachImageSharpImage((img, ms) => + { + img.Save(ms, new JpegEncoder()); + return null; + }); } [Benchmark(Baseline = true, Description = "EncodeJpegMultiple - System.Drawing")] public void EncodeJpegSystemDrawing() { - this.ForEachSystemDrawingImage((img, ms) => { img.Save(ms, ImageFormat.Jpeg); return null; }); + this.ForEachSystemDrawingImage((img, ms) => + { + img.Save(ms, ImageFormat.Jpeg); + return null; + }); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_Aggregate.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_Aggregate.cs index e39cfa6ba2..4a3c88a281 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_Aggregate.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_Aggregate.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. using System.Collections.Generic; @@ -13,8 +13,8 @@ using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Tests; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { [Config(typeof(MultiImageBenchmarkBase.Config))] @@ -93,4 +93,4 @@ public void ImageSharp() }); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_ImageSpecific.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_ImageSpecific.cs index 1834f77eaf..0d0e3212b1 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_ImageSpecific.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/LoadResizeSave_ImageSpecific.cs @@ -1,18 +1,20 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using BenchmarkDotNet.Attributes; using System; -using System.IO; -using SixLabors.ImageSharp.Tests; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; +using System.IO; +using BenchmarkDotNet.Attributes; + +using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Tests; + using SDImage = System.Drawing.Image; -using SixLabors.ImageSharp.Formats.Jpeg; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { [Config(typeof(Config.ShortClr))] @@ -29,9 +31,7 @@ public class LoadResizeSave_ImageSpecific [Params( TestImages.Jpeg.BenchmarkSuite.Lake_Small444YCbCr, TestImages.Jpeg.BenchmarkSuite.BadRstProgressive518_Large444YCbCr, - - TestImages.Jpeg.BenchmarkSuite.Jpeg420Exif_MidSizeYCbCr - )] + TestImages.Jpeg.BenchmarkSuite.Jpeg420Exif_MidSizeYCbCr)] public string TestImage { get; set; } [Params(false, true)] @@ -89,7 +89,7 @@ public void ImageSharp() // [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT // Job-ZPEZGV : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0 // Job-SGOCJT : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT - // + // // Method | Runtime | TestImage | ParallelExec | Mean | Error | StdDev | Scaled | ScaledSD | Gen 0 | Allocated | // -------------- |-------- |----------------------------- |------------- |----------:|----------:|----------:|-------:|---------:|---------:|----------:| // SystemDrawing | Clr | Jpg/baseline/jpeg420exif.jpg | False | 64.88 ms | 3.735 ms | 0.2110 ms | 1.00 | 0.00 | 250.0000 | 791.07 KB | @@ -104,4 +104,4 @@ public void ImageSharp() // SystemDrawing | Core | Jpg/baseline/jpeg420exif.jpg | True | 64.20 ms | 6.560 ms | 0.3707 ms | 1.00 | 0.00 | 250.0000 | 789.79 KB | // ImageSharp | Core | Jpg/baseline/jpeg420exif.jpg | True | 68.08 ms | 18.376 ms | 1.0383 ms | 1.06 | 0.01 | - | 50.49 KB | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/YCbCrColorConversion.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/YCbCrColorConversion.cs index 313a7c97d3..1e4ebb7196 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/YCbCrColorConversion.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/YCbCrColorConversion.cs @@ -74,7 +74,7 @@ private static Buffer2D[] CreateRandomValues( for (int j = 0; j < inputBufferLength; j++) { - values[j] = (float)rnd.NextDouble() * (maxVal - minVal) + minVal; + values[j] = ((float)rnd.NextDouble() * (maxVal - minVal)) + minVal; } // no need to dispose when buffer is not array owner diff --git a/tests/ImageSharp.Benchmarks/Codecs/MultiImageBenchmarkBase.cs b/tests/ImageSharp.Benchmarks/Codecs/MultiImageBenchmarkBase.cs index 6d4caa8436..eafbc0fdeb 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/MultiImageBenchmarkBase.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/MultiImageBenchmarkBase.cs @@ -20,7 +20,7 @@ namespace SixLabors.ImageSharp.Benchmarks.Codecs using BenchmarkDotNet.Environments; using SixLabors.ImageSharp.Tests; - using CoreImage = ImageSharp.Image; + using CoreImage = SixLabors.ImageSharp.Image; public abstract class MultiImageBenchmarkBase { @@ -36,27 +36,33 @@ public class ShortClr : Benchmarks.Config { public ShortClr() { - this.Add( - Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(1).WithIterationCount(2) - ); + this.Add(Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(1).WithIterationCount(2)); } } } - protected Dictionary FileNamesToBytes = new Dictionary(); - - protected Dictionary> FileNamesToImageSharpImages = new Dictionary>(); - protected Dictionary FileNamesToSystemDrawingImages = new Dictionary(); + protected Dictionary fileNamesToBytes = new Dictionary(); + protected Dictionary> fileNamesToImageSharpImages = new Dictionary>(); + protected Dictionary fileNamesToSystemDrawingImages = new Dictionary(); /// - /// The values of this enum separate input files into categories + /// The values of this enum separate input files into categories. /// public enum InputImageCategory { + /// + /// Use all images. + /// AllImages, + /// + /// Use small images only. + /// SmallImagesOnly, + /// + /// Use large images only. + /// LargeImagesOnly } @@ -73,12 +79,13 @@ public enum InputImageCategory protected virtual IEnumerable ExcludeSubstringsInFileNames => new[] { "badeof", "BadEof", "CriticalEOF" }; /// - /// Enumerates folders containing files OR files to be processed by the benchmark. + /// Gets folders containing files OR files to be processed by the benchmark. /// protected IEnumerable AllFoldersOrFiles => this.InputImageSubfoldersOrFiles.Select(f => Path.Combine(this.BaseFolder, f)); /// - /// The images sized above this threshold will be included in + /// Gets the large image threshold. + /// The images sized above this threshold will be included in. /// protected virtual int LargeImageThresholdInBytes => 100000; @@ -102,7 +109,7 @@ protected IEnumerable> EnumeratePairsByBenchmarkSettings protected IEnumerable> FileNames2Bytes => this.EnumeratePairsByBenchmarkSettings( - this.FileNamesToBytes, + this.fileNamesToBytes, arr => arr.Length < this.LargeImageThresholdInBytes); protected abstract IEnumerable InputImageSubfoldersOrFiles { get; } @@ -114,6 +121,7 @@ public virtual void Setup() { throw new Exception("Vector.IsHardwareAccelerated == false! Check your build settings!"); } + // Console.WriteLine("Vector.IsHardwareAccelerated: " + Vector.IsHardwareAccelerated); this.ReadFilesImpl(); } @@ -124,7 +132,7 @@ protected virtual void ReadFilesImpl() { if (File.Exists(path)) { - this.FileNamesToBytes[path] = File.ReadAllBytes(path); + this.fileNamesToBytes[path] = File.ReadAllBytes(path); continue; } @@ -138,7 +146,7 @@ protected virtual void ReadFilesImpl() foreach (string fn in allFiles) { - this.FileNamesToBytes[fn] = File.ReadAllBytes(fn); + this.fileNamesToBytes[fn] = File.ReadAllBytes(fn); } } } @@ -157,7 +165,6 @@ protected void ForEachStream(Func operation) { object obj = operation(memoryStream); (obj as IDisposable)?.Dispose(); - } catch (Exception ex) { @@ -173,31 +180,30 @@ protected override void ReadFilesImpl() { base.ReadFilesImpl(); - foreach (KeyValuePair kv in this.FileNamesToBytes) + foreach (KeyValuePair kv in this.fileNamesToBytes) { byte[] bytes = kv.Value; string fn = kv.Key; using (var ms1 = new MemoryStream(bytes)) { - this.FileNamesToImageSharpImages[fn] = CoreImage.Load(ms1); - + this.fileNamesToImageSharpImages[fn] = CoreImage.Load(ms1); } - this.FileNamesToSystemDrawingImages[fn] = new Bitmap(new MemoryStream(bytes)); + this.fileNamesToSystemDrawingImages[fn] = new Bitmap(new MemoryStream(bytes)); } } protected IEnumerable>> FileNames2ImageSharpImages => this.EnumeratePairsByBenchmarkSettings( - this.FileNamesToImageSharpImages, + this.fileNamesToImageSharpImages, img => img.Width * img.Height < this.LargeImageThresholdInPixels); protected IEnumerable> FileNames2SystemDrawingImages => this.EnumeratePairsByBenchmarkSettings( - this.FileNamesToSystemDrawingImages, + this.fileNamesToSystemDrawingImages, img => img.Width * img.Height < this.LargeImageThresholdInPixels); protected virtual int LargeImageThresholdInPixels => 700000; @@ -210,13 +216,11 @@ protected void ForEachImageSharpImage(Func, object> operation) { object obj = operation(kv.Value); (obj as IDisposable)?.Dispose(); - } catch (Exception ex) { Console.WriteLine($"Operation on {kv.Key} failed with {ex.Message}"); } - } } @@ -224,13 +228,13 @@ protected void ForEachImageSharpImage(Func, MemoryStream, object> { using (var workStream = new MemoryStream()) { - this.ForEachImageSharpImage( img => { // ReSharper disable AccessToDisposedClosure object result = operation(img, workStream); workStream.Seek(0, SeekOrigin.Begin); + // ReSharper restore AccessToDisposedClosure return result; }); @@ -257,18 +261,17 @@ protected void ForEachSystemDrawingImage(Func { // ReSharper disable AccessToDisposedClosure object result = operation(img, workStream); workStream.Seek(0, SeekOrigin.Begin); + // ReSharper restore AccessToDisposedClosure return result; }); } - } } } diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/FromRgba32Bytes.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/FromRgba32Bytes.cs index b964221764..8c35f072c4 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/FromRgba32Bytes.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/FromRgba32Bytes.cs @@ -1,16 +1,14 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - -using System.Buffers; using System; - +using System.Buffers; using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces.Bulk { public abstract class FromRgba32Bytes @@ -23,7 +21,7 @@ public abstract class FromRgba32Bytes private Configuration configuration; [Params( - 128, + 128, 1024, 2048)] public int Count { get; set; } @@ -43,12 +41,12 @@ public void Cleanup() this.source.Dispose(); } - //[Benchmark] + // [Benchmark] public void Naive() { Span s = this.source.GetSpan(); Span d = this.destination.GetSpan(); - + for (int i = 0; i < this.Count; i++) { int i4 = i * 4; @@ -89,4 +87,4 @@ public class FromRgba32Bytes_ToBgra32 : FromRgba32Bytes // CommonBulk | 2048 | 2,625.4 ns | 30.143 ns | 26.721 ns | 1.00 | // OptimizedBulk | 2048 | 1,843.0 ns | 20.505 ns | 18.177 ns | 0.70 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/FromVector4.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/FromVector4.cs index 8b2d08e66a..1a5c70e3c4 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/FromVector4.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/FromVector4.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.Buffers; using System.Numerics; @@ -14,6 +12,7 @@ using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces.Bulk { [Config(typeof(Config.ShortClr))] @@ -26,10 +25,7 @@ public abstract class FromVector4 protected Configuration Configuration => Configuration.Default; - [Params( - 64, - 2048 - )] + [Params(64, 2048)] public int Count { get; set; } [GlobalSetup] @@ -46,12 +42,11 @@ public void Cleanup() this.source.Dispose(); } - //[Benchmark] + // [Benchmark] public void PerElement() { ref Vector4 s = ref MemoryMarshal.GetReference(this.source.GetSpan()); ref TPixel d = ref MemoryMarshal.GetReference(this.destination.GetSpan()); - for (int i = 0; i < this.Count; i++) { Unsafe.Add(ref d, i).FromVector4(Unsafe.Add(ref s, i)); @@ -127,4 +122,4 @@ public void ExtendedIntrinsic() // PixelOperations_Base | Core | 2048 | 16,875.73 ns | 1,271.957 ns | 71.8679 ns | 4.30 | 0.10 | - | 24 B | // PixelOperations_Specialized | Core | 2048 | 2,129.92 ns | 262.888 ns | 14.8537 ns |!! 0.54 | 0.01 | - | 0 B | <--- ExtendedIntrinsics rock! } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/Rgb24Bytes.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/Rgb24Bytes.cs index 294baa9d51..5c02c6688e 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/Rgb24Bytes.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/Rgb24Bytes.cs @@ -1,13 +1,12 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System.Buffers; using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces.Bulk { public abstract class Rgb24Bytes @@ -57,4 +56,4 @@ public void OptimizedBulk() => public class Rgb24Bytes_Rgba32 : Rgb24Bytes { } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/ToRgba32Bytes.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/ToRgba32Bytes.cs index 7f4b2bc41d..9ff118ebd7 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/ToRgba32Bytes.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/ToRgba32Bytes.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. using System; @@ -9,7 +9,6 @@ using SixLabors.ImageSharp.PixelFormats; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces.Bulk { public abstract class ToRgba32Bytes @@ -39,7 +38,7 @@ public void Cleanup() this.destination.Dispose(); } - //[Benchmark] + // [Benchmark] public void Naive() { Span s = this.source.GetSpan(); diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4.cs index 70de8f4e27..1131366fce 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4.cs @@ -1,17 +1,15 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - -using System.Buffers; using System; +using System.Buffers; using System.Numerics; - using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces.Bulk { public abstract class ToVector4 @@ -23,12 +21,7 @@ public abstract class ToVector4 protected Configuration Configuration => Configuration.Default; - [Params( - 64, - 256, - //512, - //1024, - 2048)] + [Params(64, 256, 2048)] // 512, 1024 public int Count { get; set; } [GlobalSetup] @@ -45,7 +38,7 @@ public void Cleanup() this.destination.Dispose(); } - //[Benchmark] + // [Benchmark] public void Naive() { Span s = this.source.GetSpan(); @@ -56,7 +49,6 @@ public void Naive() d[i] = s[i].ToVector4(); } } - [Benchmark] public void PixelOperations_Specialized() @@ -67,4 +59,4 @@ public void PixelOperations_Specialized() this.destination.GetSpan()); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Bgra32.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Bgra32.cs index 39702d5253..3a69a6e246 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Bgra32.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Bgra32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Memory; @@ -38,4 +41,4 @@ public void PixelOperations_Base() // PixelOperations_Base | Core | 2048 | 6,937.5 ns | 1,692.19 ns | 95.6121 ns | 1.00 | 0.00 | - | 24 B | // PixelOperations_Specialized | Core | 2048 | 2,994.5 ns | 1,126.65 ns | 63.6578 ns | 0.43 | 0.01 | - | 0 B | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Rgba32.cs b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Rgba32.cs index ab05a14073..b74a412c8f 100644 --- a/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Rgba32.cs +++ b/tests/ImageSharp.Benchmarks/Color/Bulk/ToVector4_Rgba32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Numerics; using System.Runtime.CompilerServices; @@ -49,7 +52,7 @@ public void ExtendedIntrinsics() SimdUtils.ExtendedIntrinsics.BulkConvertByteToNormalizedFloat(sBytes, dFloats); } - //[Benchmark] + // [Benchmark] public void ExtendedIntrinsics_BulkConvertByteToNormalizedFloat_2Loops() { Span sBytes = MemoryMarshal.Cast(this.source.GetSpan()); @@ -91,7 +94,7 @@ public void ExtendedIntrinsics_BulkConvertByteToNormalizedFloat_2Loops() } } - //[Benchmark] + // [Benchmark] public void ExtendedIntrinsics_BulkConvertByteToNormalizedFloat_ConvertInSameLoop() { Span sBytes = MemoryMarshal.Cast(this.source.GetSpan()); @@ -127,38 +130,39 @@ public void ExtendedIntrinsics_BulkConvertByteToNormalizedFloat_ConvertInSameLoo [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector ConvertToNormalizedSingle(Vector u, Vector scale) { - Vector vi = Vector.AsVectorInt32(u); - Vector v = Vector.ConvertToSingle(vi); + var vi = Vector.AsVectorInt32(u); + var v = Vector.ConvertToSingle(vi); v *= scale; return v; } - // RESULTS (2018 October): - // - // Method | Runtime | Count | Mean | Error | StdDev | Scaled | ScaledSD | Gen 0 | Allocated | - // ---------------------------- |-------- |------ |------------:|-------------:|------------:|-------:|---------:|-------:|----------:| - // FallbackIntrinsics128 | Clr | 64 | 287.62 ns | 6.026 ns | 0.3405 ns | 1.19 | 0.00 | - | 0 B | - // BasicIntrinsics256 | Clr | 64 | 240.83 ns | 10.585 ns | 0.5981 ns | 1.00 | 0.00 | - | 0 B | - // ExtendedIntrinsics | Clr | 64 | 168.28 ns | 11.478 ns | 0.6485 ns | 0.70 | 0.00 | - | 0 B | - // PixelOperations_Base | Clr | 64 | 334.08 ns | 38.048 ns | 2.1498 ns | 1.39 | 0.01 | 0.0072 | 24 B | - // PixelOperations_Specialized | Clr | 64 | 255.41 ns | 10.939 ns | 0.6181 ns | 1.06 | 0.00 | - | 0 B | <--- ceremonial overhead has been minimized! - // | | | | | | | | | | - // FallbackIntrinsics128 | Core | 64 | 183.29 ns | 8.931 ns | 0.5046 ns | 1.32 | 0.00 | - | 0 B | - // BasicIntrinsics256 | Core | 64 | 139.18 ns | 7.633 ns | 0.4313 ns | 1.00 | 0.00 | - | 0 B | - // ExtendedIntrinsics | Core | 64 | 66.29 ns | 16.366 ns | 0.9247 ns | 0.48 | 0.01 | - | 0 B | - // PixelOperations_Base | Core | 64 | 257.75 ns | 16.959 ns | 0.9582 ns | 1.85 | 0.01 | 0.0072 | 24 B | - // PixelOperations_Specialized | Core | 64 | 90.14 ns | 9.955 ns | 0.5625 ns | 0.65 | 0.00 | - | 0 B | - // | | | | | | | | | | - // FallbackIntrinsics128 | Clr | 2048 | 5,011.84 ns | 347.991 ns | 19.6621 ns | 1.22 | 0.01 | - | 0 B | - // BasicIntrinsics256 | Clr | 2048 | 4,119.35 ns | 720.153 ns | 40.6900 ns | 1.00 | 0.00 | - | 0 B | - // ExtendedIntrinsics | Clr | 2048 | 1,195.29 ns | 164.389 ns | 9.2883 ns |!! 0.29 | 0.00 | - | 0 B | <--- ExtendedIntrinsics rock! - // PixelOperations_Base | Clr | 2048 | 6,820.58 ns | 823.433 ns | 46.5255 ns | 1.66 | 0.02 | - | 24 B | - // PixelOperations_Specialized | Clr | 2048 | 4,203.53 ns | 176.714 ns | 9.9847 ns | 1.02 | 0.01 | - | 0 B | <--- can't yet detect whether ExtendedIntrinsics are available :( - // | | | | | | | | | | - // FallbackIntrinsics128 | Core | 2048 | 5,017.89 ns | 4,021.533 ns | 227.2241 ns | 1.24 | 0.05 | - | 0 B | - // BasicIntrinsics256 | Core | 2048 | 4,046.51 ns | 1,150.390 ns | 64.9992 ns | 1.00 | 0.00 | - | 0 B | - // ExtendedIntrinsics | Core | 2048 | 1,130.59 ns | 832.588 ns | 47.0427 ns |!! 0.28 | 0.01 | - | 0 B | <--- ExtendedIntrinsics rock! - // PixelOperations_Base | Core | 2048 | 6,752.68 ns | 272.820 ns | 15.4148 ns | 1.67 | 0.02 | - | 24 B | - // PixelOperations_Specialized | Core | 2048 | 1,126.13 ns | 79.192 ns | 4.4745 ns |!! 0.28 | 0.00 | - | 0 B | <--- ExtendedIntrinsics rock! + /*RESULTS (2018 October): + + Method | Runtime | Count | Mean | Error | StdDev | Scaled | ScaledSD | Gen 0 | Allocated | + ---------------------------- |-------- |------ |------------:|-------------:|------------:|-------:|---------:|-------:|----------:| + FallbackIntrinsics128 | Clr | 64 | 287.62 ns | 6.026 ns | 0.3405 ns | 1.19 | 0.00 | - | 0 B | + BasicIntrinsics256 | Clr | 64 | 240.83 ns | 10.585 ns | 0.5981 ns | 1.00 | 0.00 | - | 0 B | + ExtendedIntrinsics | Clr | 64 | 168.28 ns | 11.478 ns | 0.6485 ns | 0.70 | 0.00 | - | 0 B | + PixelOperations_Base | Clr | 64 | 334.08 ns | 38.048 ns | 2.1498 ns | 1.39 | 0.01 | 0.0072 | 24 B | + PixelOperations_Specialized | Clr | 64 | 255.41 ns | 10.939 ns | 0.6181 ns | 1.06 | 0.00 | - | 0 B | <--- ceremonial overhead has been minimized! + | | | | | | | | | | + FallbackIntrinsics128 | Core | 64 | 183.29 ns | 8.931 ns | 0.5046 ns | 1.32 | 0.00 | - | 0 B | + BasicIntrinsics256 | Core | 64 | 139.18 ns | 7.633 ns | 0.4313 ns | 1.00 | 0.00 | - | 0 B | + ExtendedIntrinsics | Core | 64 | 66.29 ns | 16.366 ns | 0.9247 ns | 0.48 | 0.01 | - | 0 B | + PixelOperations_Base | Core | 64 | 257.75 ns | 16.959 ns | 0.9582 ns | 1.85 | 0.01 | 0.0072 | 24 B | + PixelOperations_Specialized | Core | 64 | 90.14 ns | 9.955 ns | 0.5625 ns | 0.65 | 0.00 | - | 0 B | + | | | | | | | | | | + FallbackIntrinsics128 | Clr | 2048 | 5,011.84 ns | 347.991 ns | 19.6621 ns | 1.22 | 0.01 | - | 0 B | + BasicIntrinsics256 | Clr | 2048 | 4,119.35 ns | 720.153 ns | 40.6900 ns | 1.00 | 0.00 | - | 0 B | + ExtendedIntrinsics | Clr | 2048 | 1,195.29 ns | 164.389 ns | 9.2883 ns |!! 0.29 | 0.00 | - | 0 B | <--- ExtendedIntrinsics rock! + PixelOperations_Base | Clr | 2048 | 6,820.58 ns | 823.433 ns | 46.5255 ns | 1.66 | 0.02 | - | 24 B | + PixelOperations_Specialized | Clr | 2048 | 4,203.53 ns | 176.714 ns | 9.9847 ns | 1.02 | 0.01 | - | 0 B | <--- can't yet detect whether ExtendedIntrinsics are available :( + | | | | | | | | | | + FallbackIntrinsics128 | Core | 2048 | 5,017.89 ns | 4,021.533 ns | 227.2241 ns | 1.24 | 0.05 | - | 0 B | + BasicIntrinsics256 | Core | 2048 | 4,046.51 ns | 1,150.390 ns | 64.9992 ns | 1.00 | 0.00 | - | 0 B | + ExtendedIntrinsics | Core | 2048 | 1,130.59 ns | 832.588 ns | 47.0427 ns |!! 0.28 | 0.01 | - | 0 B | <--- ExtendedIntrinsics rock! + PixelOperations_Base | Core | 2048 | 6,752.68 ns | 272.820 ns | 15.4148 ns | 1.67 | 0.02 | - | 24 B | + PixelOperations_Specialized | Core | 2048 | 1,126.13 ns | 79.192 ns | 4.4745 ns |!! 0.28 | 0.00 | - | 0 B | <--- ExtendedIntrinsics rock! + */ } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToCieLabConvert.cs b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToCieLabConvert.cs index 855f5b9b40..5ca5849173 100644 --- a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToCieLabConvert.cs +++ b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToCieLabConvert.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; using Colourful; using Colourful.Conversion; @@ -18,7 +21,6 @@ public class ColorspaceCieXyzToCieLabConvert private static readonly ColourfulConverter ColourfulConverter = new ColourfulConverter(); - [Benchmark(Baseline = true, Description = "Colourful Convert")] public double ColourfulConvert() { @@ -31,4 +33,4 @@ public float ColorSpaceConvert() return ColorSpaceConverter.ToCieLab(CieXyz).L; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToHunterLabConvert.cs b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToHunterLabConvert.cs index 07870b3a85..3f9d1648cb 100644 --- a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToHunterLabConvert.cs +++ b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToHunterLabConvert.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; using Colourful; using Colourful.Conversion; @@ -30,4 +33,4 @@ public float ColorSpaceConvert() return ColorSpaceConverter.ToHunterLab(CieXyz).L; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToLmsConvert.cs b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToLmsConvert.cs index 4d9ba89286..f82afaac47 100644 --- a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToLmsConvert.cs +++ b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToLmsConvert.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; using Colourful; using Colourful.Conversion; diff --git a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToRgbConvert.cs b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToRgbConvert.cs index f20ffdcabc..59705a2023 100644 --- a/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToRgbConvert.cs +++ b/tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToRgbConvert.cs @@ -1,11 +1,14 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; using Colourful; using Colourful.Conversion; using SixLabors.ImageSharp.ColorSpaces; - using SixLabors.ImageSharp.ColorSpaces.Conversion; + namespace SixLabors.ImageSharp.Benchmarks.ColorSpaces { public class ColorspaceCieXyzToRgbConvert @@ -18,7 +21,6 @@ public class ColorspaceCieXyzToRgbConvert private static readonly ColourfulConverter ColourfulConverter = new ColourfulConverter(); - [Benchmark(Baseline = true, Description = "Colourful Convert")] public double ColourfulConvert() { @@ -31,4 +33,4 @@ public float ColorSpaceConvert() return ColorSpaceConverter.ToRgb(CieXyz).R; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.LookupTables.cs b/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.LookupTables.cs index 335ecf4789..a2290ce1f7 100644 --- a/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.LookupTables.cs +++ b/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.LookupTables.cs @@ -1,4 +1,7 @@ -namespace SixLabors.ImageSharp.Benchmarks +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Benchmarks { public partial class RgbToYCbCr { @@ -234,4 +237,4 @@ private static class LookupTables }; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.cs b/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.cs index 0571513f56..b11e389af7 100644 --- a/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.cs +++ b/tests/ImageSharp.Benchmarks/Color/RgbToYCbCr.cs @@ -98,6 +98,7 @@ public static Byte Create(byte[] data) { result.Data[i] = data[i]; } + return result; } } @@ -125,6 +126,7 @@ public void Setup() { this.inputSourceRGB[i] = (byte)(42 + i); } + this.inputSourceRGBAsInteger = new int[InputByteCount + Vector.Count]; // Filling this should be part of the measured operation } @@ -139,7 +141,6 @@ public unsafe void RgbaToYcbCrScalarFloat() var yPtr = (float*)&result.Y; var cbPtr = (float*)&result.Cb; var crPtr = (float*)&result.Cr; - // end of code-bloat block :) for (int i = 0; i < InputColorCount; i++) { @@ -165,7 +166,6 @@ public unsafe void RgbaToYcbCrSimdFloat() var yPtr = (float*)&result.Y; var cbPtr = (float*)&result.Cb; var crPtr = (float*)&result.Cr; - // end of code-bloat block :) for (int i = 0; i < InputColorCount; i++) { @@ -174,8 +174,7 @@ public unsafe void RgbaToYcbCrSimdFloat() var vectorRgb = new Vector3( input.Data[i3 + 0], input.Data[i3 + 1], - input.Data[i3 + 2] - ); + input.Data[i3 + 2]); Vector3 vectorY = VectorY * vectorRgb; Vector3 vectorCb = VectorCb * vectorRgb; @@ -197,7 +196,6 @@ public unsafe void RgbaToYcbCrScaledIntegerSimd() var yPtr = (float*)&result.Y; var cbPtr = (float*)&result.Cb; var crPtr = (float*)&result.Cr; - // end of code-bloat block :) var yCoeffs = new Vector(ScaledCoeffs.Y); var cbCoeffs = new Vector(ScaledCoeffs.Cb); @@ -243,7 +241,6 @@ public unsafe void RgbaToYcbCrScaledIntegerSimdWithDotProduct() float* yPtr = (float*)&result.Y; float* cbPtr = (float*)&result.Cb; float* crPtr = (float*)&result.Cr; - // end of code-bloat block :) var yCoeffs = new Vector(ScaledCoeffs.Y); var cbCoeffs = new Vector(ScaledCoeffs.Cb); @@ -306,7 +303,6 @@ public unsafe void RgbaToYcbCrScaledInteger() float* yPtr = (float*)&result.Y; float* cbPtr = (float*)&result.Cb; float* crPtr = (float*)&result.Cr; - // end of code-bloat block :) for (int i = 0; i < InputColorCount; i++) { @@ -345,7 +341,6 @@ public unsafe void RgbaToYcbCrScaledIntegerLut() float* yPtr = (float*)&result.Y; float* cbPtr = (float*)&result.Cb; float* crPtr = (float*)&result.Cr; - // end of code-bloat block :) for (int i = 0; i < InputColorCount; i++) { diff --git a/tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs b/tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs index 060a28550e..b8e58a8c5a 100644 --- a/tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs +++ b/tests/ImageSharp.Benchmarks/Color/RgbWorkingSpaceAdapt.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; using Colourful; using Colourful.Conversion; diff --git a/tests/ImageSharp.Benchmarks/Color/YcbCrToRgb.cs b/tests/ImageSharp.Benchmarks/Color/YcbCrToRgb.cs index 2e3307d298..5d3bc26bae 100644 --- a/tests/ImageSharp.Benchmarks/Color/YcbCrToRgb.cs +++ b/tests/ImageSharp.Benchmarks/Color/YcbCrToRgb.cs @@ -1,4 +1,7 @@ -namespace SixLabors.ImageSharp.Benchmarks +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Benchmarks { using System.Numerics; diff --git a/tests/ImageSharp.Benchmarks/Config.cs b/tests/ImageSharp.Benchmarks/Config.cs index cb4fcbba18..fc93fc04e2 100644 --- a/tests/ImageSharp.Benchmarks/Config.cs +++ b/tests/ImageSharp.Benchmarks/Config.cs @@ -22,8 +22,7 @@ public ShortClr() this.Add( Job.Default.With(ClrRuntime.Net472).WithLaunchCount(1).WithWarmupCount(3).WithIterationCount(3), Job.Default.With(CoreRuntime.Core31).WithLaunchCount(1).WithWarmupCount(3).WithIterationCount(3), - Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(3).WithIterationCount(3) - ); + Job.Default.With(CoreRuntime.Core21).WithLaunchCount(1).WithWarmupCount(3).WithIterationCount(3)); } } } diff --git a/tests/ImageSharp.Benchmarks/General/Array2D.cs b/tests/ImageSharp.Benchmarks/General/Array2D.cs index 1f8961fcde..908ada9f0d 100644 --- a/tests/ImageSharp.Benchmarks/General/Array2D.cs +++ b/tests/ImageSharp.Benchmarks/General/Array2D.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. using System; @@ -9,8 +9,8 @@ namespace SixLabors.ImageSharp.Benchmarks.General { - /** - * Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | + /* + Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | -------------------------------------------- |------ |---------:|---------:|---------:|-------:|---------:| 'Emulated 2D array access using flat array' | 32 | 224.2 ns | 4.739 ns | 13.75 ns | 0.65 | 0.07 | 'Array access using 2D array' | 32 | 346.6 ns | 9.225 ns | 26.91 ns | 1.00 | 0.00 | @@ -19,7 +19,6 @@ namespace SixLabors.ImageSharp.Benchmarks.General * */ - public class Array2D { private float[] flatArray; @@ -34,6 +33,7 @@ public class Array2D public int Count { get; set; } public int Min { get; private set; } + public int Max { get; private set; } [GlobalSetup] @@ -65,11 +65,12 @@ public float FlatArrayIndex() { for (int j = this.Min; j < this.Max; j++) { - ref float v = ref a[count * i + j]; + ref float v = ref a[(count * i) + j]; v = i * j; s += v; } } + return s; } @@ -87,6 +88,7 @@ public float Array2DIndex() s += v; } } + return s; } @@ -104,6 +106,7 @@ public float ArrayJaggedIndex() s += v; } } + return s; } @@ -121,7 +124,8 @@ public float ArrayMatrixIndex() s += v; } } + return s; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/ArrayReverse.cs b/tests/ImageSharp.Benchmarks/General/ArrayReverse.cs index c49c383eb8..41137e28be 100644 --- a/tests/ImageSharp.Benchmarks/General/ArrayReverse.cs +++ b/tests/ImageSharp.Benchmarks/General/ArrayReverse.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. using System; @@ -12,9 +12,9 @@ public class ArrayReverse [Params(4, 16, 32)] public int Count { get; set; } - byte[] source; + private byte[] source; - byte[] destination; + private byte[] destination; [GlobalSetup] public void SetUp() @@ -34,12 +34,13 @@ public void ReverseLoop() { this.ReverseBytes(this.source, 0, this.Count); - //for (int i = 0; i < this.source.Length / 2; i++) - //{ - // byte tmp = this.source[i]; - // this.source[i] = this.source[this.source.Length - i - 1]; - // this.source[this.source.Length - i - 1] = tmp; - //} + /* + for (int i = 0; i < this.source.Length / 2; i++) + { + byte tmp = this.source[i]; + this.source[i] = this.source[this.source.Length - i - 1]; + this.source[this.source.Length - i - 1] = tmp; + }*/ } public void ReverseBytes(byte[] source, int index, int length) @@ -56,4 +57,4 @@ public void ReverseBytes(byte[] source, int index, int length) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/Abs.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/Abs.cs index ea53959b6a..fc0b149c1f 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/Abs.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/Abs.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using BenchmarkDotNet.Attributes; diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/ClampFloat.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/ClampFloat.cs index 404714a54b..9644cbc7d3 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/ClampFloat.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/ClampFloat.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -37,7 +40,6 @@ public float UsingBranching() return acc; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] private static float ClampUsingMathF(float x, float min, float max) { @@ -66,4 +68,4 @@ private static float ClampUsingBranching(float x, float min, float max) // UsingMathF | 30.37 ns | 0.3764 ns | 0.3337 ns | 1.00 | // UsingBranching | 18.66 ns | 0.1043 ns | 0.0871 ns | 0.61 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoConstant.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoConstant.cs index 94349b20b6..0ccde7a13a 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoConstant.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoConstant.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; namespace SixLabors.ImageSharp.Benchmarks.General.BasicMath { @@ -19,4 +22,4 @@ public int Bitwise() return ImageMaths.Modulo8(this.value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoVariable.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoVariable.cs index d5683673fe..e8cb8ca622 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoVariable.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/ModuloPowerOfTwoVariable.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using BenchmarkDotNet.Attributes; namespace SixLabors.ImageSharp.Benchmarks.General.BasicMath { @@ -28,4 +31,4 @@ public int Bitwise() // Standard | 1.2465 ns | 0.0093 ns | 0.0455 ns | 1.2423 ns | 1.00 | 0.00 | // Bitwise | 0.0265 ns | 0.0103 ns | 0.0515 ns | 0.0000 ns | 0.02 | 0.04 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/Pow.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/Pow.cs index 0f256fc781..b7eb01fcb5 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/Pow.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/Pow.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using BenchmarkDotNet.Attributes; @@ -9,7 +12,6 @@ public class Pow [Params(-1.333F, 1.333F)] public float X { get; set; } - [Benchmark(Baseline = true, Description = "Math.Pow 2")] public float MathPow() { diff --git a/tests/ImageSharp.Benchmarks/General/BasicMath/Round.cs b/tests/ImageSharp.Benchmarks/General/BasicMath/Round.cs index 2c18b2972c..bb308d4805 100644 --- a/tests/ImageSharp.Benchmarks/General/BasicMath/Round.cs +++ b/tests/ImageSharp.Benchmarks/General/BasicMath/Round.cs @@ -1,17 +1,20 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using BenchmarkDotNet.Attributes; namespace SixLabors.ImageSharp.Benchmarks.General.BasicMath { public class Round { - private const float input = .51F; + private const float Input = .51F; [Benchmark] - public int ConvertTo() => Convert.ToInt32(input); + public int ConvertTo() => Convert.ToInt32(Input); [Benchmark] - public int MathRound() => (int)Math.Round(input); + public int MathRound() => (int)Math.Round(Input); // Results 20th Jan 2019 // Method | Mean | Error | StdDev | Median | diff --git a/tests/ImageSharp.Benchmarks/General/CopyBuffers.cs b/tests/ImageSharp.Benchmarks/General/CopyBuffers.cs index 2c325d184a..2afa8753f8 100644 --- a/tests/ImageSharp.Benchmarks/General/CopyBuffers.cs +++ b/tests/ImageSharp.Benchmarks/General/CopyBuffers.cs @@ -34,7 +34,6 @@ public class CopyBuffers [Params(10, 50, 100, 1000, 10000)] public int Count { get; set; } - [GlobalSetup] public void Setup() { @@ -74,7 +73,6 @@ public unsafe void BufferMemoryCopy() Buffer.MemoryCopy(pinnedSource, pinnedDestination, this.Count, this.Count); } - [Benchmark(Description = "Marshal.Copy()")] public unsafe void MarshalCopy() { diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/ITestPixel.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/ITestPixel.cs index b5f339fb37..6d7c3c4236 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/ITestPixel.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/ITestPixel.cs @@ -1,10 +1,13 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { - interface ITestPixel + public interface ITestPixel where T : struct, ITestPixel { void FromRgba32(Rgba32 source); @@ -25,4 +28,4 @@ interface ITestPixel void CopyToVector4(ref Vector4 dest); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromRgba32.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromRgba32.cs index 9f1b2721b4..55527da188 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromRgba32.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromRgba32.cs @@ -1,4 +1,5 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; using System.Runtime.CompilerServices; @@ -9,6 +10,7 @@ using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats.Utils; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { public abstract class PixelConversion_ConvertFromRgba32 @@ -16,23 +18,23 @@ public abstract class PixelConversion_ConvertFromRgba32 internal struct ConversionRunner where T : struct, ITestPixel { - public readonly T[] dest; + public readonly T[] Dest; - public readonly Rgba32[] source; + public readonly Rgba32[] Source; public ConversionRunner(int count) { - this.dest = new T[count]; - this.source = new Rgba32[count]; + this.Dest = new T[count]; + this.Source = new Rgba32[count]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunByRefConversion() { - int count = this.dest.Length; + int count = this.Dest.Length; - ref T destBaseRef = ref this.dest[0]; - ref Rgba32 sourceBaseRef = ref this.source[0]; + ref T destBaseRef = ref this.Dest[0]; + ref Rgba32 sourceBaseRef = ref this.Source[0]; for (int i = 0; i < count; i++) { @@ -43,10 +45,10 @@ public void RunByRefConversion() [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunByValConversion() { - int count = this.dest.Length; + int count = this.Dest.Length; - ref T destBaseRef = ref this.dest[0]; - ref Rgba32 sourceBaseRef = ref this.source[0]; + ref T destBaseRef = ref this.Dest[0]; + ref Rgba32 sourceBaseRef = ref this.Source[0]; for (int i = 0; i < count; i++) { @@ -57,10 +59,10 @@ public void RunByValConversion() [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RunFromBytesConversion() { - int count = this.dest.Length; + int count = this.Dest.Length; - ref T destBaseRef = ref this.dest[0]; - ref Rgba32 sourceBaseRef = ref this.source[0]; + ref T destBaseRef = ref this.Dest[0]; + ref Rgba32 sourceBaseRef = ref this.Source[0]; for (int i = 0; i < count; i++) { @@ -69,22 +71,19 @@ public void RunFromBytesConversion() } } } - - internal ConversionRunner compatibleMemLayoutRunner; - internal ConversionRunner permutedRunnerRgbaToArgb; + internal ConversionRunner CompatibleMemLayoutRunner; - [Params( - 256, - 2048 - )] + internal ConversionRunner PermutedRunnerRgbaToArgb; + + [Params(256, 2048)] public int Count { get; set; } [GlobalSetup] public void Setup() { - this.compatibleMemLayoutRunner = new ConversionRunner(this.Count); - this.permutedRunnerRgbaToArgb = new ConversionRunner(this.Count); + this.CompatibleMemLayoutRunner = new ConversionRunner(this.Count); + this.PermutedRunnerRgbaToArgb = new ConversionRunner(this.Count); } } @@ -93,26 +92,26 @@ public class PixelConversion_ConvertFromRgba32_Compatible : PixelConversion_Conv [Benchmark(Baseline = true)] public void ByRef() { - this.compatibleMemLayoutRunner.RunByRefConversion(); + this.CompatibleMemLayoutRunner.RunByRefConversion(); } [Benchmark] public void ByVal() { - this.compatibleMemLayoutRunner.RunByValConversion(); + this.CompatibleMemLayoutRunner.RunByValConversion(); } [Benchmark] public void FromBytes() { - this.compatibleMemLayoutRunner.RunFromBytesConversion(); + this.CompatibleMemLayoutRunner.RunFromBytesConversion(); } [Benchmark] public void Inline() { - ref Rgba32 sBase = ref this.compatibleMemLayoutRunner.source[0]; - ref Rgba32 dBase = ref Unsafe.As(ref this.compatibleMemLayoutRunner.dest[0]); + ref Rgba32 sBase = ref this.CompatibleMemLayoutRunner.Source[0]; + ref Rgba32 dBase = ref Unsafe.As(ref this.CompatibleMemLayoutRunner.Dest[0]); for (int i = 0; i < this.Count; i++) { @@ -120,12 +119,12 @@ public void Inline() } } - // Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | - // ---------- |------ |---------:|---------:|---------:|-------:|---------:| - // ByRef | 256 | 128.5 ns | 1.217 ns | 1.138 ns | 1.00 | 0.00 | - // ByVal | 256 | 196.7 ns | 2.792 ns | 2.612 ns | 1.53 | 0.02 | - // FromBytes | 256 | 321.7 ns | 2.180 ns | 1.820 ns | 2.50 | 0.03 | - // Inline | 256 | 129.9 ns | 2.759 ns | 2.581 ns | 1.01 | 0.02 | + /* Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | + ---------- |------ |---------:|---------:|---------:|-------:|---------:| + ByRef | 256 | 128.5 ns | 1.217 ns | 1.138 ns | 1.00 | 0.00 | + ByVal | 256 | 196.7 ns | 2.792 ns | 2.612 ns | 1.53 | 0.02 | + FromBytes | 256 | 321.7 ns | 2.180 ns | 1.820 ns | 2.50 | 0.03 | + Inline | 256 | 129.9 ns | 2.759 ns | 2.581 ns | 1.01 | 0.02 | */ } public class PixelConversion_ConvertFromRgba32_Permuted_RgbaToArgb : PixelConversion_ConvertFromRgba32 @@ -133,26 +132,26 @@ public class PixelConversion_ConvertFromRgba32_Permuted_RgbaToArgb : PixelConver [Benchmark(Baseline = true)] public void ByRef() { - this.permutedRunnerRgbaToArgb.RunByRefConversion(); + this.PermutedRunnerRgbaToArgb.RunByRefConversion(); } [Benchmark] public void ByVal() { - this.permutedRunnerRgbaToArgb.RunByValConversion(); + this.PermutedRunnerRgbaToArgb.RunByValConversion(); } [Benchmark] public void FromBytes() { - this.permutedRunnerRgbaToArgb.RunFromBytesConversion(); + this.PermutedRunnerRgbaToArgb.RunFromBytesConversion(); } [Benchmark] public void InlineShuffle() { - ref Rgba32 sBase = ref this.permutedRunnerRgbaToArgb.source[0]; - ref TestArgb dBase = ref this.permutedRunnerRgbaToArgb.dest[0]; + ref Rgba32 sBase = ref this.PermutedRunnerRgbaToArgb.Source[0]; + ref TestArgb dBase = ref this.PermutedRunnerRgbaToArgb.Dest[0]; for (int i = 0; i < this.Count; i++) { @@ -169,8 +168,8 @@ public void InlineShuffle() [Benchmark] public void PixelConverter_Rgba32_ToArgb32() { - ref uint sBase = ref Unsafe.As(ref this.permutedRunnerRgbaToArgb.source[0]); - ref uint dBase = ref Unsafe.As(ref this.permutedRunnerRgbaToArgb.dest[0]); + ref uint sBase = ref Unsafe.As(ref this.PermutedRunnerRgbaToArgb.Source[0]); + ref uint dBase = ref Unsafe.As(ref this.PermutedRunnerRgbaToArgb.Dest[0]); for (int i = 0; i < this.Count; i++) { @@ -182,8 +181,8 @@ public void PixelConverter_Rgba32_ToArgb32() [Benchmark] public void PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer() { - Span source = MemoryMarshal.Cast(this.permutedRunnerRgbaToArgb.source); - Span dest = MemoryMarshal.Cast(this.permutedRunnerRgbaToArgb.dest); + Span source = MemoryMarshal.Cast(this.PermutedRunnerRgbaToArgb.Source); + Span dest = MemoryMarshal.Cast(this.PermutedRunnerRgbaToArgb.Dest); source.CopyTo(dest); ref uint dBase = ref MemoryMarshal.GetReference(dest); @@ -195,21 +194,23 @@ public void PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer() } } - // RESULTS: - // Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | - // ---------------------------------------------------------- |------ |-----------:|-----------:|-----------:|-------:|---------:| - // ByRef | 256 | 328.7 ns | 6.6141 ns | 6.1868 ns | 1.00 | 0.00 | - // ByVal | 256 | 322.0 ns | 4.3541 ns | 4.0728 ns | 0.98 | 0.02 | - // FromBytes | 256 | 321.5 ns | 3.3499 ns | 3.1335 ns | 0.98 | 0.02 | - // InlineShuffle | 256 | 330.7 ns | 4.2525 ns | 3.9778 ns | 1.01 | 0.02 | - // PixelConverter_Rgba32_ToArgb32 | 256 | 167.4 ns | 0.6357 ns | 0.5309 ns | 0.51 | 0.01 | - // PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer | 256 | 196.6 ns | 0.8929 ns | 0.7915 ns | 0.60 | 0.01 | - // | | | | | | | - // ByRef | 2048 | 2,534.4 ns | 8.2947 ns | 6.9265 ns | 1.00 | 0.00 | - // ByVal | 2048 | 2,638.5 ns | 52.6843 ns | 70.3320 ns | 1.04 | 0.03 | - // FromBytes | 2048 | 2,517.2 ns | 40.8055 ns | 38.1695 ns | 0.99 | 0.01 | - // InlineShuffle | 2048 | 2,546.5 ns | 21.2506 ns | 19.8778 ns | 1.00 | 0.01 | - // PixelConverter_Rgba32_ToArgb32 | 2048 | 1,265.7 ns | 5.1397 ns | 4.5562 ns | 0.50 | 0.00 | - // PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer | 2048 | 1,410.3 ns | 11.1939 ns | 9.9231 ns | 0.56 | 0.00 |// + /* + RESULTS: + Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | + ---------------------------------------------------------- |------ |-----------:|-----------:|-----------:|-------:|---------:| + ByRef | 256 | 328.7 ns | 6.6141 ns | 6.1868 ns | 1.00 | 0.00 | + ByVal | 256 | 322.0 ns | 4.3541 ns | 4.0728 ns | 0.98 | 0.02 | + FromBytes | 256 | 321.5 ns | 3.3499 ns | 3.1335 ns | 0.98 | 0.02 | + InlineShuffle | 256 | 330.7 ns | 4.2525 ns | 3.9778 ns | 1.01 | 0.02 | + PixelConverter_Rgba32_ToArgb32 | 256 | 167.4 ns | 0.6357 ns | 0.5309 ns | 0.51 | 0.01 | + PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer | 256 | 196.6 ns | 0.8929 ns | 0.7915 ns | 0.60 | 0.01 | + | | | | | | | + ByRef | 2048 | 2,534.4 ns | 8.2947 ns | 6.9265 ns | 1.00 | 0.00 | + ByVal | 2048 | 2,638.5 ns | 52.6843 ns | 70.3320 ns | 1.04 | 0.03 | + FromBytes | 2048 | 2,517.2 ns | 40.8055 ns | 38.1695 ns | 0.99 | 0.01 | + InlineShuffle | 2048 | 2,546.5 ns | 21.2506 ns | 19.8778 ns | 1.00 | 0.01 | + PixelConverter_Rgba32_ToArgb32 | 2048 | 1,265.7 ns | 5.1397 ns | 4.5562 ns | 0.50 | 0.00 | + PixelConverter_Rgba32_ToArgb32_CopyThenWorkOnSingleBuffer | 2048 | 1,410.3 ns | 11.1939 ns | 9.9231 ns | 0.56 | 0.00 | + */ } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromVector4.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromVector4.cs index d0c8a3045c..0b24276d33 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromVector4.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertFromVector4.cs @@ -1,4 +1,5 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System.Numerics; using System.Runtime.CompilerServices; @@ -8,12 +9,13 @@ using SixLabors.ImageSharp.PixelFormats; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { public class PixelConversion_ConvertFromVector4 { [StructLayout(LayoutKind.Sequential)] - struct TestRgbaVector : ITestPixel + private struct TestRgbaVector : ITestPixel { private Vector4 v; @@ -39,13 +41,17 @@ public void CopyToVector4(ref Vector4 dest) } public void FromRgba32(Rgba32 source) => throw new System.NotImplementedException(); + public void FromRgba32(ref Rgba32 source) => throw new System.NotImplementedException(); + public void FromBytes(byte r, byte g, byte b, byte a) => throw new System.NotImplementedException(); + public Rgba32 ToRgba32() => throw new System.NotImplementedException(); + public void CopyToRgba32(ref Rgba32 dest) => throw new System.NotImplementedException(); } - struct ConversionRunner + private struct ConversionRunner where T : struct, ITestPixel { private T[] dest; @@ -100,7 +106,7 @@ public void Setup() this.nonVectorRunner = new ConversionRunner(this.Count); this.vectorRunner = new ConversionRunner(this.Count); } - + [Benchmark(Baseline = true)] public void VectorByRef() { @@ -124,7 +130,6 @@ public void NonVectorByVal() { this.nonVectorRunner.RunByValConversion(); } - } /* @@ -135,8 +140,8 @@ public void NonVectorByVal() * VectorByVal | 32 | 24.5347 ns | 0.0771 ns | 1.04 | 0.01 | * NonVectorByRef | 32 | 59.0187 ns | 0.2114 ns | 2.49 | 0.01 | * NonVectorByVal | 32 | 58.7529 ns | 0.2545 ns | 2.48 | 0.02 | - * + * * !!! Conclusion !!! * We do not need by-ref version of ConvertFromVector4() stuff */ -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32.cs index ea8b34c249..93a27a5554 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32.cs @@ -1,4 +1,7 @@ -using System.Runtime.CompilerServices; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -8,14 +11,14 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { /// /// When implementing TPixel --> Rgba32 style conversions on IPixel, should which API should we prefer? - /// 1. Rgba32 ToRgba32(); + /// 1. Rgba32 ToRgba32(); /// OR /// 2. void CopyToRgba32(ref Rgba32 dest); /// ? /// public class PixelConversion_ConvertToRgba32 { - struct ConversionRunner + private struct ConversionRunner where T : struct, ITestPixel { private T[] source; @@ -98,7 +101,7 @@ public void PermutedCopyTo() /* * Results: - * + * * Method | Count | Mean | StdDev | Scaled | Scaled-StdDev | * --------------- |------ |------------ |---------- |------- |-------------- | * CompatibleRetval | 128 | 89.7358 ns | 2.2389 ns | 1.00 | 0.00 | @@ -106,4 +109,4 @@ public void PermutedCopyTo() * PermutedRetval | 128 | 845.4038 ns | 5.6154 ns | 9.43 | 0.23 | * PermutedCopyTo | 128 | 155.6004 ns | 3.8870 ns | 1.73 | 0.06 | */ -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32_AsPartOfCompositeOperation.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32_AsPartOfCompositeOperation.cs index fff9ae9bc7..6a59e993b8 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32_AsPartOfCompositeOperation.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToRgba32_AsPartOfCompositeOperation.cs @@ -1,4 +1,7 @@ -using System.Runtime.CompilerServices; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -8,7 +11,7 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { public class PixelConversion_ConvertToRgba32_AsPartOfCompositeOperation { - struct ConversionRunner + private struct ConversionRunner where T : struct, ITestPixel { private T[] source; @@ -110,4 +113,4 @@ public void PermutedCopyTo() // CompatibleCopyTo | 32 | 36.12 ns | 0.3596 ns | 0.3003 ns | 0.68 | 0.01 | // PermutedRetval | 32 | 303.61 ns | 5.1697 ns | 4.8358 ns | 5.72 | 0.09 | // PermutedCopyTo | 32 | 38.05 ns | 0.8053 ns | 1.2297 ns | 0.72 | 0.02 | -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4.cs index 68a16b7919..80a2e80d22 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -7,7 +10,7 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { public class PixelConversion_ConvertToVector4 { - struct ConversionRunner + private struct ConversionRunner where T : struct, ITestPixel { private T[] source; @@ -78,4 +81,4 @@ public void UseCopyTo() // UseRetval | 32 | 109.0 ns | 1.202 ns | 1.125 ns | 1.00 | // UseCopyTo | 32 | 108.6 ns | 1.151 ns | 1.020 ns | 1.00 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4_AsPartOfCompositeOperation.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4_AsPartOfCompositeOperation.cs index c6daf0f1e2..699a4cf09d 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4_AsPartOfCompositeOperation.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_ConvertToVector4_AsPartOfCompositeOperation.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -7,7 +10,7 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { public class PixelConversion_ConvertToVector4_AsPartOfCompositeOperation { - struct ConversionRunner + private struct ConversionRunner where T : struct, ITestPixel { private T[] source; @@ -92,4 +95,4 @@ public void UseCopyTo() // UseRetval | 32 | 120.2 ns | 1.560 ns | 1.383 ns | 1.00 | 0.00 | // UseCopyTo | 32 | 121.7 ns | 2.439 ns | 2.281 ns | 1.01 | 0.02 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Argb32.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Argb32.cs index 40893914e1..ef9d033d95 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Argb32.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Argb32.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -74,7 +77,6 @@ public void Default_Group2() } } - [Benchmark] public void Default_Group4() { @@ -98,7 +100,7 @@ public void Default_Group4() Unsafe.Add(ref d2, 1).FromRgba32(s3); } } - + [Benchmark] public void BitOps() { @@ -137,6 +139,7 @@ public static class FromRgba32 /// /// Converts a packed to . /// + /// The argb value. [MethodImpl(InliningOptions.ShortMethod)] public static uint ToArgb32(uint packedRgba) { @@ -148,6 +151,7 @@ public static uint ToArgb32(uint packedRgba) /// /// Converts a packed to . /// + /// The bgra value. [MethodImpl(InliningOptions.ShortMethod)] public static uint ToBgra32(uint packedRgba) { @@ -173,4 +177,4 @@ public static uint ToBgra32(uint packedRgba) // BitOps | 64 | 39.25 ns | 0.3266 ns | 0.2895 ns | 0.37 | // BitOps_GroupAsULong | 64 | 41.80 ns | 0.2227 ns | 0.2083 ns | 0.39 | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs index cd0aed3c47..90591d1750 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Numerics; using System.Runtime.CompilerServices; @@ -10,8 +13,8 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { - //[MonoJob] - //[RyuJitX64Job] + // [MonoJob] + // [RyuJitX64Job] public class PixelConversion_Rgba32_To_Bgra32 { private Rgba32[] source; @@ -19,19 +22,22 @@ public class PixelConversion_Rgba32_To_Bgra32 private Bgra32[] dest; [StructLayout(LayoutKind.Sequential)] - struct Tuple4OfUInt32 + private struct Tuple4OfUInt32 { - public uint V0, V1, V2, V3; + private uint v0; + private uint v1; + private uint v2; + private uint v3; public void ConvertMe() { - this.V0 = FromRgba32.ToBgra32(this.V0); - this.V1 = FromRgba32.ToBgra32(this.V1); - this.V2 = FromRgba32.ToBgra32(this.V2); - this.V3 = FromRgba32.ToBgra32(this.V3); + this.v0 = FromRgba32.ToBgra32(this.v0); + this.v1 = FromRgba32.ToBgra32(this.v1); + this.v2 = FromRgba32.ToBgra32(this.v2); + this.v3 = FromRgba32.ToBgra32(this.v3); } } - + [Params(64)] public int Count { get; set; } @@ -81,7 +87,7 @@ public void Default_Group2() ref Rgba32 sBase = ref this.source[0]; ref Bgra32 dBase = ref this.dest[0]; - for (int i = 0; i < this.Count; i+=2) + for (int i = 0; i < this.Count; i += 2) { ref Rgba32 s0 = ref Unsafe.Add(ref sBase, i); Rgba32 s1 = Unsafe.Add(ref s0, 1); @@ -115,7 +121,7 @@ public void Default_Group4() Unsafe.Add(ref d2, 1).FromRgba32(s3); } } - + [MethodImpl(MethodImplOptions.NoInlining)] private static void Group4GenericImpl(ReadOnlySpan source, Span dest) where TPixel : struct, IPixel @@ -141,13 +147,13 @@ private static void Group4GenericImpl(ReadOnlySpan source, Span< } } - //[Benchmark] + // [Benchmark] public void Default_Group4_Generic() { Group4GenericImpl(this.source.AsSpan(), this.dest.AsSpan()); } - //[Benchmark] + // [Benchmark] public void Default_Group8() { ref Rgba32 sBase = ref this.source[0]; @@ -174,7 +180,6 @@ public void Default_Group8() ref Bgra32 d5 = ref Unsafe.Add(ref d4, 1); ref Bgra32 d6 = ref Unsafe.Add(ref d5, 1); - d0.FromRgba32(s0); d1.FromRgba32(s1); d2.FromRgba32(s2); @@ -214,7 +219,7 @@ public void Bitops_Tuple() } } - //[Benchmark] + // [Benchmark] public void Bitops_SingleTuple() { ref Tuple4OfUInt32 sBase = ref Unsafe.As(ref this.source[0]); @@ -225,7 +230,7 @@ public void Bitops_SingleTuple() } } - //[Benchmark] + // [Benchmark] public void Bitops_Simd() { ref Octet.OfUInt32 sBase = ref Unsafe.As(ref this.source[0]); @@ -238,15 +243,29 @@ public void Bitops_Simd() } [StructLayout(LayoutKind.Sequential)] - struct B + private struct B { - public uint tmp2, tmp5, tmp8, tmp11, tmp14, tmp17, tmp20, tmp23; + public uint Tmp2; + public uint Tmp5; + public uint Tmp8; + public uint Tmp11; + public uint Tmp14; + public uint Tmp17; + public uint Tmp20; + public uint Tmp23; } [StructLayout(LayoutKind.Sequential)] - struct C + private struct C { - public uint tmp3, tmp6, tmp9, tmp12, tmp15, tmp18, tmp21, tmp24; + public uint Tmp3; + public uint Tmp6; + public uint Tmp9; + public uint Tmp12; + public uint Tmp15; + public uint Tmp18; + public uint Tmp21; + public uint Tmp24; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -263,14 +282,14 @@ private static void BitopsSimdImpl(ref Octet.OfUInt32 s, ref Octet.OfUInt32 d) C c = default; - c.tmp3 = (b.tmp2 << 16) | (b.tmp2 >> 16); - c.tmp6 = (b.tmp5 << 16) | (b.tmp5 >> 16); - c.tmp9 = (b.tmp8 << 16) | (b.tmp8 >> 16); - c.tmp12 = (b.tmp11 << 16) | (b.tmp11 >> 16); - c.tmp15 = (b.tmp14 << 16) | (b.tmp14 >> 16); - c.tmp18 = (b.tmp17 << 16) | (b.tmp17 >> 16); - c.tmp21 = (b.tmp20 << 16) | (b.tmp20 >> 16); - c.tmp24 = (b.tmp23 << 16) | (b.tmp23 >> 16); + c.Tmp3 = (b.Tmp2 << 16) | (b.Tmp2 >> 16); + c.Tmp6 = (b.Tmp5 << 16) | (b.Tmp5 >> 16); + c.Tmp9 = (b.Tmp8 << 16) | (b.Tmp8 >> 16); + c.Tmp12 = (b.Tmp11 << 16) | (b.Tmp11 >> 16); + c.Tmp15 = (b.Tmp14 << 16) | (b.Tmp14 >> 16); + c.Tmp18 = (b.Tmp17 << 16) | (b.Tmp17 >> 16); + c.Tmp21 = (b.Tmp20 << 16) | (b.Tmp20 >> 16); + c.Tmp24 = (b.Tmp23 << 16) | (b.Tmp23 >> 16); Vector cc = Unsafe.As>(ref c); Vector dd = aa + cc; @@ -278,7 +297,7 @@ private static void BitopsSimdImpl(ref Octet.OfUInt32 s, ref Octet.OfUInt32 d) d = Unsafe.As, Octet.OfUInt32>(ref dd); } - //[Benchmark] + // [Benchmark] public void BitOps_Group2() { ref uint sBase = ref Unsafe.As(ref this.source[0]); @@ -294,7 +313,7 @@ public void BitOps_Group2() Unsafe.Add(ref d0, 1) = FromRgba32.ToBgra32(s1); } } - + [Benchmark] public void BitOps_GroupAsULong() { @@ -315,7 +334,7 @@ public void BitOps_GroupAsULong() } } - //[Benchmark] + // [Benchmark] public void BitOps_GroupAsULong_V2() { ref ulong sBase = ref Unsafe.As(ref this.source[0]); @@ -350,6 +369,7 @@ public static class FromRgba32 /// /// Converts a packed to . /// + /// The argb value. [MethodImpl(InliningOptions.ShortMethod)] public static uint ToArgb32(uint packedRgba) { @@ -361,6 +381,7 @@ public static uint ToArgb32(uint packedRgba) /// /// Converts a packed to . /// + /// The bgra value. [MethodImpl(InliningOptions.ShortMethod)] public static uint ToBgra32(uint packedRgba) { @@ -376,7 +397,6 @@ public static uint ToBgra32(uint packedRgba) } } - // RESULTS: // Method | Count | Mean | Error | StdDev | Scaled | ScaledSD | // -------------------- |------ |---------:|----------:|----------:|-------:|---------:| diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/TestArgb.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/TestArgb.cs index 76de794eca..4985206054 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/TestArgb.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/TestArgb.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -7,9 +10,12 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { [StructLayout(LayoutKind.Sequential)] - struct TestArgb : ITestPixel + public struct TestArgb : ITestPixel { - public byte A, R, G, B; + public byte A; + public byte R; + public byte G; + public byte B; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void FromRgba32(Rgba32 p) @@ -86,4 +92,4 @@ public void CopyToVector4(ref Vector4 dest) dest.W = this.A; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/TestRgba.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/TestRgba.cs index 36d5f3e5b9..b325ec7c64 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/TestRgba.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/TestRgba.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -7,9 +10,12 @@ namespace SixLabors.ImageSharp.Benchmarks.General.PixelConversion { [StructLayout(LayoutKind.Sequential)] - struct TestRgba : ITestPixel + public struct TestRgba : ITestPixel { - public byte R, G, B, A; + public byte R; + public byte G; + public byte B; + public byte A; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void FromRgba32(Rgba32 source) @@ -57,7 +63,7 @@ public void CopyToRgba32(ref Rgba32 dest) [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4 ToVector4() { - return new Vector4(this.R, this.G, this.B, this.A) * new Vector4(1f / 255f); + return new Vector4(this.R, this.G, this.B, this.A) * new Vector4(1f / 255f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -68,4 +74,4 @@ public void CopyToVector4(ref Vector4 dest) dest = tmp; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/StructCasting.cs b/tests/ImageSharp.Benchmarks/General/StructCasting.cs index bed68b54a1..ff89ad3ffe 100644 --- a/tests/ImageSharp.Benchmarks/General/StructCasting.cs +++ b/tests/ImageSharp.Benchmarks/General/StructCasting.cs @@ -1,4 +1,7 @@ -using System.Runtime.CompilerServices; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; namespace SixLabors.ImageSharp.Benchmarks.General diff --git a/tests/ImageSharp.Benchmarks/General/Vector4Constants.cs b/tests/ImageSharp.Benchmarks/General/Vector4Constants.cs index 02bc5d843e..80f4041620 100644 --- a/tests/ImageSharp.Benchmarks/General/Vector4Constants.cs +++ b/tests/ImageSharp.Benchmarks/General/Vector4Constants.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Numerics; @@ -28,8 +31,7 @@ public void Setup() this.GetRandomFloat(), this.GetRandomFloat(), this.GetRandomFloat(), - this.GetRandomFloat() - ); + this.GetRandomFloat()); } [Benchmark(Baseline = true)] @@ -37,10 +39,10 @@ public Vector4 Static() { Vector4 p = this.parameter; - Vector4 x = p * A / B + p * C / D; - Vector4 y = p / A * B + p / C * D; - Vector4 z = Vector4.Min(p, A); - Vector4 w = Vector4.Max(p, B); + Vector4 x = (p * A / B) + (p * C / D); + Vector4 y = (p / A * B) + (p / C * D); + var z = Vector4.Min(p, A); + var w = Vector4.Max(p, B); return x + y + z + w; } @@ -49,10 +51,10 @@ public Vector4 Inlined() { Vector4 p = this.parameter; - Vector4 x = p * new Vector4(1.2f) / new Vector4(2.3f) + p * new Vector4(4.5f) / new Vector4(6.7f); - Vector4 y = p / new Vector4(1.2f) * new Vector4(2.3f) + p / new Vector4(4.5f) * new Vector4(6.7f); - Vector4 z = Vector4.Min(p, new Vector4(1.2f)); - Vector4 w = Vector4.Max(p, new Vector4(2.3f)); + Vector4 x = (p * new Vector4(1.2f) / new Vector4(2.3f)) + (p * new Vector4(4.5f) / new Vector4(6.7f)); + Vector4 y = (p / new Vector4(1.2f) * new Vector4(2.3f)) + (p / new Vector4(4.5f) * new Vector4(6.7f)); + var z = Vector4.Min(p, new Vector4(1.2f)); + var w = Vector4.Max(p, new Vector4(2.3f)); return x + y + z + w; } diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/BitwiseOrUint32.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/BitwiseOrUint32.cs index 60bf615c56..41764b8160 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/BitwiseOrUint32.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/BitwiseOrUint32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; @@ -24,7 +27,7 @@ public void Setup() for (int i = 0; i < this.InputSize; i++) { - this.input[i] = (uint) i; + this.input[i] = (uint)i; } } @@ -43,7 +46,7 @@ public void Simd() { var v = new Vector(this.testValue); - for (int i = 0; i < this.input.Length; i+=Vector.Count) + for (int i = 0; i < this.input.Length; i += Vector.Count) { var a = new Vector(this.input, i); a = Vector.BitwiseOr(a, v); diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/DivFloat.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/DivFloat.cs index be9534f7d0..8d842a0f51 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/DivFloat.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/DivFloat.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; @@ -51,4 +54,4 @@ public void Simd() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/DivUInt32.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/DivUInt32.cs index bfc8d3de38..f103867cd8 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/DivUInt32.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/DivUInt32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; @@ -53,4 +56,4 @@ public void Simd() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/Divide.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/Divide.cs index df09aa569a..30dddf483a 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/Divide.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/Divide.cs @@ -1,10 +1,15 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; namespace ImageSharp.Benchmarks.General.Vectorization { +#pragma warning disable SA1649 // File name should match first type name public class DivFloat : SIMDBenchmarkBase.Divide +#pragma warning restore SA1649 // File name should match first type name { protected override float GetTestValue() => 42; @@ -53,7 +58,7 @@ public class DivInt16 : SIMDBenchmarkBase.Divide { protected override short GetTestValue() => 42; - protected override Vector GetTestVector() => new Vector(new short[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}); + protected override Vector GetTestVector() => new Vector(new short[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }); [Benchmark(Baseline = true)] public void Standard() @@ -65,4 +70,4 @@ public void Standard() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/MulFloat.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/MulFloat.cs index 79207a9ff3..61de537821 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/MulFloat.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/MulFloat.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/MulUInt32.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/MulUInt32.cs index d837556f7d..a800df405b 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/MulUInt32.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/MulUInt32.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/Multiply.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/Multiply.cs index 7a679c0009..5e9ffaae84 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/Multiply.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/Multiply.cs @@ -1,9 +1,14 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using BenchmarkDotNet.Attributes; namespace ImageSharp.Benchmarks.General.Vectorization { +#pragma warning disable SA1649 // File name should match first type name public class MulUInt32 : SIMDBenchmarkBase.Multiply +#pragma warning restore SA1649 // File name should match first type name { protected override uint GetTestValue() => 42u; @@ -47,4 +52,4 @@ public void Standard() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/Premultiply.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/Premultiply.cs index 23f13c89b7..cdc7cac2e8 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/Premultiply.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/Premultiply.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -56,4 +59,4 @@ public static void PremultiplyRefWithPropertyAssign(ref Vector4 source) source *= new Vector4(w) { W = 1 }; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/ReinterpretUInt32AsFloat.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/ReinterpretUInt32AsFloat.cs index 19a1bcea45..dc921bc420 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/ReinterpretUInt32AsFloat.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/ReinterpretUInt32AsFloat.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using System.Runtime.InteropServices; @@ -15,22 +18,20 @@ public class ReinterpretUInt32AsFloat public int InputSize { get; set; } [StructLayout(LayoutKind.Explicit)] - struct UIntFloatUnion + private struct UIntFloatUnion { [FieldOffset(0)] - public float f; + public float F; [FieldOffset(0)] - public uint i; + public uint I; } - [GlobalSetup] public void Setup() { this.input = new uint[this.InputSize]; this.result = new float[this.InputSize]; - for (int i = 0; i < this.InputSize; i++) { this.input[i] = (uint)i; @@ -43,8 +44,8 @@ public void Standard() UIntFloatUnion u = default; for (int i = 0; i < this.input.Length; i++) { - u.i = this.input[i]; - this.result[i] = u.f; + u.I = this.input[i]; + this.result[i] = u.F; } } @@ -54,7 +55,7 @@ public void Simd() for (int i = 0; i < this.input.Length; i += Vector.Count) { var a = new Vector(this.input, i); - Vector b = Vector.AsVectorSingle(a); + var b = Vector.AsVectorSingle(a); b.CopyTo(this.result, i); } } diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/SIMDBenchmarkBase.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/SIMDBenchmarkBase.cs index 8a14f02451..8fa0b5cfcf 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/SIMDBenchmarkBase.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/SIMDBenchmarkBase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using System.Runtime.CompilerServices; @@ -22,7 +25,7 @@ public abstract class SIMDBenchmarkBase [Params(32)] public int InputSize { get; set; } - + [GlobalSetup] public virtual void Setup() { @@ -63,7 +66,5 @@ public void Simd() } } } - - } } diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/UInt32ToSingle.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/UInt32ToSingle.cs index 2c9f4289e3..3c79df494e 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/UInt32ToSingle.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/UInt32ToSingle.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Numerics; using System.Runtime.CompilerServices; @@ -32,10 +35,6 @@ public void MagicMethod() for (int i = 0; i < n; i++) { - // union { float f; uint32_t i; } u; - // u.f = 32768.0f + x * (255.0f / 256.0f); - // return (uint8_t)u.i; - ref Vector df = ref Unsafe.Add(ref b, i); var vi = Vector.AsVectorUInt32(df); @@ -67,7 +66,7 @@ public void StandardSimd() Unsafe.Add(ref bf, i) = v; } } - + [Benchmark] public void StandardSimdFromInt() { @@ -87,7 +86,6 @@ public void StandardSimdFromInt() } } - [Benchmark] public void StandardSimdFromInt_RefCast() { diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/VectorFetching.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/VectorFetching.cs index 4d83dd4910..6d177588b4 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/VectorFetching.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/VectorFetching.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + namespace SixLabors.ImageSharp.Benchmarks.General.Vectorization { using System; @@ -18,13 +21,13 @@ public class VectorFetching [Params(64)] public int InputSize { get; set; } - + [GlobalSetup] public void Setup() { this.data = new float[this.InputSize]; this.testValue = 42; - + for (int i = 0; i < this.InputSize; i++) { this.data[i] = i; diff --git a/tests/ImageSharp.Benchmarks/General/Vectorization/WidenBytesToUInt32.cs b/tests/ImageSharp.Benchmarks/General/Vectorization/WidenBytesToUInt32.cs index 2bc3af4c98..870fe3271b 100644 --- a/tests/ImageSharp.Benchmarks/General/Vectorization/WidenBytesToUInt32.cs +++ b/tests/ImageSharp.Benchmarks/General/Vectorization/WidenBytesToUInt32.cs @@ -1,4 +1,7 @@ -using System.Numerics; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; @@ -61,4 +64,4 @@ public void Simd() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Samplers/Crop.cs b/tests/ImageSharp.Benchmarks/Samplers/Crop.cs index 4fe7a365f3..7fec81e710 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/Crop.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/Crop.cs @@ -1,14 +1,12 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using SixLabors.ImageSharp.PixelFormats; - using System.Drawing; using System.Drawing.Drawing2D; - using BenchmarkDotNet.Attributes; -using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; using CoreSize = SixLabors.Primitives.Size; namespace SixLabors.ImageSharp.Benchmarks @@ -26,7 +24,7 @@ public Size CropSystemDrawing() graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.DrawImage(source, new Rectangle(0, 0, 100, 100), 0, 0, 100, 100, GraphicsUnit.Pixel); - + return destination.Size; } } diff --git a/tests/ImageSharp.Benchmarks/Samplers/DetectEdges.cs b/tests/ImageSharp.Benchmarks/Samplers/DetectEdges.cs index b36b28ef33..7718e72159 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/DetectEdges.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/DetectEdges.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. using SixLabors.ImageSharp.PixelFormats; @@ -10,8 +10,7 @@ namespace SixLabors.ImageSharp.Benchmarks using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Processing; - - using CoreImage = ImageSharp.Image; + using CoreImage = SixLabors.ImageSharp.Image; public class DetectEdges : BenchmarkBase { @@ -51,4 +50,4 @@ public void ImageProcessorCoreDetectEdges() this.image.Mutate(x => x.DetectEdges(EdgeDetectionOperators.Sobel)); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Samplers/Diffuse.cs b/tests/ImageSharp.Benchmarks/Samplers/Diffuse.cs index c2b9cdc193..2d1e408fa9 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/Diffuse.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/Diffuse.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; @@ -26,11 +29,11 @@ public Size DoDiffuse() // BenchmarkDotNet=v0.11.5, OS=Windows 10.0.18362 // Intel Core i7-8650U CPU 1.90GHz(Kaby Lake R), 1 CPU, 8 logical and 4 physical cores // .NET Core SDK = 3.0.100 -// +// // [Host] : .NET Core 2.1.13 (CoreCLR 4.6.28008.01, CoreFX 4.6.28008.01), 64bit RyuJIT // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.8.4018.0 // Core : .NET Core 2.1.13 (CoreCLR 4.6.28008.01, CoreFX 4.6.28008.01), 64bit RyuJIT -// +// // IterationCount=3 LaunchCount=1 WarmupCount=3 // // #### Before #### @@ -39,9 +42,9 @@ public Size DoDiffuse() // |---------- |----- |-------- |----------:|---------:|---------:|------:|------:|------:|----------:| // | DoDiffuse | Clr | Clr | 129.58 ms | 24.60 ms | 1.349 ms | - | - | - | 6 KB | // | DoDiffuse | Core | Core | 92.63 ms | 89.78 ms | 4.921 ms | - | - | - | 4.58 KB | -// +// // #### After #### -// +// // | Method | Job | Runtime | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | // |---------- |----- |-------- |----------:|----------:|----------:|------:|------:|------:|----------:| // | DoDiffuse | Clr | Clr | 124.93 ms | 33.297 ms | 1.8251 ms | - | - | - | 2 KB | diff --git a/tests/ImageSharp.Benchmarks/Samplers/GaussianBlur.cs b/tests/ImageSharp.Benchmarks/Samplers/GaussianBlur.cs index 3a47d016a4..c5cfcb6eb2 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/GaussianBlur.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/GaussianBlur.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; diff --git a/tests/ImageSharp.Benchmarks/Samplers/Resize.cs b/tests/ImageSharp.Benchmarks/Samplers/Resize.cs index 172e243729..2d299baa96 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/Resize.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/Resize.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. using System.Drawing; @@ -14,7 +14,9 @@ namespace SixLabors.ImageSharp.Benchmarks { [Config(typeof(Config.ShortClr))] +#pragma warning disable SA1649 // File name should match first type name public abstract class ResizeBenchmarkBase +#pragma warning restore SA1649 // File name should match first type name where TPixel : struct, IPixel { protected readonly Configuration Configuration = new Configuration(new JpegConfigurationModule()); @@ -24,20 +26,18 @@ public abstract class ResizeBenchmarkBase private Bitmap sourceBitmap; [Params("3032-400")] - public virtual string SourceToDest { get; set; } - + public virtual string SourceToDest { get; set; } + protected int SourceSize { get; private set; } protected int DestSize { get; private set; } - [GlobalSetup] public virtual void Setup() { string[] stuff = this.SourceToDest.Split('-'); this.SourceSize = int.Parse(stuff[0], CultureInfo.InvariantCulture); this.DestSize = int.Parse(stuff[1], CultureInfo.InvariantCulture); - this.sourceImage = new Image(this.Configuration, this.SourceSize, this.SourceSize); this.sourceBitmap = new Bitmap(this.SourceSize, this.SourceSize); } @@ -75,11 +75,13 @@ public int SystemDrawing() // Parallel cases have been disabled for fast benchmark execution. // Uncomment, if you are interested in parallel speedup - //[Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 4")] - //public int ImageSharp_P4() => this.RunImageSharpResize(4); + /* + [Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 4")] + public int ImageSharp_P4() => this.RunImageSharpResize(4); - //[Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 8")] - //public int ImageSharp_P8() => this.RunImageSharpResize(8); + [Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 8")] + public int ImageSharp_P8() => this.RunImageSharpResize(8); + */ protected int RunImageSharpResize(int maxDegreeOfParallelism) { @@ -110,9 +112,9 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3394.0 // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // - // IterationCount=3 LaunchCount=1 WarmupCount=3 - // + // + // IterationCount=3 LaunchCount=1 WarmupCount=3 + // // Method | Job | Runtime | SourceToDest | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | // ----------------------------------------- |----- |-------- |------------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:| // SystemDrawing | Clr | Clr | 3032-400 | 120.11 ms | 1.435 ms | 0.0786 ms | 1.00 | 0.00 | - | - | - | 1638 B | @@ -157,9 +159,9 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0 // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // + // // IterationCount=3 LaunchCount=1 WarmupCount=3 - // + // // Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | // ----------------------------------------- |----- |-------- |----------- |--------- |----------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:| // SystemDrawing | Clr | Clr | 3032 | 400 | 119.01 ms | 18.513 ms | 1.0147 ms | 1.00 | - | - | - | 1638 B | @@ -185,7 +187,7 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0 // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // + // // Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | // ----------------------------------------- |----- |-------- |----------- |--------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:| // SystemDrawing | Clr | Clr | 3032 | 400 | 121.37 ms | 48.580 ms | 2.6628 ms | 1.00 | 0.00 | - | - | - | 2048 B | @@ -195,7 +197,6 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032 | 400 | 92.47 ms | 5.683 ms | 0.3115 ms | 0.78 | 0.01 | - | - | - | 44512 B | } - public class Resize_BicubicCompand_Rgba32 : ResizeBenchmarkBase { protected override void ExecuteResizeOperation(IImageProcessingContext ctx) @@ -212,9 +213,9 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT // Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0 // Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT - // + // // IterationCount=3 LaunchCount=1 WarmupCount=3 - // + // // Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | // ----------------------------------------- |----- |-------- |----------- |--------- |---------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:| // SystemDrawing | Clr | Clr | 3032 | 400 | 120.7 ms | 68.985 ms | 3.7813 ms | 1.00 | 0.00 | - | - | - | 1638 B | @@ -223,4 +224,4 @@ protected override void ExecuteResizeOperation(IImageProcessingContext ctx) // SystemDrawing | Core | Core | 3032 | 400 | 118.3 ms | 6.899 ms | 0.3781 ms | 1.00 | 0.00 | - | - | - | 96 B | // 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032 | 400 | 122.4 ms | 15.069 ms | 0.8260 ms | 1.03 | 0.01 | - | - | - | 15712 B | } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Benchmarks/Samplers/Rotate.cs b/tests/ImageSharp.Benchmarks/Samplers/Rotate.cs index 69ff1549bd..7bfa2a1ba1 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/Rotate.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/Rotate.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. using BenchmarkDotNet.Attributes; @@ -24,25 +24,27 @@ public Size DoRotate() } } -// Nov 7 2018 -//BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17763 -//Intel Core i7-6600U CPU 2.60GHz(Skylake), 1 CPU, 4 logical and 2 physical cores -//.NET Core SDK = 2.1.403 - -// [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT -// Job-KKDIMW : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0 -// Job-IUZRFA : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT - -//LaunchCount=1 TargetCount=3 WarmupCount=3 - -// #### BEFORE ####: -// Method | Runtime | Mean | Error | StdDev | Allocated | -//--------- |-------- |---------:|----------:|----------:|----------:| -// DoRotate | Clr | 85.19 ms | 13.379 ms | 0.7560 ms | 6 KB | -// DoRotate | Core | 53.51 ms | 9.512 ms | 0.5375 ms | 4.29 KB | - -// #### AFTER ####: -//Method | Runtime | Mean | Error | StdDev | Allocated | -//--------- |-------- |---------:|---------:|---------:|----------:| -// DoRotate | Clr | 77.08 ms | 23.97 ms | 1.354 ms | 6 KB | -// DoRotate | Core | 40.36 ms | 47.43 ms | 2.680 ms | 4.36 KB | \ No newline at end of file +/* + Nov 7 2018 +BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17763 +Intel Core i7-6600U CPU 2.60GHz(Skylake), 1 CPU, 4 logical and 2 physical cores +.NET Core SDK = 2.1.403 + + [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT + Job-KKDIMW : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0 + Job-IUZRFA : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT + +LaunchCount=1 TargetCount=3 WarmupCount=3 + + #### BEFORE ####: + Method | Runtime | Mean | Error | StdDev | Allocated | +--------- |-------- |---------:|----------:|----------:|----------:| + DoRotate | Clr | 85.19 ms | 13.379 ms | 0.7560 ms | 6 KB | + DoRotate | Core | 53.51 ms | 9.512 ms | 0.5375 ms | 4.29 KB | + + #### AFTER ####: +Method | Runtime | Mean | Error | StdDev | Allocated | +--------- |-------- |---------:|---------:|---------:|----------:| + DoRotate | Clr | 77.08 ms | 23.97 ms | 1.354 ms | 6 KB | + DoRotate | Core | 40.36 ms | 47.43 ms | 2.680 ms | 4.36 KB | + */ diff --git a/tests/ImageSharp.Benchmarks/Samplers/Skew.cs b/tests/ImageSharp.Benchmarks/Samplers/Skew.cs index 559e49704b..a1a5265852 100644 --- a/tests/ImageSharp.Benchmarks/Samplers/Skew.cs +++ b/tests/ImageSharp.Benchmarks/Samplers/Skew.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. using BenchmarkDotNet.Attributes; @@ -24,25 +24,27 @@ public Size DoSkew() } } -// Nov 7 2018 -//BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17763 -//Intel Core i7-6600U CPU 2.60GHz(Skylake), 1 CPU, 4 logical and 2 physical cores -//.NET Core SDK = 2.1.403 - -// [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT -// Job-KKDIMW : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0 -// Job-IUZRFA : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT - -//LaunchCount=1 TargetCount=3 WarmupCount=3 - -// #### BEFORE ####: -//Method | Runtime | Mean | Error | StdDev | Allocated | -//------- |-------- |---------:|---------:|----------:|----------:| -// DoSkew | Clr | 78.14 ms | 8.383 ms | 0.4736 ms | 6 KB | -// DoSkew | Core | 44.22 ms | 4.109 ms | 0.2322 ms | 4.28 KB | - -// #### AFTER ####: -//Method | Runtime | Mean | Error | StdDev | Allocated | -//------- |-------- |---------:|----------:|----------:|----------:| -// DoSkew | Clr | 71.63 ms | 25.589 ms | 1.4458 ms | 6 KB | -// DoSkew | Core | 38.99 ms | 8.640 ms | 0.4882 ms | 4.36 KB | \ No newline at end of file +/* + Nov 7 2018 +BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17763 +Intel Core i7-6600U CPU 2.60GHz(Skylake), 1 CPU, 4 logical and 2 physical cores +.NET Core SDK = 2.1.403 + + [Host] : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT + Job-KKDIMW : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0 + Job-IUZRFA : .NET Core 2.1.5 (CoreCLR 4.6.26919.02, CoreFX 4.6.26919.02), 64bit RyuJIT + +LaunchCount=1 TargetCount=3 WarmupCount=3 + + #### BEFORE ####: +Method | Runtime | Mean | Error | StdDev | Allocated | +------- |-------- |---------:|---------:|----------:|----------:| + DoSkew | Clr | 78.14 ms | 8.383 ms | 0.4736 ms | 6 KB | + DoSkew | Core | 44.22 ms | 4.109 ms | 0.2322 ms | 4.28 KB | + + #### AFTER ####: +Method | Runtime | Mean | Error | StdDev | Allocated | +------- |-------- |---------:|----------:|----------:|----------:| + DoSkew | Clr | 71.63 ms | 25.589 ms | 1.4458 ms | 6 KB | + DoSkew | Core | 38.99 ms | 8.640 ms | 0.4882 ms | 4.36 KB | + */ diff --git a/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj b/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj index e89b28dc11..cccad300d2 100644 --- a/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj +++ b/tests/ImageSharp.Sandbox46/ImageSharp.Sandbox46.csproj @@ -18,6 +18,10 @@ + + + + diff --git a/tests/ImageSharp.Sandbox46/Program.cs b/tests/ImageSharp.Sandbox46/Program.cs index 93fe74076e..d4fa2c784e 100644 --- a/tests/ImageSharp.Sandbox46/Program.cs +++ b/tests/ImageSharp.Sandbox46/Program.cs @@ -1,7 +1,5 @@ -// -// Copyright (c) James Jackson-South and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// using SixLabors.ImageSharp.Tests.PixelFormats.PixelOperations; using SixLabors.ImageSharp.Tests.ProfilingBenchmarks; diff --git a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs index 8d60338498..ae2f9a59bd 100644 --- a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs @@ -1,4 +1,3 @@ -// Copyright (c) Six Labors and contributors. // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. @@ -7,8 +6,8 @@ using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Advanced { public class AdvancedImageExtensionsTests @@ -17,7 +16,7 @@ public class GetPixelMemory { [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void WhenMemoryIsOwned(TestImageProvider provider) where TPixel : struct, IPixel { @@ -40,10 +39,9 @@ public void WhenMemoryIsOwned(TestImageProvider provider) } } - [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32 | PixelTypes.Bgr24)] - [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void WhenMemoryIsConsumed(TestImageProvider provider) where TPixel : struct, IPixel { @@ -73,7 +71,7 @@ public void WhenMemoryIsConsumed(TestImageProvider provider) [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void GetPixelRowMemory(TestImageProvider provider) where TPixel : struct, IPixel { @@ -99,7 +97,7 @@ public void GetPixelRowMemory(TestImageProvider provider) [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void GetPixelRowSpan(TestImageProvider provider) where TPixel : struct, IPixel { @@ -126,7 +124,7 @@ public void GetPixelRowSpan(TestImageProvider provider) #pragma warning disable 0618 [Theory] - [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public unsafe void DangerousGetPinnableReference_CopyToBuffer(TestImageProvider provider) where TPixel : struct, IPixel { @@ -136,7 +134,6 @@ public unsafe void DangerousGetPinnableReference_CopyToBuffer(TestImageP ref byte source = ref Unsafe.As(ref targetBuffer[0]); ref byte dest = ref Unsafe.As(ref image.DangerousGetPinnableReferenceToPixelBuffer()); - fixed (byte* targetPtr = &source) fixed (byte* pixelBasePtr = &dest) { diff --git a/tests/ImageSharp.Tests/Color/ColorTests.CastTo.cs b/tests/ImageSharp.Tests/Color/ColorTests.CastTo.cs index fbd1c73f16..c658227aeb 100644 --- a/tests/ImageSharp.Tests/Color/ColorTests.CastTo.cs +++ b/tests/ImageSharp.Tests/Color/ColorTests.CastTo.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.PixelFormats; diff --git a/tests/ImageSharp.Tests/Color/ColorTests.cs b/tests/ImageSharp.Tests/Color/ColorTests.cs index 6d9b34ee95..2ac774f53e 100644 --- a/tests/ImageSharp.Tests/Color/ColorTests.cs +++ b/tests/ImageSharp.Tests/Color/ColorTests.cs @@ -81,22 +81,22 @@ public class FromHex [Fact] public void ShortHex() { - Assert.Equal(new Rgb24(255, 255, 255), (Rgb24) Color.FromHex("#fff")); - Assert.Equal(new Rgb24(255, 255, 255), (Rgb24) Color.FromHex("fff")); - Assert.Equal(new Rgba32(0, 0, 0, 255), (Rgba32) Color.FromHex("000f")); + Assert.Equal(new Rgb24(255, 255, 255), (Rgb24)Color.FromHex("#fff")); + Assert.Equal(new Rgb24(255, 255, 255), (Rgb24)Color.FromHex("fff")); + Assert.Equal(new Rgba32(0, 0, 0, 255), (Rgba32)Color.FromHex("000f")); } [Fact] public void LeadingPoundIsOptional() { - Assert.Equal(new Rgb24(0, 128, 128), (Rgb24) Color.FromHex("#008080")); - Assert.Equal(new Rgb24(0, 128, 128), (Rgb24) Color.FromHex("008080")); + Assert.Equal(new Rgb24(0, 128, 128), (Rgb24)Color.FromHex("#008080")); + Assert.Equal(new Rgb24(0, 128, 128), (Rgb24)Color.FromHex("008080")); } [Fact] public void ThrowsOnEmpty() { - Assert.Throws(() => Color.FromHex("")); + Assert.Throws(() => Color.FromHex(string.Empty)); } [Fact] diff --git a/tests/ImageSharp.Tests/Color/ReferencePalette.cs b/tests/ImageSharp.Tests/Color/ReferencePalette.cs index 3c6e382c58..9896731e69 100644 --- a/tests/ImageSharp.Tests/Color/ReferencePalette.cs +++ b/tests/ImageSharp.Tests/Color/ReferencePalette.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.PixelFormats; @@ -274,4 +274,4 @@ internal static class ReferencePalette Rgba32.FromHex("#453b32") }; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/CieLabTests.cs b/tests/ImageSharp.Tests/Colorspaces/CieLabTests.cs index dbc07b916e..4bba0ab039 100644 --- a/tests/ImageSharp.Tests/Colorspaces/CieLabTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/CieLabTests.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. using System.Numerics; @@ -32,15 +32,15 @@ public void CieLabEquality() var y = new CieLab(Vector3.One); Assert.True(default(CieLab) == default(CieLab)); - Assert.True(default(CieLab) != new CieLab(1, 0, 1)); - Assert.False(default(CieLab) == new CieLab(1, 0, 1)); + Assert.True(new CieLab(1, 0, 1) != default(CieLab)); + Assert.False(new CieLab(1, 0, 1) == default(CieLab)); Assert.Equal(default(CieLab), default(CieLab)); Assert.Equal(new CieLab(1, 0, 1), new CieLab(1, 0, 1)); Assert.Equal(new CieLab(Vector3.One), new CieLab(Vector3.One)); Assert.False(x.Equals(y)); - Assert.False(default(CieLab) == new CieLab(1, 0, 1)); + Assert.False(new CieLab(1, 0, 1) == default(CieLab)); Assert.False(x.Equals((object)y)); Assert.False(x.GetHashCode().Equals(y.GetHashCode())); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/CieXyChromaticityCoordinatesTests.cs b/tests/ImageSharp.Tests/Colorspaces/CieXyChromaticityCoordinatesTests.cs index 42ace9dbed..4811a66d45 100644 --- a/tests/ImageSharp.Tests/Colorspaces/CieXyChromaticityCoordinatesTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/CieXyChromaticityCoordinatesTests.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. using SixLabors.ImageSharp.ColorSpaces; @@ -29,15 +29,15 @@ public void CieXyChromaticityCoordinatesEquality() var y = new CieXyChromaticityCoordinates(1, 1); Assert.True(default(CieXyChromaticityCoordinates) == default(CieXyChromaticityCoordinates)); - Assert.True(default(CieXyChromaticityCoordinates) != new CieXyChromaticityCoordinates(1, 0)); - Assert.False(default(CieXyChromaticityCoordinates) == new CieXyChromaticityCoordinates(1, 0)); + Assert.True(new CieXyChromaticityCoordinates(1, 0) != default(CieXyChromaticityCoordinates)); + Assert.False(new CieXyChromaticityCoordinates(1, 0) == default(CieXyChromaticityCoordinates)); Assert.Equal(default(CieXyChromaticityCoordinates), default(CieXyChromaticityCoordinates)); Assert.Equal(new CieXyChromaticityCoordinates(1, 0), new CieXyChromaticityCoordinates(1, 0)); Assert.Equal(new CieXyChromaticityCoordinates(1, 1), new CieXyChromaticityCoordinates(1, 1)); Assert.False(x.Equals(y)); - Assert.False(default(CieXyChromaticityCoordinates) == new CieXyChromaticityCoordinates(1, 0)); + Assert.False(new CieXyChromaticityCoordinates(1, 0) == default(CieXyChromaticityCoordinates)); Assert.False(x.Equals((object)y)); Assert.False(x.GetHashCode().Equals(y.GetHashCode())); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/ApproximateColorspaceComparer.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/ApproximateColorspaceComparer.cs index 7bf84dd0af..feb3b38f0a 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/ApproximateColorspaceComparer.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/ApproximateColorspaceComparer.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. using System.Collections.Generic; @@ -30,13 +30,13 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion IEqualityComparer, IEqualityComparer { - private readonly float Epsilon; + private readonly float epsilon; /// /// Initializes a new instance of the class. /// /// The comparison error difference epsilon to use. - public ApproximateColorSpaceComparer(float epsilon = 1F) => this.Epsilon = epsilon; + public ApproximateColorSpaceComparer(float epsilon = 1F) => this.epsilon = epsilon; /// public bool Equals(Rgb x, Rgb y) @@ -234,7 +234,7 @@ public bool Equals(RgbWorkingSpace x, RgbWorkingSpace y) private bool Equals(float x, float y) { float d = x - y; - return d >= -this.Epsilon && d <= this.Epsilon; + return d >= -this.epsilon && d <= this.epsilon; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchAndCieXyyConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchAndCieXyyConversionTests.cs index a65f618835..c5af017889 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchAndCieXyyConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchAndCieXyyConversionTests.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. using System; @@ -69,11 +69,10 @@ public void Convert_CieXyy_to_CieLch(float x, float y, float yl, float l, float // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchuvAndCieLuvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchuvAndCieLuvConversionTests.cs index 6829c62b50..e14d02faf4 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchuvAndCieLuvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchuvAndCieLuvConversionTests.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. using System; @@ -87,11 +87,10 @@ public void Convert_CieLuv_to_CieLchuv(float l, float u, float v, float l2, floa // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndCieXyyConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndCieXyyConversionTests.cs index 3b41204f7c..5566ce1b4c 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndCieXyyConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndCieXyyConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_CieXyy_to_CieLuv(float x, float y, float yl, float l, float // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHslConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHslConversionTests.cs index bfc0d2ecf1..f130bb9470 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHslConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHslConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Hsl_to_CieLuv(float h, float s, float l2, float l, float u, // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHsvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHsvConversionTests.cs index f11b17fff3..9e0af62eec 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHsvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHsvConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Hsv_to_CieLuv(float h, float s, float v2, float l, float u, // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHunterLabConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHunterLabConversionTests.cs index de2329c2ec..68fe54b517 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHunterLabConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndHunterLabConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_HunterLab_to_CieLuv(float l2, float a, float b, float l, flo // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLinearRgbConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLinearRgbConversionTests.cs index 3a1bd10c41..7c3e66f528 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLinearRgbConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLinearRgbConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_LinearRgb_to_CieLuv(float r, float g, float b, float l, floa // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLmsConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLmsConversionTests.cs index f3881f10f7..d42322336c 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLmsConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndLmsConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Lms_to_CieLuv(float l2, float m, float s, float l, float u, // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndRgbConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndRgbConversionTests.cs index 644f4577bf..8223ffdbce 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndRgbConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndRgbConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Rgb_to_CieLuv(float r, float g, float b, float l, float u, f // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndYCbCrConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndYCbCrConversionTests.cs index 41b9dba091..e300049df0 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndYCbCrConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieLuvAndYCbCrConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_YCbCr_to_CieLuv(float y, float cb, float cr, float l, float // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHslConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHslConversionTests.cs index 5b36beaab9..1c343afa29 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHslConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHslConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_Hsl_to_CieXyy(float h, float s, float l, float x, float y, f Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); + CieXyy actual = Converter.ToCieXyy(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHsvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHsvConversionTests.cs index da77378759..9a3cb8b010 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHsvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHsvConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Hsv_to_CieXyy(float h, float s, float v, float x, float y, f // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHunterLabConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHunterLabConversionTests.cs index 96d14c98a6..9e46024755 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHunterLabConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndHunterLabConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_HunterLab_to_CieXyy(float l, float a, float b, float x, floa Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); + CieXyy actual = Converter.ToCieXyy(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLinearRgbConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLinearRgbConversionTests.cs index 0339730945..71b41e6cab 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLinearRgbConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLinearRgbConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_LinearRgb_to_CieXyy(float r, float g, float b, float x, floa // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLmsConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLmsConversionTests.cs index fb0e06e6bb..4737ba59f8 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLmsConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndLmsConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_Lms_to_CieXyy(float l, float m, float s, float x, float y, f Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); + CieXyy actual = Converter.ToCieXyy(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndRgbConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndRgbConversionTests.cs index 5bbcd90875..1193ccaa19 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndRgbConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndRgbConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_Rgb_to_CieXyy(float r, float g, float b, float x, float y, f Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); + CieXyy actual = Converter.ToCieXyy(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndYCbCrConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndYCbCrConversionTests.cs index 1ee84ef2e5..b1342c80c4 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndYCbCrConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyyAndYCbCrConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_YCbCr_to_CieXyy(float y2, float cb, float cr, float x, float Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); + CieXyy actual = Converter.ToCieXyy(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchConversionTests.cs index 77f0c69699..42f00c51e0 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchConversionTests.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. using System; @@ -63,17 +63,16 @@ public void Convert_CieLch_to_CieXyz(float l, float c, float h, float x, float y Span actualSpan = new CieXyz[5]; // Act - var actual = Converter.ToCieXyz(input); + CieXyz actual = Converter.ToCieXyz(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchuvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchuvConversionTests.cs index 24e134d732..f123617731 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchuvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLchuvConversionTests.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. using System; @@ -63,17 +63,16 @@ public void Convert_CieLchuv_to_CieXyz(float l, float c, float h, float x, float Span actualSpan = new CieXyz[5]; // Act - var actual = Converter.ToCieXyz(input); + CieXyz actual = Converter.ToCieXyz(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHslConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHslConversionTests.cs index cd1c9f2c3e..eda5db125f 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHslConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHslConversionTests.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. using System; @@ -70,11 +70,10 @@ public void Convert_Hsl_to_CieXyz(float h, float s, float l, float x, float y, f // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHsvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHsvConversionTests.cs index 8112f6a198..47f780789b 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHsvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndHsvConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_Hsv_to_CieXyz(float h, float s, float v, float x, float y, f Span actualSpan = new CieXyz[5]; // Act - var actual = Converter.ToCieXyz(input); + CieXyz actual = Converter.ToCieXyz(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndYCbCrConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndYCbCrConversionTests.cs index 9ea890f101..d6d59ec076 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndYCbCrConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndYCbCrConversionTests.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. using System; @@ -64,17 +64,16 @@ public void Convert_YCbCr_to_CieXyz(float y2, float cb, float cr, float x, float Span actualSpan = new CieXyz[5]; // Act - var actual = Converter.ToCieXyz(input); + CieXyz actual = Converter.ToCieXyz(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); - for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs index 8b1fed84c2..8f9fef5e9e 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs @@ -72,7 +72,6 @@ public void Convert_Rgb_To_Hsl(float r, float g, float b, float h, float s, floa var input = new Rgb(r, g, b); var expected = new Hsl(h, s, l); - Span inputSpan = new Rgb[5]; inputSpan.Fill(input); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/VonKriesChromaticAdaptationTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/VonKriesChromaticAdaptationTests.cs index b1427f4d5f..bd870b01ac 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/VonKriesChromaticAdaptationTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/VonKriesChromaticAdaptationTests.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. using System; @@ -13,8 +13,8 @@ public class VonKriesChromaticAdaptationTests private static readonly ApproximateColorSpaceComparer ColorSpaceComparer = new ApproximateColorSpaceComparer(.0001F); public static readonly TheoryData WhitePoints = new TheoryData { - {CieLuv.DefaultWhitePoint, CieLab.DefaultWhitePoint}, - {CieLuv.DefaultWhitePoint, CieLuv.DefaultWhitePoint} + { CieLuv.DefaultWhitePoint, CieLab.DefaultWhitePoint }, + { CieLuv.DefaultWhitePoint, CieLuv.DefaultWhitePoint } }; [Theory] diff --git a/tests/ImageSharp.Tests/Colorspaces/HunterLabTests.cs b/tests/ImageSharp.Tests/Colorspaces/HunterLabTests.cs index 95261e1d98..a657098f57 100644 --- a/tests/ImageSharp.Tests/Colorspaces/HunterLabTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/HunterLabTests.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. using System.Numerics; @@ -32,8 +32,8 @@ public void HunterLabEquality() var y = new HunterLab(Vector3.One); Assert.True(default(HunterLab) == default(HunterLab)); - Assert.True(default(HunterLab) != new HunterLab(1, 0, 1)); - Assert.False(default(HunterLab) == new HunterLab(1, 0, 1)); + Assert.True(new HunterLab(1, 0, 1) != default(HunterLab)); + Assert.False(new HunterLab(1, 0, 1) == default(HunterLab)); Assert.Equal(default(HunterLab), default(HunterLab)); Assert.Equal(new HunterLab(1, 0, 1), new HunterLab(1, 0, 1)); Assert.Equal(new HunterLab(Vector3.One), new HunterLab(Vector3.One)); @@ -42,4 +42,4 @@ public void HunterLabEquality() Assert.False(x.GetHashCode().Equals(y.GetHashCode())); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/LmsTests.cs b/tests/ImageSharp.Tests/Colorspaces/LmsTests.cs index 1b0939dc5c..f0c1471e0c 100644 --- a/tests/ImageSharp.Tests/Colorspaces/LmsTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/LmsTests.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. using System.Numerics; @@ -18,11 +18,11 @@ public void LmsConstructorAssignsFields() const float l = 75F; const float m = -64F; const float s = 87F; - var Lms = new Lms(l, m, s); + var lms = new Lms(l, m, s); - Assert.Equal(l, Lms.L); - Assert.Equal(m, Lms.M); - Assert.Equal(s, Lms.S); + Assert.Equal(l, lms.L); + Assert.Equal(m, lms.M); + Assert.Equal(s, lms.S); } [Fact] @@ -32,8 +32,8 @@ public void LmsEquality() var y = new Lms(Vector3.One); Assert.True(default(Lms) == default(Lms)); - Assert.True(default(Lms) != new Lms(1, 0, 1)); - Assert.False(default(Lms) == new Lms(1, 0, 1)); + Assert.True(new Lms(1, 0, 1) != default(Lms)); + Assert.False(new Lms(1, 0, 1) == default(Lms)); Assert.Equal(default(Lms), default(Lms)); Assert.Equal(new Lms(1, 0, 1), new Lms(1, 0, 1)); Assert.Equal(new Lms(Vector3.One), new Lms(Vector3.One)); @@ -42,4 +42,4 @@ public void LmsEquality() Assert.False(x.GetHashCode().Equals(y.GetHashCode())); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Colorspaces/StringRepresentationTests.cs b/tests/ImageSharp.Tests/Colorspaces/StringRepresentationTests.cs index 5249b709b1..211b98abb3 100644 --- a/tests/ImageSharp.Tests/Colorspaces/StringRepresentationTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/StringRepresentationTests.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. using System.Numerics; @@ -9,58 +9,56 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces { public class StringRepresentationTests { - private static readonly Vector3 one = new Vector3(1); - private static readonly Vector3 zero = new Vector3(0); - private static readonly Vector3 random = new Vector3(42.4F, 94.5F, 83.4F); + private static readonly Vector3 One = new Vector3(1); + private static readonly Vector3 Zero = new Vector3(0); + private static readonly Vector3 Random = new Vector3(42.4F, 94.5F, 83.4F); public static readonly TheoryData TestData = new TheoryData { - { new CieLab(zero), "CieLab(0, 0, 0)" }, - { new CieLch(zero), "CieLch(0, 0, 0)" }, - { new CieLchuv(zero), "CieLchuv(0, 0, 0)" }, - { new CieLuv(zero), "CieLuv(0, 0, 0)" }, - { new CieXyz(zero), "CieXyz(0, 0, 0)" }, - { new CieXyy(zero), "CieXyy(0, 0, 0)" }, - { new HunterLab(zero), "HunterLab(0, 0, 0)" }, - { new Lms(zero), "Lms(0, 0, 0)" }, - { new LinearRgb(zero), "LinearRgb(0, 0, 0)" }, - { new Rgb(zero), "Rgb(0, 0, 0)" }, - { new Hsl(zero), "Hsl(0, 0, 0)" }, - { new Hsv(zero), "Hsv(0, 0, 0)" }, - { new YCbCr(zero), "YCbCr(0, 0, 0)" }, - - { new CieLab(one), "CieLab(1, 1, 1)" }, - { new CieLch(one), "CieLch(1, 1, 1)" }, - { new CieLchuv(one), "CieLchuv(1, 1, 1)" }, - { new CieLuv(one), "CieLuv(1, 1, 1)" }, - { new CieXyz(one), "CieXyz(1, 1, 1)" }, - { new CieXyy(one), "CieXyy(1, 1, 1)" }, - { new HunterLab(one), "HunterLab(1, 1, 1)" }, - { new Lms(one), "Lms(1, 1, 1)" }, - { new LinearRgb(one), "LinearRgb(1, 1, 1)" }, - { new Rgb(one), "Rgb(1, 1, 1)" }, - { new Hsl(one), "Hsl(1, 1, 1)" }, - { new Hsv(one), "Hsv(1, 1, 1)" }, - { new YCbCr(one), "YCbCr(1, 1, 1)" }, - { new CieXyChromaticityCoordinates(1, 1), "CieXyChromaticityCoordinates(1, 1)"}, - - { new CieLab(random), "CieLab(42.4, 94.5, 83.4)" }, - { new CieLch(random), "CieLch(42.4, 94.5, 83.4)" }, - { new CieLchuv(random), "CieLchuv(42.4, 94.5, 83.4)" }, - { new CieLuv(random), "CieLuv(42.4, 94.5, 83.4)" }, - { new CieXyz(random), "CieXyz(42.4, 94.5, 83.4)" }, - { new CieXyy(random), "CieXyy(42.4, 94.5, 83.4)" }, - { new HunterLab(random), "HunterLab(42.4, 94.5, 83.4)" }, - { new Lms(random), "Lms(42.4, 94.5, 83.4)" }, - { new LinearRgb(random), "LinearRgb(1, 1, 1)" }, // clamping to 1 is expected - { new Rgb(random), "Rgb(1, 1, 1)" }, // clamping to 1 is expected - { new Hsl(random), "Hsl(42.4, 1, 1)" }, // clamping to 1 is expected - { new Hsv(random), "Hsv(42.4, 1, 1)" }, // clamping to 1 is expected - { new YCbCr(random), "YCbCr(42.4, 94.5, 83.4)" }, - }; + { new CieLab(Zero), "CieLab(0, 0, 0)" }, + { new CieLch(Zero), "CieLch(0, 0, 0)" }, + { new CieLchuv(Zero), "CieLchuv(0, 0, 0)" }, + { new CieLuv(Zero), "CieLuv(0, 0, 0)" }, + { new CieXyz(Zero), "CieXyz(0, 0, 0)" }, + { new CieXyy(Zero), "CieXyy(0, 0, 0)" }, + { new HunterLab(Zero), "HunterLab(0, 0, 0)" }, + { new Lms(Zero), "Lms(0, 0, 0)" }, + { new LinearRgb(Zero), "LinearRgb(0, 0, 0)" }, + { new Rgb(Zero), "Rgb(0, 0, 0)" }, + { new Hsl(Zero), "Hsl(0, 0, 0)" }, + { new Hsv(Zero), "Hsv(0, 0, 0)" }, + { new YCbCr(Zero), "YCbCr(0, 0, 0)" }, + { new CieLab(One), "CieLab(1, 1, 1)" }, + { new CieLch(One), "CieLch(1, 1, 1)" }, + { new CieLchuv(One), "CieLchuv(1, 1, 1)" }, + { new CieLuv(One), "CieLuv(1, 1, 1)" }, + { new CieXyz(One), "CieXyz(1, 1, 1)" }, + { new CieXyy(One), "CieXyy(1, 1, 1)" }, + { new HunterLab(One), "HunterLab(1, 1, 1)" }, + { new Lms(One), "Lms(1, 1, 1)" }, + { new LinearRgb(One), "LinearRgb(1, 1, 1)" }, + { new Rgb(One), "Rgb(1, 1, 1)" }, + { new Hsl(One), "Hsl(1, 1, 1)" }, + { new Hsv(One), "Hsv(1, 1, 1)" }, + { new YCbCr(One), "YCbCr(1, 1, 1)" }, + { new CieXyChromaticityCoordinates(1, 1), "CieXyChromaticityCoordinates(1, 1)" }, + { new CieLab(Random), "CieLab(42.4, 94.5, 83.4)" }, + { new CieLch(Random), "CieLch(42.4, 94.5, 83.4)" }, + { new CieLchuv(Random), "CieLchuv(42.4, 94.5, 83.4)" }, + { new CieLuv(Random), "CieLuv(42.4, 94.5, 83.4)" }, + { new CieXyz(Random), "CieXyz(42.4, 94.5, 83.4)" }, + { new CieXyy(Random), "CieXyy(42.4, 94.5, 83.4)" }, + { new HunterLab(Random), "HunterLab(42.4, 94.5, 83.4)" }, + { new Lms(Random), "Lms(42.4, 94.5, 83.4)" }, + { new LinearRgb(Random), "LinearRgb(1, 1, 1)" }, // clamping to 1 is expected + { new Rgb(Random), "Rgb(1, 1, 1)" }, // clamping to 1 is expected + { new Hsl(Random), "Hsl(42.4, 1, 1)" }, // clamping to 1 is expected + { new Hsv(Random), "Hsv(42.4, 1, 1)" }, // clamping to 1 is expected + { new YCbCr(Random), "YCbCr(42.4, 94.5, 83.4)" }, + }; [Theory] [MemberData(nameof(TestData))] public void StringRepresentationsAreCorrect(object color, string text) => Assert.Equal(text, color.ToString()); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Common/EncoderExtensionsTests.cs b/tests/ImageSharp.Tests/Common/EncoderExtensionsTests.cs index e1b4fc790c..edaad4f51c 100644 --- a/tests/ImageSharp.Tests/Common/EncoderExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Common/EncoderExtensionsTests.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. using System; @@ -12,7 +12,7 @@ public class EncoderExtensionsTests [Fact] public void GetString_EmptyBuffer_ReturnsEmptyString() { - var buffer = new ReadOnlySpan(); + var buffer = default(ReadOnlySpan); string result = Encoding.UTF8.GetString(buffer); diff --git a/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs b/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs index 58317ca49f..6bf3d07457 100644 --- a/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs +++ b/tests/ImageSharp.Tests/Common/SimdUtilsTests.cs @@ -55,6 +55,7 @@ private static Vector CreateExactTestVector1() { data[i] = data[i - 4] + 100f; } + return new Vector(data); } @@ -66,7 +67,7 @@ private static Vector CreateRandomTestVector(int seed, float min, float m for (int i = 0; i < Vector.Count; i++) { - float v = (float)rnd.NextDouble() * (max - min) + min; + float v = ((float)rnd.NextDouble() * (max - min)) + min; data[i] = v; } @@ -132,7 +133,7 @@ public void BasicIntrinsics256_BulkConvertNormalizedFloatToByte_WithRoundedData( SimdUtils.BasicIntrinsics256.BulkConvertNormalizedFloatToByte(normalized, dest); - byte[] expected = orig.Select(f => (byte)(f)).ToArray(); + byte[] expected = orig.Select(f => (byte)f).ToArray(); Assert.Equal(expected, dest); } @@ -229,9 +230,9 @@ private static void TestImpl_BulkConvertByteToNormalizedFloat( [MemberData(nameof(ArraySizesDivisibleBy4))] public void FallbackIntrinsics128_BulkConvertNormalizedFloatToByteClampOverflows(int count) { - TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, - (s, d) => SimdUtils.FallbackIntrinsics128.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span) - ); + TestImpl_BulkConvertNormalizedFloatToByteClampOverflows( + count, + (s, d) => SimdUtils.FallbackIntrinsics128.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span)); } [Theory] @@ -243,18 +244,16 @@ public void BasicIntrinsics256_BulkConvertNormalizedFloatToByteClampOverflows(in return; } - TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, - (s, d) => SimdUtils.BasicIntrinsics256.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span) - ); + TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, (s, d) => SimdUtils.BasicIntrinsics256.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span)); } [Theory] [MemberData(nameof(ArraySizesDivisibleBy32))] public void ExtendedIntrinsics_BulkConvertNormalizedFloatToByteClampOverflows(int count) { - TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, - (s, d) => SimdUtils.ExtendedIntrinsics.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span) - ); + TestImpl_BulkConvertNormalizedFloatToByteClampOverflows( + count, + (s, d) => SimdUtils.ExtendedIntrinsics.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span)); } [Theory] @@ -282,11 +281,9 @@ public void ExtendedIntrinsics_ConvertToSingle(short scale) [MemberData(nameof(ArbitraryArraySizes))] public void BulkConvertNormalizedFloatToByteClampOverflows(int count) { - TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, - (s, d) => SimdUtils.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span) - ); + TestImpl_BulkConvertNormalizedFloatToByteClampOverflows(count, (s, d) => SimdUtils.BulkConvertNormalizedFloatToByteClampOverflows(s.Span, d.Span)); - // for small values, let's stress test the implementation a bit: + // For small values, let's stress test the implementation a bit: if (count > 0 && count < 10) { for (int i = 0; i < 20; i++) @@ -301,7 +298,9 @@ public void BulkConvertNormalizedFloatToByteClampOverflows(int count) private static void TestImpl_BulkConvertNormalizedFloatToByteClampOverflows( int count, - Action, Memory> convert, int seed = -1) + Action, + Memory> convert, + int seed = -1) { seed = seed > 0 ? seed : count; float[] source = new Random(seed).GenerateRandomFloatArray(count, -0.2f, 1.2f); @@ -313,7 +312,7 @@ private static void TestImpl_BulkConvertNormalizedFloatToByteClampOverflows( Assert.Equal(expected, actual); } - private static byte NormalizedFloatToByte(float f) => (byte)Math.Min(255f, Math.Max(0f, f * 255f + 0.5f)); + private static byte NormalizedFloatToByte(float f) => (byte)Math.Min(255f, Math.Max(0f, (f * 255f) + 0.5f)); [Theory] [InlineData(0)] diff --git a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs index 8b2c65b07b..d47d5da8ef 100644 --- a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.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. using System; @@ -67,7 +67,10 @@ private class SeekableStream : MemoryStream public long Offset; public SeekOrigin Loc; - public SeekableStream(int capacity) : base(capacity) { } + public SeekableStream(int capacity) + : base(capacity) + { + } public override long Seek(long offset, SeekOrigin loc) { @@ -83,7 +86,10 @@ private class NonSeekableStream : MemoryStream public List Counts = new List(); - public NonSeekableStream() : base(4) { } + public NonSeekableStream() + : base(4) + { + } public override int Read(byte[] buffer, int offset, int count) { @@ -97,7 +103,10 @@ private class EofStream : MemoryStream { public override bool CanSeek => false; - public EofStream(int capacity) : base(capacity) { } + public EofStream(int capacity) + : base(capacity) + { + } public override int Read(byte[] buffer, int offset, int count) { diff --git a/tests/ImageSharp.Tests/Common/Tuple8.cs b/tests/ImageSharp.Tests/Common/Tuple8.cs index 3335e6e377..7c7f254db9 100644 --- a/tests/ImageSharp.Tests/Common/Tuple8.cs +++ b/tests/ImageSharp.Tests/Common/Tuple8.cs @@ -1,4 +1,7 @@ -using System.Runtime.InteropServices; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Runtime.InteropServices; namespace SixLabors.ImageSharp.Common.Tuples { @@ -95,4 +98,4 @@ public void LoadFrom(ref OfUInt32 i) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/ConfigurationTests.cs b/tests/ImageSharp.Tests/ConfigurationTests.cs index 6b35bbb972..a68baf93fb 100644 --- a/tests/ImageSharp.Tests/ConfigurationTests.cs +++ b/tests/ImageSharp.Tests/ConfigurationTests.cs @@ -8,8 +8,8 @@ using SixLabors.ImageSharp.IO; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { /// @@ -18,6 +18,7 @@ namespace SixLabors.ImageSharp.Tests public class ConfigurationTests { public Configuration ConfigurationEmpty { get; } + public Configuration DefaultConfiguration { get; } private readonly int expectedDefaultConfigurationCount = 5; @@ -87,7 +88,6 @@ public void MaxDegreeOfParallelism_CompatibleWith_ParallelOptions(int maxDegreeO } } - [Fact] public void ConstructorCallConfigureOnFormatProvider() { @@ -112,11 +112,11 @@ public void ConfigurationCannotAddDuplicates() { Configuration config = this.DefaultConfiguration; - Assert.Equal(expectedDefaultConfigurationCount, config.ImageFormats.Count()); + Assert.Equal(this.expectedDefaultConfigurationCount, config.ImageFormats.Count()); config.ImageFormatsManager.AddImageFormat(BmpFormat.Instance); - Assert.Equal(expectedDefaultConfigurationCount, config.ImageFormats.Count()); + Assert.Equal(this.expectedDefaultConfigurationCount, config.ImageFormats.Count()); } [Fact] @@ -124,14 +124,14 @@ public void DefaultConfigurationHasCorrectFormatCount() { Configuration config = Configuration.CreateDefaultInstance(); - Assert.Equal(expectedDefaultConfigurationCount, config.ImageFormats.Count()); + Assert.Equal(this.expectedDefaultConfigurationCount, config.ImageFormats.Count()); } [Fact] public void WorkingBufferSizeHint_DefaultIsCorrect() { Configuration config = this.DefaultConfiguration; - Assert.True(config.WorkingBufferSizeHintInBytes > 1024); + Assert.True(config.WorkingBufferSizeHintInBytes > 1024); } } } diff --git a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs index 202cd04c9b..729ae7b9a4 100644 --- a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs @@ -45,7 +45,8 @@ public void ImageBlendingMatchesSvgSpecExamples(TestImageProvider(TestImageProvider( } image.DebugSave(provider, testInfo, encoder: encoder); - image.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.01f), provider, testInfo); } } [Theory] - [WithTestPatternImages(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImage(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void DrawImageOfDifferentPixelType(TestImageProvider provider) where TPixel : struct, IPixel { @@ -167,7 +169,8 @@ public void DrawTransformed(TestImageProvider provider) image.Mutate(x => x.DrawImage(blend, position, .75F)); image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.002f), + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.002f), provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); @@ -194,7 +197,5 @@ void Test() } } } - - } } diff --git a/tests/ImageSharp.Tests/FileTestBase.cs b/tests/ImageSharp.Tests/FileTestBase.cs index 4f8475738b..12f7636a2e 100644 --- a/tests/ImageSharp.Tests/FileTestBase.cs +++ b/tests/ImageSharp.Tests/FileTestBase.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. using System; @@ -71,22 +71,23 @@ public static class Extensions /// protected static readonly List Files = new List { - TestFile.Create(TestImages.Jpeg.Baseline.Calliphora), - //TestFile.Create(TestImages.Jpeg.Baseline.Turtle), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.Ycck), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.Cmyk), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.Floorplan), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Progressive.Festzug), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.Bad.BadEOF), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.Bad.ExifUndefType), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Progressive.Fb), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Progressive.Progress), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Baseline.GammaDalaiLamaGray), // Perf: Enable for local testing only - //TestFile.Create(TestImages.Jpeg.Progressive.Bad.BadEOF), // Perf: Enable for local testing only - TestFile.Create(TestImages.Bmp.Car), +#pragma warning disable SA1515 // Single-line comment should be preceded by blank line + TestFile.Create(TestImages.Jpeg.Baseline.Calliphora), + // TestFile.Create(TestImages.Jpeg.Baseline.Turtle), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.Ycck), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.Cmyk), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.Floorplan), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Progressive.Festzug), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.Bad.BadEOF), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.Bad.ExifUndefType), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Progressive.Fb), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Progressive.Progress), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Baseline.GammaDalaiLamaGray), // Perf: Enable for local testing only + // TestFile.Create(TestImages.Jpeg.Progressive.Bad.BadEOF), // Perf: Enable for local testing only + TestFile.Create(TestImages.Bmp.Car), // TestFile.Create(TestImages.Bmp.NegHeight), // Perf: Enable for local testing only // TestFile.Create(TestImages.Bmp.CoreHeader), // Perf: Enable for local testing only - TestFile.Create(TestImages.Png.Splash), + TestFile.Create(TestImages.Png.Splash), // TestFile.Create(TestImages.Png.SnakeGame), // TestFile.Create(TestImages.Png.Cross), // Perf: Enable for local testing only // TestFile.Create(TestImages.Png.Bad.ChunkLength1), // Perf: Enable for local testing only @@ -104,10 +105,11 @@ public static class Extensions // TestFile.Create(TestImages.Png.FilterVar), // Perf: Enable for local testing only // TestFile.Create(TestImages.Png.P1), // Perf: Enable for local testing only // TestFile.Create(TestImages.Png.Pd), // Perf: Enable for local testing only - TestFile.Create(TestImages.Gif.Rings), + TestFile.Create(TestImages.Gif.Rings), // TestFile.Create(TestImages.Gif.Trans), // Perf: Enable for local testing only // TestFile.Create(TestImages.Gif.Cheers), // Perf: Enable for local testing only // TestFile.Create(TestImages.Gif.Giphy) // Perf: Enable for local testing only }; +#pragma warning restore SA1515 // Single-line comment should be preceded by blank line } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs index ecec6f0a7a..fb3348be72 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs @@ -11,7 +11,6 @@ using Xunit; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Formats.Bmp { using SixLabors.ImageSharp.Metadata; @@ -28,8 +27,8 @@ public class BmpDecoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { Car, 3780, 3780 , PixelResolutionUnit.PixelsPerMeter }, - { V5Header, 3780, 3780 , PixelResolutionUnit.PixelsPerMeter }, + { Car, 3780, 3780, PixelResolutionUnit.PixelsPerMeter }, + { V5Header, 3780, 3780, PixelResolutionUnit.PixelsPerMeter }, { RLE8, 2835, 2835, PixelResolutionUnit.PixelsPerMeter } }; @@ -94,6 +93,7 @@ public void BmpDecoder_CanDecode_4Bit(TestImageProvider provider using (Image image = provider.GetImage(new BmpDecoder())) { image.DebugSave(provider); + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. if (TestEnvironment.IsWindows) { @@ -160,6 +160,7 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit_WithDelta(TestIma using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) { image.DebugSave(provider); + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. if (TestEnvironment.IsWindows) { @@ -176,6 +177,7 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit(TestImageProvider using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) { image.DebugSave(provider); + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. if (TestEnvironment.IsWindows) { @@ -346,7 +348,12 @@ public void BmpDecoder_CanDecodeOversizedPalette(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - Assert.Throws( () => { using (provider.GetImage(new BmpDecoder())) { } }); + Assert.Throws(() => + { + using (provider.GetImage(new BmpDecoder())) + { + } + }); } [Theory] @@ -355,7 +362,12 @@ public void BmpDecoder_ThrowsImageFormatException_OnInvalidPaletteSize(T public void BmpDecoder_ThrowsNotSupportedException_OnUnsupportedBitmaps(TestImageProvider provider) where TPixel : struct, IPixel { - Assert.Throws(() => { using (provider.GetImage(new BmpDecoder())) { } }); + Assert.Throws(() => + { + using (provider.GetImage(new BmpDecoder())) + { + } + }); } [Theory] diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs index fd9f50a294..6a218abe2b 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs @@ -15,7 +15,6 @@ using Xunit.Abstractions; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Formats.Bmp { using static TestImages.Bmp; @@ -32,8 +31,8 @@ public class BmpEncoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { Car, 3780, 3780 , PixelResolutionUnit.PixelsPerMeter }, - { V5Header, 3780, 3780 , PixelResolutionUnit.PixelsPerMeter }, + { Car, 3780, 3780, PixelResolutionUnit.PixelsPerMeter }, + { V5Header, 3780, 3780, PixelResolutionUnit.PixelsPerMeter }, { RLE8, 2835, 2835, PixelResolutionUnit.PixelsPerMeter } }; @@ -98,16 +97,16 @@ public void Encode_PreserveBitsPerPixel(string imagePath, BmpBitsPerPixel bmpBit } [Theory] - [WithTestPatternImages(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] + [WithTestPatternImage(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] public void Encode_IsNotBoundToSinglePixelType(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel); [Theory] - [WithTestPatternImages(nameof(BitsPerPixel), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel), 47, 8, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel), 49, 7, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel), 47, 8, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel), 49, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BitsPerPixel), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel), 7, 5, PixelTypes.Rgba32)] public void Encode_WorksWithDifferentSizes(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel); @@ -117,7 +116,8 @@ public void Encode_WorksWithDifferentSizes(TestImageProvider pro [WithFile(WinBmpv4, PixelTypes.Rgba32 | PixelTypes.Rgb24, BmpBitsPerPixel.Pixel32)] [WithFile(WinBmpv5, PixelTypes.Rgba32 | PixelTypes.Rgb24, BmpBitsPerPixel.Pixel32)] public void Encode_32Bit_WithV3Header_Works(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) - // if supportTransparency is false, a v3 bitmap header will be written + + // If supportTransparency is false, a v3 bitmap header will be written. where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel, supportTransparency: false); [Theory] @@ -129,8 +129,7 @@ public void Encode_32Bit_WithV4Header_Works(TestImageProvider pr where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel, supportTransparency: true); [Theory] - // WinBmpv3 is a 24 bits per pixel image - [WithFile(WinBmpv3, PixelTypes.Rgb24, BmpBitsPerPixel.Pixel24)] + [WithFile(WinBmpv3, PixelTypes.Rgb24, BmpBitsPerPixel.Pixel24)] // WinBmpv3 is a 24 bits per pixel image. [WithFile(F, PixelTypes.Rgb24, BmpBitsPerPixel.Pixel24)] public void Encode_24Bit_WithV3Header_Works(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel, supportTransparency: false); @@ -141,7 +140,6 @@ public void Encode_24Bit_WithV3Header_Works(TestImageProvider pr public void Encode_24Bit_WithV4Header_Works(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel, supportTransparency: true); - [Theory] [WithFile(Rgb16, PixelTypes.Bgra5551, BmpBitsPerPixel.Pixel16)] [WithFile(Bit16, PixelTypes.Bgra5551, BmpBitsPerPixel.Pixel16)] diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs index 4eac337307..9818f9d41f 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs @@ -7,7 +7,6 @@ using Xunit; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Formats.Bmp { using static TestImages.Bmp; diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs index eb39c28479..f9c87e08e5 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs @@ -8,8 +8,8 @@ using SixLabors.ImageSharp.Processing.Processors.Quantization; using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Gif { public class GifEncoderTests @@ -20,13 +20,13 @@ public class GifEncoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Gif.Rings, (int)ImageMetadata.DefaultHorizontalResolution, (int)ImageMetadata.DefaultVerticalResolution , PixelResolutionUnit.PixelsPerInch}, - { TestImages.Gif.Ratio1x4, 1, 4 , PixelResolutionUnit.AspectRatio}, + { TestImages.Gif.Rings, (int)ImageMetadata.DefaultHorizontalResolution, (int)ImageMetadata.DefaultVerticalResolution, PixelResolutionUnit.PixelsPerInch }, + { TestImages.Gif.Ratio1x4, 1, 4, PixelResolutionUnit.AspectRatio }, { TestImages.Gif.Ratio4x1, 4, 1, PixelResolutionUnit.AspectRatio } }; [Theory] - [WithTestPatternImages(100, 100, TestPixelTypes)] + [WithTestPatternImage(100, 100, TestPixelTypes)] public void EncodeGeneratedPatterns(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs index 7f1acf71e1..cb99bc528d 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs @@ -18,8 +18,8 @@ public class GifMetadataTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Gif.Rings, (int)ImageMetadata.DefaultHorizontalResolution, (int)ImageMetadata.DefaultVerticalResolution , PixelResolutionUnit.PixelsPerInch}, - { TestImages.Gif.Ratio1x4, 1, 4 , PixelResolutionUnit.AspectRatio}, + { TestImages.Gif.Rings, (int)ImageMetadata.DefaultHorizontalResolution, (int)ImageMetadata.DefaultVerticalResolution, PixelResolutionUnit.PixelsPerInch }, + { TestImages.Gif.Ratio1x4, 1, 4, PixelResolutionUnit.AspectRatio }, { TestImages.Gif.Ratio4x1, 4, 1, PixelResolutionUnit.AspectRatio } }; diff --git a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs index 9a15e1c1b3..d011a63301 100644 --- a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs +++ b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs @@ -13,12 +13,12 @@ using SixLabors.ImageSharp.PixelFormats; using Xunit; - namespace SixLabors.ImageSharp.Tests { public class ImageFormatManagerTests { public ImageFormatManager FormatsManagerEmpty { get; } + public ImageFormatManager DefaultFormatsManager { get; } public ImageFormatManagerTests() @@ -28,7 +28,7 @@ public ImageFormatManagerTests() } [Fact] - public void IfAutoloadWellKnownFormatsIsTrueAllFormatsAreLoaded() + public void IfAutoLoadWellKnownFormatsIsTrueAllFormatsAreLoaded() { Assert.Equal(1, this.DefaultFormatsManager.ImageEncoders.Select(item => item.Value).OfType().Count()); Assert.Equal(1, this.DefaultFormatsManager.ImageEncoders.Select(item => item.Value).OfType().Count()); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs index 4b1abf9094..2f0158f4b0 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs @@ -1,9 +1,8 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. // Uncomment this to turn unit tests into benchmarks: -//#define BENCHMARKING - +// #define BENCHMARKING using SixLabors.ImageSharp.Formats.Jpeg.Components; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Tests.Formats.Jpg.Utils; @@ -12,8 +11,8 @@ using Xunit; using Xunit.Abstractions; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public partial class Block8x8FTests @@ -31,7 +30,7 @@ private static void VerifyAllZeroOutsideSubArea(Buffer2D buffer, int subX { for (int x = 0; x < 20; x++) { - if (x < subX || x >= subX + 8 * horizontalFactor || y < subY || y >= subY + 8 * verticalFactor) + if (x < subX || x >= subX + (8 * horizontalFactor) || y < subY || y >= subY + (8 * verticalFactor)) { Assert.Equal(0, buffer[x, y]); } @@ -96,4 +95,4 @@ public void CopyTo(int horizontalFactor, int verticalFactor) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.cs index 21b9b6cab6..ef8804242f 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.cs @@ -2,8 +2,7 @@ // Licensed under the Apache License, Version 2.0. // Uncomment this to turn unit tests into benchmarks: -//#define BENCHMARKING - +// #define BENCHMARKING using System; using System.Diagnostics; @@ -35,6 +34,7 @@ private bool SkipOnNonAvx2Runner() this.Output.WriteLine("AVX2 not supported, skipping!"); return true; } + return false; } @@ -46,7 +46,7 @@ public void Indexer() Times, () => { - var block = new Block8x8F(); + var block = default(Block8x8F); for (int i = 0; i < Block8x8F.Size; i++) { @@ -72,7 +72,7 @@ public void Indexer_ReferenceBenchmarkWithArray() () => { // Block8x8F block = new Block8x8F(); - var block = new float[64]; + float[] block = new float[64]; for (int i = 0; i < Block8x8F.Size; i++) { block[i] = i; @@ -90,8 +90,8 @@ public void Indexer_ReferenceBenchmarkWithArray() [Fact] public void Load_Store_FloatArray() { - var data = new float[Block8x8F.Size]; - var mirror = new float[Block8x8F.Size]; + float[] data = new float[Block8x8F.Size]; + float[] mirror = new float[Block8x8F.Size]; for (int i = 0; i < Block8x8F.Size; i++) { @@ -102,7 +102,7 @@ public void Load_Store_FloatArray() Times, () => { - var b = new Block8x8F(); + var b = default(Block8x8F); b.LoadFrom(data); b.CopyTo(mirror); }); @@ -115,8 +115,8 @@ public void Load_Store_FloatArray() [Fact] public unsafe void Load_Store_FloatArray_Ptr() { - var data = new float[Block8x8F.Size]; - var mirror = new float[Block8x8F.Size]; + float[] data = new float[Block8x8F.Size]; + float[] mirror = new float[Block8x8F.Size]; for (int i = 0; i < Block8x8F.Size; i++) { @@ -127,7 +127,7 @@ public unsafe void Load_Store_FloatArray_Ptr() Times, () => { - var b = new Block8x8F(); + var b = default(Block8x8F); Block8x8F.LoadFrom(&b, data); Block8x8F.CopyTo(&b, mirror); }); @@ -140,8 +140,8 @@ public unsafe void Load_Store_FloatArray_Ptr() [Fact] public void Load_Store_IntArray() { - var data = new int[Block8x8F.Size]; - var mirror = new int[Block8x8F.Size]; + int[] data = new int[Block8x8F.Size]; + int[] mirror = new int[Block8x8F.Size]; for (int i = 0; i < Block8x8F.Size; i++) { @@ -152,7 +152,7 @@ public void Load_Store_IntArray() Times, () => { - var v = new Block8x8F(); + var v = default(Block8x8F); v.LoadFrom(data); v.CopyTo(mirror); }); @@ -168,13 +168,13 @@ public void TransposeInto() float[] expected = Create8x8FloatData(); ReferenceImplementations.Transpose8x8(expected); - var source = new Block8x8F(); + var source = default(Block8x8F); source.LoadFrom(Create8x8FloatData()); - var dest = new Block8x8F(); + var dest = default(Block8x8F); source.TransposeInto(ref dest); - var actual = new float[64]; + float[] actual = new float[64]; dest.CopyTo(actual); Assert.Equal(expected, actual); @@ -206,12 +206,12 @@ public void TransposeInto_Benchmark() private static float[] Create8x8ColorCropTestData() { - var result = new float[64]; + float[] result = new float[64]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { - result[i * 8 + j] = -300 + i * 100 + j * 10; + result[(i * 8) + j] = -300 + (i * 100) + (j * 10); } } @@ -230,7 +230,7 @@ public void NormalizeColors() Block8x8F dest = block; dest.NormalizeColorsInplace(255); - var array = new float[64]; + float[] array = new float[64]; dest.CopyTo(array); this.Output.WriteLine("Result:"); this.PrintLinearData(array); @@ -269,10 +269,10 @@ public void NormalizeColorsAndRoundAvx2(int seed) [InlineData(2)] public unsafe void Quantize(int seed) { - var block = new Block8x8F(); + var block = default(Block8x8F); block.LoadFrom(Create8x8RoundedRandomFloatData(-2000, 2000, seed)); - var qt = new Block8x8F(); + var qt = default(Block8x8F); qt.LoadFrom(Create8x8RoundedRandomFloatData(-2000, 2000, seed)); var unzig = ZigZag.CreateUnzigTable(); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8Tests.cs b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8Tests.cs index da75e059f4..af8ba83c35 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8Tests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8Tests.cs @@ -58,10 +58,10 @@ public unsafe void Indexer_GetScalarAt_SetScalarAt() { sum += Block8x8.GetScalarAt(&block, i); } + Assert.Equal(sum, 64 * 63 / 2); } - [Fact] public void AsFloatBlock() { @@ -119,7 +119,7 @@ public void Equality_WhenFalse() public void IndexerXY() { Block8x8 block = default; - block[8 * 3 + 5] = 42; + block[(8 * 3) + 5] = 42; short value = block[5, 3]; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/DCTTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/DCTTests.cs index 91e2f43d35..ad44f0ad8b 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/DCTTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/DCTTests.cs @@ -1,4 +1,6 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using SixLabors.ImageSharp.Formats.Jpeg.Components; @@ -7,6 +9,7 @@ using Xunit; using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public static class DCTTests @@ -19,17 +22,17 @@ public FastFloatingPoint(ITestOutputHelper output) } [Fact] - public void iDCT2D8x4_LeftPart() + public void IDCT2D8x4_LeftPart() { float[] sourceArray = Create8x8FloatData(); var expectedDestArray = new float[64]; - ReferenceImplementations.LLM_FloatingPoint_DCT.iDCT2D8x4_32f(sourceArray, expectedDestArray); + ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D8x4_32f(sourceArray, expectedDestArray); - var source = new Block8x8F(); + var source = default(Block8x8F); source.LoadFrom(sourceArray); - var dest = new Block8x8F(); + var dest = default(Block8x8F); FastFloatingPointDCT.IDCT8x4_LeftPart(ref source, ref dest); @@ -44,17 +47,17 @@ public void iDCT2D8x4_LeftPart() } [Fact] - public void iDCT2D8x4_RightPart() + public void IDCT2D8x4_RightPart() { float[] sourceArray = Create8x8FloatData(); var expectedDestArray = new float[64]; - ReferenceImplementations.LLM_FloatingPoint_DCT.iDCT2D8x4_32f(sourceArray.AsSpan(4), expectedDestArray.AsSpan(4)); + ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D8x4_32f(sourceArray.AsSpan(4), expectedDestArray.AsSpan(4)); - var source = new Block8x8F(); + var source = default(Block8x8F); source.LoadFrom(sourceArray); - var dest = new Block8x8F(); + var dest = default(Block8x8F); FastFloatingPointDCT.IDCT8x4_RightPart(ref source, ref dest); @@ -106,21 +109,20 @@ public void LLM_TransformIDCT_CompareToAccurate(int seed) this.CompareBlocks(expected, actual, 1f); } - [Theory] [InlineData(1)] [InlineData(2)] public void FDCT8x4_LeftPart(int seed) { Span src = Create8x8RoundedRandomFloatData(-200, 200, seed); - var srcBlock = new Block8x8F(); + var srcBlock = default(Block8x8F); srcBlock.LoadFrom(src); - var destBlock = new Block8x8F(); + var destBlock = default(Block8x8F); var expectedDest = new float[64]; - ReferenceImplementations.LLM_FloatingPoint_DCT.fDCT2D8x4_32f(src, expectedDest); + ReferenceImplementations.LLM_FloatingPoint_DCT.FDCT2D8x4_32f(src, expectedDest); FastFloatingPointDCT.FDCT8x4_LeftPart(ref srcBlock, ref destBlock); var actualDest = new float[64]; @@ -135,14 +137,14 @@ public void FDCT8x4_LeftPart(int seed) public void FDCT8x4_RightPart(int seed) { Span src = Create8x8RoundedRandomFloatData(-200, 200, seed); - var srcBlock = new Block8x8F(); + var srcBlock = default(Block8x8F); srcBlock.LoadFrom(src); - var destBlock = new Block8x8F(); + var destBlock = default(Block8x8F); var expectedDest = new float[64]; - ReferenceImplementations.LLM_FloatingPoint_DCT.fDCT2D8x4_32f(src.Slice(4), expectedDest.AsSpan(4)); + ReferenceImplementations.LLM_FloatingPoint_DCT.FDCT2D8x4_32f(src.Slice(4), expectedDest.AsSpan(4)); FastFloatingPointDCT.FDCT8x4_RightPart(ref srcBlock, ref destBlock); var actualDest = new float[64]; @@ -157,16 +159,16 @@ public void FDCT8x4_RightPart(int seed) public void TransformFDCT(int seed) { Span src = Create8x8RoundedRandomFloatData(-200, 200, seed); - var srcBlock = new Block8x8F(); + var srcBlock = default(Block8x8F); srcBlock.LoadFrom(src); - var destBlock = new Block8x8F(); + var destBlock = default(Block8x8F); var expectedDest = new float[64]; var temp1 = new float[64]; - var temp2 = new Block8x8F(); + var temp2 = default(Block8x8F); - ReferenceImplementations.LLM_FloatingPoint_DCT.fDCT2D_llm(src, expectedDest, temp1, downscaleBy8: true); + ReferenceImplementations.LLM_FloatingPoint_DCT.FDCT2D_llm(src, expectedDest, temp1, downscaleBy8: true); FastFloatingPointDCT.TransformFDCT(ref srcBlock, ref destBlock, ref temp2, false); var actualDest = new float[64]; @@ -174,7 +176,6 @@ public void TransformFDCT(int seed) Assert.Equal(actualDest, expectedDest, new ApproximateFloatComparer(1f)); } - } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs index caaad73c9f..146b07d05f 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs @@ -8,8 +8,8 @@ using SixLabors.ImageSharp.ColorSpaces.Conversion; using SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder; using SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder.ColorConverters; -using SixLabors.ImageSharp.Tests.Colorspaces.Conversion; using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.Tests.Colorspaces.Conversion; using Xunit; using Xunit.Abstractions; @@ -105,8 +105,7 @@ public void FromYCbCrSimdAvx2(int inputBufferLength, int resultBufferLength, int return; } - //JpegColorConverter.FromYCbCrSimdAvx2.LogPlz = s => this.Output.WriteLine(s); - + // JpegColorConverter.FromYCbCrSimdAvx2.LogPlz = s => this.Output.WriteLine(s); ValidateRgbToYCbCrConversion( new JpegColorConverter.FromYCbCrSimdAvx2(8), 3, @@ -115,7 +114,6 @@ public void FromYCbCrSimdAvx2(int inputBufferLength, int resultBufferLength, int seed); } - [Theory] [MemberData(nameof(CommonConversionData))] public void ConvertFromYCbCr_WithDefaultConverter(int inputBufferLength, int resultBufferLength, int seed) @@ -129,9 +127,9 @@ public void ConvertFromYCbCr_WithDefaultConverter(int inputBufferLength, int res } // Benchmark, for local execution only - //[Theory] - //[InlineData(false)] - //[InlineData(true)] + // [Theory] + // [InlineData(false)] + // [InlineData(true)] public void BenchmarkYCbCr(bool simd) { int count = 2053; @@ -289,7 +287,7 @@ private static JpegColorConverter.ComponentValues CreateRandomValues( for (int j = 0; j < inputBufferLength; j++) { - values[j] = (float)rnd.NextDouble() * (maxVal - minVal) + minVal; + values[j] = ((float)rnd.NextDouble() * (maxVal - minVal)) + minVal; } // no need to dispose when buffer is not array owner @@ -297,6 +295,7 @@ private static JpegColorConverter.ComponentValues CreateRandomValues( var source = new MemorySource(memory); buffers[i] = new Buffer2D(source, values.Length, 1); } + return new JpegColorConverter.ComponentValues(buffers, 0); } @@ -308,7 +307,7 @@ private static void ValidateConversion( int seed) { ValidateRgbToYCbCrConversion( - JpegColorConverter.GetConverter(colorSpace,8), + JpegColorConverter.GetConverter(colorSpace, 8), componentCount, inputBufferLength, resultBufferLength, @@ -333,4 +332,4 @@ private static void ValidateRgbToYCbCrConversion( } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs index 2485561f1e..adf4629580 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs @@ -1,11 +1,10 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. - using SixLabors.ImageSharp.PixelFormats; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public partial class JpegDecoderTests diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Images.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Images.cs index 37da32d763..b7d7e6b831 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Images.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Images.cs @@ -17,7 +17,6 @@ public partial class JpegDecoderTests // BUG: The following image has a high difference compared to the expected output: 1.0096% // TestImages.Jpeg.Baseline.Jpeg420Small, - TestImages.Jpeg.Issues.Fuzz.AccessViolationException922, TestImages.Jpeg.Baseline.Jpeg444, TestImages.Jpeg.Baseline.Bad.BadEOF, @@ -65,8 +64,8 @@ public partial class JpegDecoderTests TestImages.Jpeg.Issues.OrderedInterleavedProgressive723C }; - public static string[] UnrecoverableTestJpegs = { - + public static string[] UnrecoverableTestJpegs = + { TestImages.Jpeg.Issues.CriticalEOF214, TestImages.Jpeg.Issues.Fuzz.NullReferenceException797, TestImages.Jpeg.Issues.Fuzz.AccessViolationException798, diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs index 4b845c2cbb..c2fc320aff 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs @@ -31,7 +31,6 @@ public partial class JpegDecoderTests { false, TestImages.Jpeg.Baseline.Jpeg400, 8, false, false }, { false, TestImages.Jpeg.Baseline.Snake, 24, true, true }, { false, TestImages.Jpeg.Baseline.Jpeg420Exif, 24, true, false }, - { true, TestImages.Jpeg.Progressive.Progress, 24, false, false }, { true, TestImages.Jpeg.Progressive.Fb, 24, false, true }, { true, TestImages.Jpeg.Baseline.Cmyk, 32, false, true }, @@ -44,8 +43,8 @@ public partial class JpegDecoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Jpeg.Baseline.Ratio1x1, 1, 1 , PixelResolutionUnit.AspectRatio}, - { TestImages.Jpeg.Baseline.Snake, 300, 300 , PixelResolutionUnit.PixelsPerInch}, + { TestImages.Jpeg.Baseline.Ratio1x1, 1, 1, PixelResolutionUnit.AspectRatio }, + { TestImages.Jpeg.Baseline.Snake, 300, 300, PixelResolutionUnit.PixelsPerInch }, { TestImages.Jpeg.Baseline.GammaDalaiLamaGray, 72, 72, PixelResolutionUnit.PixelsPerInch } }; @@ -236,12 +235,15 @@ public void IgnoreMetadata_ControlsWhetherMetadataIsParsed(bool ignoreMetadata) [InlineData(true)] public void Decoder_Reads_Correct_Resolution_From_Jfif(bool useIdentify) { - TestImageInfo(TestImages.Jpeg.Baseline.Floorplan, JpegDecoder, useIdentify, + TestImageInfo( + TestImages.Jpeg.Baseline.Floorplan, + JpegDecoder, + useIdentify, imageInfo => - { - Assert.Equal(300, imageInfo.Metadata.HorizontalResolution); - Assert.Equal(300, imageInfo.Metadata.VerticalResolution); - }); + { + Assert.Equal(300, imageInfo.Metadata.HorizontalResolution); + Assert.Equal(300, imageInfo.Metadata.VerticalResolution); + }); } [Theory] @@ -249,7 +251,10 @@ public void Decoder_Reads_Correct_Resolution_From_Jfif(bool useIdentify) [InlineData(true)] public void Decoder_Reads_Correct_Resolution_From_Exif(bool useIdentify) { - TestImageInfo(TestImages.Jpeg.Baseline.Jpeg420Exif, JpegDecoder, useIdentify, + TestImageInfo( + TestImages.Jpeg.Baseline.Jpeg420Exif, + JpegDecoder, + useIdentify, imageInfo => { Assert.Equal(72, imageInfo.Metadata.HorizontalResolution); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs index 77bc9f5404..d3da6e0392 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs @@ -3,8 +3,8 @@ using SixLabors.ImageSharp.PixelFormats; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public partial class JpegDecoderTests @@ -34,4 +34,4 @@ public void DecodeProgressiveJpeg(TestImageProvider provider) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs index a9cddebc85..2060132296 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs @@ -6,10 +6,10 @@ using System.Linq; using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Tests.Formats.Jpg.Utils; using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; +using SixLabors.Memory; using Xunit; using Xunit.Abstractions; @@ -110,9 +110,10 @@ public void JpegDecoder_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider, + // [Theory] + // [WithFile(TestImages.Jpeg.Progressive.Progress, PixelTypes.Rgba32, "PdfJsOriginal_progress.png")] + public void ValidateProgressivePdfJsOutput( + TestImageProvider provider, string pdfJsOriginalResultImage) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs index ccfde3b465..4146050f03 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs @@ -17,7 +17,7 @@ public class JpegEncoderTests public static readonly TheoryData QualityFiles = new TheoryData { - { TestImages.Jpeg.Baseline.Calliphora, 80}, + { TestImages.Jpeg.Baseline.Calliphora, 80 }, { TestImages.Jpeg.Progressive.Fb, 75 } }; @@ -27,7 +27,6 @@ public class JpegEncoderTests { JpegSubsample.Ratio420, 40 }, { JpegSubsample.Ratio420, 60 }, { JpegSubsample.Ratio420, 100 }, - { JpegSubsample.Ratio444, 40 }, { JpegSubsample.Ratio444, 60 }, { JpegSubsample.Ratio444, 100 }, @@ -36,8 +35,8 @@ public class JpegEncoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Jpeg.Baseline.Ratio1x1, 1, 1 , PixelResolutionUnit.AspectRatio}, - { TestImages.Jpeg.Baseline.Snake, 300, 300 , PixelResolutionUnit.PixelsPerInch}, + { TestImages.Jpeg.Baseline.Ratio1x1, 1, 1, PixelResolutionUnit.AspectRatio }, + { TestImages.Jpeg.Baseline.Snake, 300, 300, PixelResolutionUnit.PixelsPerInch }, { TestImages.Jpeg.Baseline.GammaDalaiLamaGray, 72, 72, PixelResolutionUnit.PixelsPerInch } }; @@ -66,17 +65,17 @@ public void Encode_PreserveQuality(string imagePath, int quality) [Theory] [WithFile(TestImages.Png.CalliphoraPartial, nameof(BitsPerPixel_Quality), PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 73, 71, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 46, 8, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 51, 7, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 73, 71, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 46, 8, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 51, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BitsPerPixel_Quality), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 7, 5, PixelTypes.Rgba32)] public void EncodeBaseline_WorksWithDifferentSizes(TestImageProvider provider, JpegSubsample subsample, int quality) where TPixel : struct, IPixel => TestJpegEncoderCore(provider, subsample, quality); [Theory] - [WithTestPatternImages(nameof(BitsPerPixel_Quality), 48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImage(nameof(BitsPerPixel_Quality), 48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void EncodeBaseline_IsNotBoundToSinglePixelType(TestImageProvider provider, JpegSubsample subsample, int quality) where TPixel : struct, IPixel => TestJpegEncoderCore(provider, subsample, quality); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs index b3219115db..86128e0020 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs @@ -60,7 +60,7 @@ public void DoProcessorStep(TestImageProvider provider) SaveBuffer(cp[2], provider); } } - + [Theory] [WithFileCollection(nameof(BaselineTestJpegs), PixelTypes.Rgba32)] public void PostProcess(TestImageProvider provider) @@ -93,4 +93,4 @@ public void PostProcess(TestImageProvider provider) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/LibJpegToolsTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/LibJpegToolsTests.cs index 3d09f4b383..9ccfed97df 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/LibJpegToolsTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/LibJpegToolsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.IO; using SixLabors.ImageSharp.PixelFormats; @@ -12,7 +15,10 @@ public class LibJpegToolsTests [Fact] public void RunDumpJpegCoeffsTool() { - if (!TestEnvironment.IsWindows) return; + if (!TestEnvironment.IsWindows) + { + return; + } string inputFile = TestFile.GetInputFileFullPath(TestImages.Jpeg.Progressive.Progress); string outputDir = TestEnvironment.CreateOutputDirectory(nameof(SpectralJpegTests)); @@ -49,4 +55,4 @@ public void ExtractSpectralData(TestImageProvider provider) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs index 1d7ca746f6..ccc2930e37 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs @@ -77,6 +77,7 @@ public void PrintComponentData(string imageFile) sb.AppendLine($"Luma: SAMP: {c0.SamplingFactors} BLOCKS: {c0.SizeInBlocks}"); sb.AppendLine($"Chroma: {c1.SamplingFactors} BLOCKS: {c1.SizeInBlocks}"); } + this.Output.WriteLine(sb.ToString()); } @@ -86,6 +87,7 @@ public void PrintComponentData(string imageFile) { TestImages.Jpeg.Baseline.Jpeg420Exif, 3, new Size(2, 2), new Size(1, 1) }, { TestImages.Jpeg.Baseline.Jpeg420Small, 3, new Size(2, 2), new Size(1, 1) }, { TestImages.Jpeg.Baseline.Testorig420, 3, new Size(2, 2), new Size(1, 1) }, + // TODO: Find Ycck or Cmyk images with different subsampling { TestImages.Jpeg.Baseline.Ycck, 4, new Size(1, 1), new Size(1, 1) }, { TestImages.Jpeg.Baseline.Cmyk, 4, new Size(1, 1), new Size(1, 1) }, diff --git a/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.FastFloatingPointDCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.FastFloatingPointDCT.cs index 60a019c290..f8afb3d0be 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.FastFloatingPointDCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.FastFloatingPointDCT.cs @@ -31,8 +31,8 @@ public void LLM_ForwardThenInverse(int seed, int startAt) float[] dest = new float[64]; float[] temp = new float[64]; - ReferenceImplementations.LLM_FloatingPoint_DCT.fDCT2D_llm(src, dest, temp, true); - ReferenceImplementations.LLM_FloatingPoint_DCT.iDCT2D_llm(dest, src, temp); + ReferenceImplementations.LLM_FloatingPoint_DCT.FDCT2D_llm(src, dest, temp, true); + ReferenceImplementations.LLM_FloatingPoint_DCT.IDCT2D_llm(dest, src, temp); this.CompareBlocks(original, src, 0.1f); } @@ -114,7 +114,7 @@ public void GT_IDCT_IsEquivalentTo_AccurateImplementation(int seed, int range) float[] dest = new float[64]; - ReferenceImplementations.GT_FloatingPoint_DCT.iDCT8x8GT(floatSrc, dest); + ReferenceImplementations.GT_FloatingPoint_DCT.IDCT8x8GT(floatSrc, dest); this.CompareBlocks(intData.ConvertAllToFloat(), dest, 1f); } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.StandardIntegerDCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.StandardIntegerDCT.cs index f16d04bf60..ca40403805 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.StandardIntegerDCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/ReferenceImplementationsTests.StandardIntegerDCT.cs @@ -1,4 +1,5 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; @@ -8,6 +9,7 @@ using Xunit; using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public partial class ReferenceImplementationsTests diff --git a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs index d5a1fb7ba0..8d7dda2fed 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs @@ -1,4 +1,6 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.IO; using System.Linq; @@ -10,6 +12,7 @@ using Xunit; using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg { public class SpectralJpegTests @@ -78,7 +81,7 @@ public void VerifySpectralCorrectness(TestImageProvider provider this.VerifySpectralCorrectnessImpl(provider, imageSharpData); } } - + private void VerifySpectralCorrectnessImpl( TestImageProvider provider, LibJpegTools.SpectralData imageSharpData) @@ -112,6 +115,7 @@ private void VerifySpectralCorrectnessImpl( totalDifference += diff.total; tolerance += libJpegComponent.SpectralBlocks.MemorySource.GetSpan().Length; } + averageDifference /= componentCount; tolerance /= 64; // fair enough? @@ -123,4 +127,4 @@ private void VerifySpectralCorrectnessImpl( Assert.True(totalDifference < tolerance); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs index 20830a33f5..b7cf6a8406 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.Diagnostics; using System.IO; @@ -14,11 +12,13 @@ using Xunit; using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { public class JpegFixture : MeasureFixture { - public JpegFixture(ITestOutputHelper output) : base(output) + public JpegFixture(ITestOutputHelper output) + : base(output) { } @@ -30,9 +30,10 @@ public static float[] Create8x8FloatData() { for (int j = 0; j < 8; j++) { - result[i * 8 + j] = i * 10 + j; + result[(i * 8) + j] = (i * 10) + j; } } + return result; } @@ -44,9 +45,10 @@ public static int[] Create8x8IntData() { for (int j = 0; j < 8; j++) { - result[i * 8 + j] = i * 10 + j; + result[(i * 8) + j] = (i * 10) + j; } } + return result; } @@ -58,14 +60,16 @@ public static short[] Create8x8ShortData() { for (int j = 0; j < 8; j++) { - short val = (short)(i * 10 + j); + short val = (short)((i * 10) + j); if ((i + j) % 2 == 0) { val *= -1; } - result[i * 8 + j] = val; + + result[(i * 8) + j] = val; } } + return result; } @@ -78,9 +82,10 @@ public static int[] Create8x8RandomIntData(int minValue, int maxValue, int seed { for (int j = 0; j < 8; j++) { - result[i * 8 + j] = rnd.Next(minValue, maxValue); + result[(i * 8) + j] = rnd.Next(minValue, maxValue); } } + return result; } @@ -99,9 +104,10 @@ public static float[] Create8x8RandomFloatData(float minValue, float maxValue, i val *= maxValue - minValue; val += minValue; - result[i * 8 + j] = (float)val; + result[(i * 8) + j] = (float)val; } } + return result; } @@ -120,8 +126,9 @@ internal void Print8x8Data(Span data) { for (int j = 0; j < 8; j++) { - bld.Append($"{data[i * 8 + j],3} "); + bld.Append($"{data[(i * 8) + j],3} "); } + bld.AppendLine(); } @@ -132,13 +139,17 @@ internal void Print8x8Data(Span data) internal void PrintLinearData(Span data, int count = -1) { - if (count < 0) count = data.Length; + if (count < 0) + { + count = data.Length; + } var sb = new StringBuilder(); for (int i = 0; i < count; i++) { sb.Append($"{data[i],3} "); } + this.Output.WriteLine(sb.ToString()); } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.ComponentData.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.ComponentData.cs index 91cd80d144..dfcc427bad 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.ComponentData.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.ComponentData.cs @@ -62,8 +62,7 @@ public static ComponentData Load(JpegComponent c, int index) var result = new ComponentData( c.WidthInBlocks, c.HeightInBlocks, - index - ); + index); for (int y = 0; y < result.HeightInBlocks; y++) { @@ -89,6 +88,7 @@ public Image CreateGrayScaleImage() this.WriteToImage(bx, by, result); } } + return result; } @@ -106,8 +106,8 @@ internal void WriteToImage(int bx, int by, Image image) Rgba32 color = default; color.FromVector4(v); - int yy = by * 8 + y; - int xx = bx * 8 + x; + int yy = (by * 8) + y; + int xx = (bx * 8) + x; image[xx, yy] = color; } } @@ -115,7 +115,7 @@ internal void WriteToImage(int bx, int by, Image image) internal float GetBlockValue(Block8x8 block, int x, int y) { - float d = (this.MaxVal - this.MinVal); + float d = this.MaxVal - this.MinVal; float val = block[y, x]; val -= this.MinVal; val /= d; @@ -136,9 +136,10 @@ public bool Equals(ComponentData other) bool ok = this.Index == other.Index && this.HeightInBlocks == other.HeightInBlocks && this.WidthInBlocks == other.WidthInBlocks; - //&& this.MinVal == other.MinVal - //&& this.MaxVal == other.MaxVal; - if (!ok) return false; + if (!ok) + { + return false; + } for (int y = 0; y < this.HeightInBlocks; y++) { @@ -146,31 +147,39 @@ public bool Equals(ComponentData other) { Block8x8 a = this.SpectralBlocks[x, y]; Block8x8 b = other.SpectralBlocks[x, y]; - if (!a.Equals(b)) return false; + if (!a.Equals(b)) + { + return false; + } } } + return true; } public override bool Equals(object obj) { - if (obj is null) return false; - if (object.ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; + if (obj is null) + { + return false; + } + + if (object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + return this.Equals((ComponentData)obj); } public override int GetHashCode() { - unchecked - { - int hashCode = this.Index; - hashCode = (hashCode * 397) ^ this.HeightInBlocks; - hashCode = (hashCode * 397) ^ this.WidthInBlocks; - hashCode = (hashCode * 397) ^ this.MinVal.GetHashCode(); - hashCode = (hashCode * 397) ^ this.MaxVal.GetHashCode(); - return hashCode; - } + return HashCode.Combine(this.Index, this.HeightInBlocks, this.WidthInBlocks, this.MinVal, this.MaxVal); } public ref Block8x8 GetBlockReference(int column, int row) @@ -180,12 +189,12 @@ public ref Block8x8 GetBlockReference(int column, int row) public static bool operator ==(ComponentData left, ComponentData right) { - return Object.Equals(left, right); + return object.Equals(left, right); } public static bool operator !=(ComponentData left, ComponentData right) { - return !Object.Equals(left, right); + return !object.Equals(left, right); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.SpectralData.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.SpectralData.cs index ac9e2835c2..0fce671e51 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.SpectralData.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.SpectralData.cs @@ -12,7 +12,6 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { - internal static partial class LibJpegTools { /// @@ -40,7 +39,10 @@ public static SpectralData LoadFromImageSharpDecoder(JpegDecoderCore decoder) public Image TryCreateRGBSpectralImage() { - if (this.ComponentCount != 3) return null; + if (this.ComponentCount != 3) + { + return null; + } LibJpegTools.ComponentData c0 = this.Components[0]; LibJpegTools.ComponentData c1 = this.Components[1]; @@ -60,6 +62,7 @@ public Image TryCreateRGBSpectralImage() this.WriteToImage(bx, by, result); } } + return result; } @@ -73,9 +76,9 @@ internal void WriteToImage(int bx, int by, Image image) Block8x8 block1 = c1.SpectralBlocks[bx, by]; Block8x8 block2 = c2.SpectralBlocks[bx, by]; - float d0 = (c0.MaxVal - c0.MinVal); - float d1 = (c1.MaxVal - c1.MinVal); - float d2 = (c2.MaxVal - c2.MinVal); + float d0 = c0.MaxVal - c0.MinVal; + float d1 = c1.MaxVal - c1.MinVal; + float d2 = c2.MaxVal - c2.MinVal; for (int y = 0; y < 8; y++) { @@ -89,8 +92,8 @@ internal void WriteToImage(int bx, int by, Image image) Rgba32 color = default; color.FromVector4(v); - int yy = by * 8 + y; - int xx = bx * 8 + x; + int yy = (by * 8) + y; + int xx = (bx * 8) + x; image[xx, yy] = color; } } @@ -117,8 +120,12 @@ public bool Equals(SpectralData other) { LibJpegTools.ComponentData a = this.Components[i]; LibJpegTools.ComponentData b = other.Components[i]; - if (!a.Equals(b)) return false; + if (!a.Equals(b)) + { + return false; + } } + return true; } @@ -151,4 +158,4 @@ public override int GetHashCode() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs index 31779df453..826335b652 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs @@ -1,8 +1,11 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; -using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using System.Numerics; +using System.Runtime.InteropServices; using SixLabors.ImageSharp.Formats.Jpeg.Components; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs index 58fa4231e6..23e047bd85 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using SixLabors.ImageSharp.Formats.Jpeg.Components; @@ -18,7 +21,7 @@ internal static partial class ReferenceImplementations /// internal static class AccurateDCT { - private static double[,] CosLut = InitCosLut(); + private static readonly double[,] CosLut = InitCosLut(); public static Block8x8 TransformIDCT(ref Block8x8 block) { @@ -29,7 +32,7 @@ public static Block8x8 TransformIDCT(ref Block8x8 block) public static void TransformIDCTInplace(Span span) { - var temp = new Block8x8(); + var temp = default(Block8x8); temp.LoadFrom(span); Block8x8 result = TransformIDCT(ref temp); result.CopyTo(span); @@ -44,7 +47,7 @@ public static Block8x8 TransformFDCT(ref Block8x8 block) public static void TransformFDCTInplace(Span span) { - var temp = new Block8x8(); + var temp = default(Block8x8); temp.LoadFrom(span); Block8x8 result = TransformFDCT(ref temp); result.CopyTo(span); @@ -56,19 +59,26 @@ public static Block8x8F TransformIDCT(ref Block8x8F block) double tmp, tmp2; Block8x8F res = default; - for (y=0; y<8; y++) { - for (x=0; x<8; x++) { + for (y = 0; y < 8; y++) + { + for (x = 0; x < 8; x++) + { tmp = 0.0; - for (v=0; v<8; v++) { + for (v = 0; v < 8; v++) + { tmp2 = 0.0; - for (u=0; u<8; u++) { - tmp2 += block[v * 8 + u] * CosLut[x, u]; + for (u = 0; u < 8; u++) + { + tmp2 += block[(v * 8) + u] * CosLut[x, u]; } + tmp += CosLut[y, v] * tmp2; } - res[y * 8 + x] = (float)tmp; + + res[(y * 8) + x] = (float)tmp; } } + return res; } @@ -88,11 +98,13 @@ public static Block8x8F TransformFDCT(ref Block8x8F block) tmp2 = 0.0; for (x = 0; x < 8; x++) { - tmp2 += block[y * 8 + x] * CosLut[x,u]; + tmp2 += block[(y * 8) + x] * CosLut[x, u]; } + tmp += CosLut[y, v] * tmp2; } - res[v * 8 + u] = (float) tmp; + + res[(v * 8) + u] = (float)tmp; } } @@ -106,15 +118,19 @@ public static Block8x8F TransformFDCT(ref Block8x8F block) double tmp; for (a = 0; a < 8; a++) - for (b = 0; b < 8; b++) { - tmp = Math.Cos((a + a + 1) * b * (3.14159265358979323846 / 16.0)); - if (b == 0) + for (b = 0; b < 8; b++) { - tmp /= Math.Sqrt(2.0); + tmp = Math.Cos((a + a + 1) * b * (3.14159265358979323846 / 16.0)); + if (b == 0) + { + tmp /= Math.Sqrt(2.0); + } + + coslu[a, b] = tmp * 0.5; } - coslu[a, b] = tmp * 0.5; } + return coslu; } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.GT_FloatingPoint_DCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.GT_FloatingPoint_DCT.cs index 3742e45bdc..1adcf0bc07 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.GT_FloatingPoint_DCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.GT_FloatingPoint_DCT.cs @@ -1,7 +1,9 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { internal static partial class ReferenceImplementations @@ -9,24 +11,24 @@ internal static partial class ReferenceImplementations /// /// Non-optimized method ported from: /// https://github.com/norishigefukushima/dct_simd/blob/master/dct/dct8x8_simd.cpp#L446 - /// + /// /// *** Paper *** /// Plonka, Gerlind, and Manfred Tasche. "Fast and numerically stable algorithms for discrete cosine transforms." Linear algebra and its applications 394 (2005) : 309 - 345. /// internal static class GT_FloatingPoint_DCT { - public static void idct81d_GT(Span src, Span dst) + public static void Idct81d_GT(Span src, Span dst) { for (int i = 0; i < 8; i++) { float mx00 = 1.4142135623731f * src[0]; - float mx01 = 1.38703984532215f * src[1] + 0.275899379282943f * src[7]; - float mx02 = 1.30656296487638f * src[2] + 0.541196100146197f * src[6]; - float mx03 = 1.17587560241936f * src[3] + 0.785694958387102f * src[5]; + float mx01 = (1.38703984532215f * src[1]) + (0.275899379282943f * src[7]); + float mx02 = (1.30656296487638f * src[2]) + (0.541196100146197f * src[6]); + float mx03 = (1.17587560241936f * src[3]) + (0.785694958387102f * src[5]); float mx04 = 1.4142135623731f * src[4]; - float mx05 = -0.785694958387102f * src[3] + 1.17587560241936f * src[5]; - float mx06 = 0.541196100146197f * src[2] - 1.30656296487638f * src[6]; - float mx07 = -0.275899379282943f * src[1] + 1.38703984532215f * src[7]; + float mx05 = (-0.785694958387102f * src[3]) + (1.17587560241936f * src[5]); + float mx06 = (0.541196100146197f * src[2]) - (1.30656296487638f * src[6]); + float mx07 = (-0.275899379282943f * src[1]) + (1.38703984532215f * src[7]); float mx09 = mx00 + mx04; float mx0a = mx01 + mx03; float mx0b = 1.4142135623731f * mx02; @@ -41,29 +43,29 @@ public static void idct81d_GT(Span src, Span dst) float mx14 = 0.353553390593274f * (mx11 + mx12); float mx15 = 0.353553390593274f * (mx11 - mx12); float mx16 = 0.5f * mx13; - dst[0] = 0.25f * (mx09 + mx0b) + 0.353553390593274f * mx0a; + dst[0] = (0.25f * (mx09 + mx0b)) + (0.353553390593274f * mx0a); dst[1] = 0.707106781186547f * (mx0f + mx15); dst[2] = 0.707106781186547f * (mx0f - mx15); dst[3] = 0.707106781186547f * (mx0e + mx16); dst[4] = 0.707106781186547f * (mx0e - mx16); dst[5] = 0.707106781186547f * (mx10 - mx14); dst[6] = 0.707106781186547f * (mx10 + mx14); - dst[7] = 0.25f * (mx09 + mx0b) - 0.353553390593274f * mx0a; + dst[7] = (0.25f * (mx09 + mx0b)) - (0.353553390593274f * mx0a); dst = dst.Slice(8); src = src.Slice(8); } } - public static void iDCT8x8GT(Span s, Span d) + public static void IDCT8x8GT(Span s, Span d) { - idct81d_GT(s, d); + Idct81d_GT(s, d); Transpose8x8(d); - idct81d_GT(d, d); + Idct81d_GT(d, d); Transpose8x8(d); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs index 0c644e5c21..82f0080c06 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs @@ -1,4 +1,6 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Numerics; using System.Runtime.CompilerServices; @@ -7,6 +9,7 @@ using Xunit.Abstractions; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { internal static partial class ReferenceImplementations @@ -29,12 +32,12 @@ internal static class LLM_FloatingPoint_DCT { public static Block8x8F TransformIDCT(ref Block8x8F source) { - var s = new float[64]; + float[] s = new float[64]; source.CopyTo(s); - var d = new float[64]; - var temp = new float[64]; + float[] d = new float[64]; + float[] temp = new float[64]; - iDCT2D_llm(s, d, temp); + IDCT2D_llm(s, d, temp); Block8x8F result = default; result.LoadFrom(d); return result; @@ -42,12 +45,12 @@ public static Block8x8F TransformIDCT(ref Block8x8F source) public static Block8x8F TransformFDCT_UpscaleBy8(ref Block8x8F source) { - var s = new float[64]; + float[] s = new float[64]; source.CopyTo(s); - var d = new float[64]; - var temp = new float[64]; + float[] d = new float[64]; + float[] temp = new float[64]; - fDCT2D_llm(s, d, temp); + FDCT2D_llm(s, d, temp); Block8x8F result = default; result.LoadFrom(d); return result; @@ -61,12 +64,13 @@ public static Block8x8F TransformFDCT_UpscaleBy8(ref Block8x8F source) public static float[] PrintConstants(ITestOutputHelper output) { - var r = new float[8]; + float[] r = new float[8]; for (int i = 0; i < 8; i++) { r[i] = (float)(Cos(i / 16.0 * M_PI) * M_SQRT2); output?.WriteLine($"float r{i} = {r[i]:R}f;"); } + return r; } @@ -75,15 +79,12 @@ public static float[] PrintConstants(ITestOutputHelper output) /// /// https://github.com/norishigefukushima/dct_simd/blob/master/dct/dct8x8_simd.cpp#L200 /// - /// - /// - private static void iDCT1Dllm_32f(Span y, Span x) + private static void IDCT1Dllm_32f(Span y, Span x) { float a0, a1, a2, a3, b0, b1, b2, b3; float z0, z1, z2, z3, z4; // see: PrintConstants() - float r0 = 1.41421354f; float r1 = 1.3870399f; float r2 = 1.306563f; @@ -101,19 +102,19 @@ private static void iDCT1Dllm_32f(Span y, Span x) z0 = z0 * (-r3 + r7); z1 = z1 * (-r3 - r1); - z2 = z2 * (-r3 - r5) + z4; - z3 = z3 * (-r3 + r5) + z4; + z2 = (z2 * (-r3 - r5)) + z4; + z3 = (z3 * (-r3 + r5)) + z4; - b3 = y[7] * (-r1 + r3 + r5 - r7) + z0 + z2; - b2 = y[5] * (r1 + r3 - r5 + r7) + z1 + z3; - b1 = y[3] * (r1 + r3 + r5 - r7) + z1 + z2; - b0 = y[1] * (r1 + r3 - r5 - r7) + z0 + z3; + b3 = (y[7] * (-r1 + r3 + r5 - r7)) + z0 + z2; + b2 = (y[5] * (r1 + r3 - r5 + r7)) + z1 + z3; + b1 = (y[3] * (r1 + r3 + r5 - r7)) + z1 + z2; + b0 = (y[1] * (r1 + r3 - r5 - r7)) + z0 + z3; z4 = (y[2] + y[6]) * r6; z0 = y[0] + y[4]; z1 = y[0] - y[4]; - z2 = z4 - y[6] * (r2 + r6); - z3 = z4 + y[2] * (r2 - r6); + z2 = z4 - (y[6] * (r2 + r6)); + z3 = z4 + (y[2] * (r2 - r6)); a0 = z0 + z3; a3 = z0 - z3; a1 = z1 + z2; @@ -133,23 +134,20 @@ private static void iDCT1Dllm_32f(Span y, Span x) /// Original: https://github.com/norishigefukushima/dct_simd/blob/master/dct/dct8x8_simd.cpp#L239 /// Applies IDCT transformation on "s" copying transformed values to "d", using temporary block "temp" /// - /// - /// - /// - internal static void iDCT2D_llm(Span s, Span d, Span temp) + internal static void IDCT2D_llm(Span s, Span d, Span temp) { int j; for (j = 0; j < 8; j++) { - iDCT1Dllm_32f(s.Slice(j * 8), temp.Slice(j * 8)); + IDCT1Dllm_32f(s.Slice(j * 8), temp.Slice(j * 8)); } Transpose8x8(temp, d); for (j = 0; j < 8; j++) { - iDCT1Dllm_32f(d.Slice(j * 8), temp.Slice(j * 8)); + IDCT1Dllm_32f(d.Slice(j * 8), temp.Slice(j * 8)); } Transpose8x8(temp, d); @@ -168,27 +166,27 @@ internal static void iDCT2D_llm(Span s, Span d, Span temp) /// /// Source /// Destination - public static void fDCT2D8x4_32f(Span s, Span d) + public static void FDCT2D8x4_32f(Span s, Span d) { - Vector4 c0 = _mm_load_ps(s, 0); - Vector4 c1 = _mm_load_ps(s, 56); - Vector4 t0 = (c0 + c1); - Vector4 t7 = (c0 - c1); - - c1 = _mm_load_ps(s, 48); - c0 = _mm_load_ps(s, 8); - Vector4 t1 = (c0 + c1); - Vector4 t6 = (c0 - c1); - - c1 = _mm_load_ps(s, 40); - c0 = _mm_load_ps(s, 16); - Vector4 t2 = (c0 + c1); - Vector4 t5 = (c0 - c1); - - c0 = _mm_load_ps(s, 24); - c1 = _mm_load_ps(s, 32); - Vector4 t3 = (c0 + c1); - Vector4 t4 = (c0 - c1); + Vector4 c0 = Mm_load_ps(s, 0); + Vector4 c1 = Mm_load_ps(s, 56); + Vector4 t0 = c0 + c1; + Vector4 t7 = c0 - c1; + + c1 = Mm_load_ps(s, 48); + c0 = Mm_load_ps(s, 8); + Vector4 t1 = c0 + c1; + Vector4 t6 = c0 - c1; + + c1 = Mm_load_ps(s, 40); + c0 = Mm_load_ps(s, 16); + Vector4 t2 = c0 + c1; + Vector4 t5 = c0 - c1; + + c0 = Mm_load_ps(s, 24); + c1 = Mm_load_ps(s, 32); + Vector4 t3 = c0 + c1; + Vector4 t4 = c0 - c1; /* c1 = x[0]; c2 = x[7]; t0 = c1 + c2; t7 = c1 - c2; @@ -197,19 +195,19 @@ public static void fDCT2D8x4_32f(Span s, Span d) c1 = x[3]; c2 = x[4]; t3 = c1 + c2; t4 = c1 - c2; */ - c0 = (t0 + t3); - Vector4 c3 = (t0 - t3); - c1 = (t1 + t2); - Vector4 c2 = (t1 - t2); + c0 = t0 + t3; + Vector4 c3 = t0 - t3; + c1 = t1 + t2; + Vector4 c2 = t1 - t2; /* c0 = t0 + t3; c3 = t0 - t3; c1 = t1 + t2; c2 = t1 - t2; */ - _mm_store_ps(d, 0, (c0 + c1)); + Mm_store_ps(d, 0, c0 + c1); - _mm_store_ps(d, 32, (c0 - c1)); + Mm_store_ps(d, 32, c0 - c1); /*y[0] = c0 + c1; y[4] = c0 - c1;*/ @@ -217,9 +215,9 @@ public static void fDCT2D8x4_32f(Span s, Span d) var w0 = new Vector4(0.541196f); var w1 = new Vector4(1.306563f); - _mm_store_ps(d, 16, ((w0 * c2) + (w1 * c3))); + Mm_store_ps(d, 16, (w0 * c2) + (w1 * c3)); - _mm_store_ps(d, 48, ((w0 * c3) - (w1 * c2))); + Mm_store_ps(d, 48, (w0 * c3) - (w1 * c2)); /* y[2] = c2 * r[6] + c3 * r[2]; y[6] = c3 * r[6] - c2 * r[2]; @@ -227,8 +225,8 @@ public static void fDCT2D8x4_32f(Span s, Span d) w0 = new Vector4(1.175876f); w1 = new Vector4(0.785695f); - c3 = ((w0 * t4) + (w1 * t7)); - c0 = ((w0 * t7) - (w1 * t4)); + c3 = (w0 * t4) + (w1 * t7); + c0 = (w0 * t7) - (w1 * t4); /* c3 = t4 * r[3] + t7 * r[5]; c0 = t7 * r[3] - t4 * r[5]; @@ -236,78 +234,94 @@ public static void fDCT2D8x4_32f(Span s, Span d) w0 = new Vector4(1.387040f); w1 = new Vector4(0.275899f); - c2 = ((w0 * t5) + (w1 * t6)); - c1 = ((w0 * t6) - (w1 * t5)); + c2 = (w0 * t5) + (w1 * t6); + c1 = (w0 * t6) - (w1 * t5); /* c2 = t5 * r[1] + t6 * r[7]; c1 = t6 * r[1] - t5 * r[7]; */ - _mm_store_ps(d, 24, (c0 - c2)); + Mm_store_ps(d, 24, c0 - c2); - _mm_store_ps(d, 40, (c3 - c1)); - //y[5] = c3 - c1; y[3] = c0 - c2; + Mm_store_ps(d, 40, c3 - c1); + // y[5] = c3 - c1; y[3] = c0 - c2; var invsqrt2 = new Vector4(0.707107f); - c0 = ((c0 + c2) * invsqrt2); - c3 = ((c3 + c1) * invsqrt2); - //c0 = (c0 + c2) * invsqrt2; - //c3 = (c3 + c1) * invsqrt2; + c0 = (c0 + c2) * invsqrt2; + c3 = (c3 + c1) * invsqrt2; + /* c0 = (c0 + c2) * invsqrt2; + c3 = (c3 + c1) * invsqrt2; */ - _mm_store_ps(d, 8, (c0 + c3)); + Mm_store_ps(d, 8, c0 + c3); - _mm_store_ps(d, 56, (c0 - c3)); - //y[1] = c0 + c3; y[7] = c0 - c3; + Mm_store_ps(d, 56, c0 - c3); + /* y[1] = c0 + c3; y[7] = c0 - c3; - /*for(i = 0;i < 8;i++) + for(i = 0;i < 8;i++) { y[i] *= invsqrt2h; }*/ } - public static void fDCT8x8_llm_sse(Span s, Span d, Span temp) + public static void FDCT8x8_llm_sse(Span s, Span d, Span temp) { Transpose8x8(s, temp); - fDCT2D8x4_32f(temp, d); + FDCT2D8x4_32f(temp, d); - fDCT2D8x4_32f(temp.Slice(4), d.Slice(4)); + FDCT2D8x4_32f(temp.Slice(4), d.Slice(4)); Transpose8x8(d, temp); - fDCT2D8x4_32f(temp, d); + FDCT2D8x4_32f(temp, d); - fDCT2D8x4_32f(temp.Slice(4), d.Slice(4)); + FDCT2D8x4_32f(temp.Slice(4), d.Slice(4)); var c = new Vector4(0.1250f); - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//0 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//1 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//2 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//3 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//4 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//5 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//6 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//7 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//8 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//9 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//10 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//11 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//12 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//13 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//14 - _mm_store_ps(d, 0, (_mm_load_ps(d, 0) * c)); d = d.Slice(4);//15 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 0 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 1 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 2 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 3 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 4 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 5 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 6 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 7 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 8 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 9 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 10 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 11 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 12 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 13 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 14 + Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); + d = d.Slice(4); // 15 } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Vector4 _mm_load_ps(Span src, int offset) + private static Vector4 Mm_load_ps(Span src, int offset) { src = src.Slice(offset); return new Vector4(src[0], src[1], src[2], src[3]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void _mm_store_ps(Span dest, int offset, Vector4 src) + private static void Mm_store_ps(Span dest, int offset, Vector4 src) { dest = dest.Slice(offset); dest[0] = src.X; @@ -318,7 +332,7 @@ private static void _mm_store_ps(Span dest, int offset, Vector4 src) // Accurate variants of constants from: // https://github.com/mozilla/mozjpeg/blob/master/simd/jfdctint-altivec.c - +#pragma warning disable SA1309 // Field names should not begin with underscore private static readonly Vector4 _1_175876 = new Vector4(1.175875602f); private static readonly Vector4 _1_961571 = new Vector4(-1.961570560f); @@ -342,20 +356,20 @@ private static void _mm_store_ps(Span dest, int offset, Vector4 src) private static readonly Vector4 _1_847759 = new Vector4(-1.847759065f); private static readonly Vector4 _0_765367 = new Vector4(0.765366865f); +#pragma warning restore SA1309 // Field names should not begin with underscore /// /// Original: /// https://github.com/norishigefukushima/dct_simd/blob/master/dct/dct8x8_simd.cpp#L261 /// Does a part of the IDCT job on the given parts of the blocks /// - /// - /// - internal static void iDCT2D8x4_32f(Span y, Span x) + internal static void IDCT2D8x4_32f(Span y, Span x) { /* float a0,a1,a2,a3,b0,b1,b2,b3; float z0,z1,z2,z3,z4; float r[8]; int i; for(i = 0;i < 8;i++){ r[i] = (float)(cos((double)i / 16.0 * M_PI) * M_SQRT2); } */ + /* 0: 1.414214 1: 1.387040 @@ -367,22 +381,22 @@ internal static void iDCT2D8x4_32f(Span y, Span x) 7: 0.275899 */ - Vector4 my1 = _mm_load_ps(y, 8); - Vector4 my7 = _mm_load_ps(y, 56); + Vector4 my1 = Mm_load_ps(y, 8); + Vector4 my7 = Mm_load_ps(y, 56); Vector4 mz0 = my1 + my7; - Vector4 my3 = _mm_load_ps(y, 24); + Vector4 my3 = Mm_load_ps(y, 24); Vector4 mz2 = my3 + my7; - Vector4 my5 = _mm_load_ps(y, 40); + Vector4 my5 = Mm_load_ps(y, 40); Vector4 mz1 = my3 + my5; Vector4 mz3 = my1 + my5; - Vector4 mz4 = ((mz0 + mz1) * _1_175876); - //z0 = y[1] + y[7]; z1 = y[3] + y[5]; z2 = y[3] + y[7]; z3 = y[1] + y[5]; - //z4 = (z0 + z1) * r[3]; + Vector4 mz4 = (mz0 + mz1) * _1_175876; + /* z0 = y[1] + y[7]; z1 = y[3] + y[5]; z2 = y[3] + y[7]; z3 = y[1] + y[5]; + z4 = (z0 + z1) * r[3];*/ - mz2 = mz2 * _1_961571 + mz4; - mz3 = mz3 * _0_390181 + mz4; + mz2 = (mz2 * _1_961571) + mz4; + mz3 = (mz3 * _0_390181) + mz4; mz0 = mz0 * _0_899976; mz1 = mz1 * _2_562915; @@ -396,10 +410,10 @@ internal static void iDCT2D8x4_32f(Span y, Span x) z2 = z2 * (-r[3] - r[5]) + z4; z3 = z3 * (-r[3] + r[5]) + z4;*/ - Vector4 mb3 = my7 * _0_298631 + mz0 + mz2; - Vector4 mb2 = my5 * _2_053120 + mz1 + mz3; - Vector4 mb1 = my3 * _3_072711 + mz1 + mz2; - Vector4 mb0 = my1 * _1_501321 + mz0 + mz3; + Vector4 mb3 = (my7 * _0_298631) + mz0 + mz2; + Vector4 mb2 = (my5 * _2_053120) + mz1 + mz3; + Vector4 mb1 = (my3 * _3_072711) + mz1 + mz2; + Vector4 mb0 = (my1 * _1_501321) + mz0 + mz3; /* 0.298631 @@ -412,21 +426,22 @@ internal static void iDCT2D8x4_32f(Span y, Span x) b0 = y[1] * ( r[1] + r[3] - r[5] - r[7]) + z0 + z3; */ - Vector4 my2 = _mm_load_ps(y, 16); - Vector4 my6 = _mm_load_ps(y, 48); + Vector4 my2 = Mm_load_ps(y, 16); + Vector4 my6 = Mm_load_ps(y, 48); mz4 = (my2 + my6) * _0_541196; - Vector4 my0 = _mm_load_ps(y, 0); - Vector4 my4 = _mm_load_ps(y, 32); + Vector4 my0 = Mm_load_ps(y, 0); + Vector4 my4 = Mm_load_ps(y, 32); mz0 = my0 + my4; mz1 = my0 - my4; - mz2 = mz4 + my6 * _1_847759; - mz3 = mz4 + my2 * _0_765367; + mz2 = mz4 + (my6 * _1_847759); + mz3 = mz4 + (my2 * _0_765367); my0 = mz0 + mz3; my3 = mz0 - mz3; my1 = mz1 + mz2; my2 = mz1 - mz2; + /* 1.847759 0.765367 @@ -438,21 +453,22 @@ internal static void iDCT2D8x4_32f(Span y, Span x) a1 = z1 + z2; a2 = z1 - z2; */ - _mm_store_ps(x, 0, my0 + mb0); + Mm_store_ps(x, 0, my0 + mb0); + + Mm_store_ps(x, 56, my0 - mb0); - _mm_store_ps(x, 56, my0 - mb0); + Mm_store_ps(x, 8, my1 + mb1); - _mm_store_ps(x, 8, my1 + mb1); + Mm_store_ps(x, 48, my1 - mb1); - _mm_store_ps(x, 48, my1 - mb1); + Mm_store_ps(x, 16, my2 + mb2); - _mm_store_ps(x, 16, my2 + mb2); + Mm_store_ps(x, 40, my2 - mb2); - _mm_store_ps(x, 40, my2 - mb2); + Mm_store_ps(x, 24, my3 + mb3); - _mm_store_ps(x, 24, my3 + mb3); + Mm_store_ps(x, 32, my3 - mb3); - _mm_store_ps(x, 32, my3 - mb3); /* x[0] = a0 + b0; x[7] = a0 - b0; x[1] = a1 + b1; x[6] = a1 - b1; @@ -462,13 +478,13 @@ internal static void iDCT2D8x4_32f(Span y, Span x) */ } - internal static void fDCT1Dllm_32f(Span x, Span y) + internal static void FDCT1Dllm_32f(Span x, Span y) { float t0, t1, t2, t3, t4, t5, t6, t7; float c0, c1, c2, c3; - var r = new float[8]; + float[] r = new float[8]; - //for(i = 0;i < 8;i++){ r[i] = (float)(cos((double)i / 16.0 * M_PI) * M_SQRT2); } + // for(i = 0;i < 8;i++){ r[i] = (float)(cos((double)i / 16.0 * M_PI) * M_SQRT2); } r[0] = 1.414214f; r[1] = 1.387040f; r[2] = 1.306563f; @@ -478,9 +494,9 @@ internal static void fDCT1Dllm_32f(Span x, Span y) r[6] = 0.541196f; r[7] = 0.275899f; - const float invsqrt2 = 0.707107f; //(float)(1.0f / M_SQRT2); - //const float invsqrt2h = 0.353554f; //invsqrt2*0.5f; + const float invsqrt2 = 0.707107f; // (float)(1.0f / M_SQRT2); + // const float invsqrt2h = 0.353554f; // invsqrt2*0.5f; c1 = x[0]; c2 = x[7]; t0 = c1 + c2; @@ -505,13 +521,13 @@ internal static void fDCT1Dllm_32f(Span x, Span y) y[0] = c0 + c1; y[4] = c0 - c1; - y[2] = c2 * r[6] + c3 * r[2]; - y[6] = c3 * r[6] - c2 * r[2]; + y[2] = (c2 * r[6]) + (c3 * r[2]); + y[6] = (c3 * r[6]) - (c2 * r[2]); - c3 = t4 * r[3] + t7 * r[5]; - c0 = t7 * r[3] - t4 * r[5]; - c2 = t5 * r[1] + t6 * r[7]; - c1 = t6 * r[1] - t5 * r[7]; + c3 = (t4 * r[3]) + (t7 * r[5]); + c0 = (t7 * r[3]) - (t4 * r[5]); + c2 = (t5 * r[1]) + (t6 * r[7]); + c1 = (t6 * r[1]) - (t5 * r[7]); y[5] = c3 - c1; y[3] = c0 - c2; @@ -521,7 +537,7 @@ internal static void fDCT1Dllm_32f(Span x, Span y) y[7] = c0 - c3; } - internal static void fDCT2D_llm( + internal static void FDCT2D_llm( Span s, Span d, Span temp, @@ -532,14 +548,14 @@ internal static void fDCT2D_llm( for (int j = 0; j < 8; j++) { - fDCT1Dllm_32f(sWorker.Slice(j * 8), temp.Slice(j * 8)); + FDCT1Dllm_32f(sWorker.Slice(j * 8), temp.Slice(j * 8)); } Transpose8x8(temp, d); for (int j = 0; j < 8; j++) { - fDCT1Dllm_32f(d.Slice(j * 8), temp.Slice(j * 8)); + FDCT1Dllm_32f(d.Slice(j * 8), temp.Slice(j * 8)); } Transpose8x8(temp, d); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.StandardIntegerDCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.StandardIntegerDCT.cs index a929e0eb02..c11edb67c7 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.StandardIntegerDCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.StandardIntegerDCT.cs @@ -1,8 +1,11 @@ -// ReSharper disable InconsistentNaming +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using SixLabors.ImageSharp.Formats.Jpeg.Components; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { internal static partial class ReferenceImplementations @@ -40,18 +43,18 @@ internal static partial class ReferenceImplementations /// public static class StandardIntegerDCT { - private const int fix_0_298631336 = 2446; - private const int fix_0_390180644 = 3196; - private const int fix_0_541196100 = 4433; - private const int fix_0_765366865 = 6270; - private const int fix_0_899976223 = 7373; - private const int fix_1_175875602 = 9633; - private const int fix_1_501321110 = 12299; - private const int fix_1_847759065 = 15137; - private const int fix_1_961570560 = 16069; - private const int fix_2_053119869 = 16819; - private const int fix_2_562915447 = 20995; - private const int fix_3_072711026 = 25172; + private const int Fix_0_298631336 = 2446; + private const int Fix_0_390180644 = 3196; + private const int Fix_0_541196100 = 4433; + private const int Fix_0_765366865 = 6270; + private const int Fix_0_899976223 = 7373; + private const int Fix_1_175875602 = 9633; + private const int Fix_1_501321110 = 12299; + private const int Fix_1_847759065 = 15137; + private const int Fix_1_961570560 = 16069; + private const int Fix_2_053119869 = 16819; + private const int Fix_2_562915447 = 20995; + private const int Fix_3_072711026 = 25172; /// /// The number of bits @@ -127,25 +130,25 @@ public static void Subtract128_TransformFDCT_Upscale8_Inplace(Span block) block[y8] = (tmp10 + tmp11 - (8 * CenterJSample)) << Pass1Bits; block[y8 + 4] = (tmp10 - tmp11) << Pass1Bits; - int z1 = (tmp12 + tmp13) * fix_0_541196100; + int z1 = (tmp12 + tmp13) * Fix_0_541196100; z1 += 1 << (Bits - Pass1Bits - 1); - block[y8 + 2] = (z1 + (tmp12 * fix_0_765366865)) >> (Bits - Pass1Bits); - block[y8 + 6] = (z1 - (tmp13 * fix_1_847759065)) >> (Bits - Pass1Bits); + block[y8 + 2] = (z1 + (tmp12 * Fix_0_765366865)) >> (Bits - Pass1Bits); + block[y8 + 6] = (z1 - (tmp13 * Fix_1_847759065)) >> (Bits - Pass1Bits); tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; - z1 = (tmp12 + tmp13) * fix_1_175875602; + z1 = (tmp12 + tmp13) * Fix_1_175875602; z1 += 1 << (Bits - Pass1Bits - 1); - tmp0 = tmp0 * fix_1_501321110; - tmp1 = tmp1 * fix_3_072711026; - tmp2 = tmp2 * fix_2_053119869; - tmp3 = tmp3 * fix_0_298631336; - tmp10 = tmp10 * -fix_0_899976223; - tmp11 = tmp11 * -fix_2_562915447; - tmp12 = tmp12 * -fix_0_390180644; - tmp13 = tmp13 * -fix_1_961570560; + tmp0 = tmp0 * Fix_1_501321110; + tmp1 = tmp1 * Fix_3_072711026; + tmp2 = tmp2 * Fix_2_053119869; + tmp3 = tmp3 * Fix_0_298631336; + tmp10 = tmp10 * -Fix_0_899976223; + tmp11 = tmp11 * -Fix_2_562915447; + tmp12 = tmp12 * -Fix_0_390180644; + tmp13 = tmp13 * -Fix_1_961570560; tmp12 += z1; tmp13 += z1; @@ -177,25 +180,25 @@ public static void Subtract128_TransformFDCT_Upscale8_Inplace(Span block) block[x] = (tmp10 + tmp11) >> Pass1Bits; block[32 + x] = (tmp10 - tmp11) >> Pass1Bits; - int z1 = (tmp12 + tmp13) * fix_0_541196100; + int z1 = (tmp12 + tmp13) * Fix_0_541196100; z1 += 1 << (Bits + Pass1Bits - 1); - block[16 + x] = (z1 + (tmp12 * fix_0_765366865)) >> (Bits + Pass1Bits); - block[48 + x] = (z1 - (tmp13 * fix_1_847759065)) >> (Bits + Pass1Bits); + block[16 + x] = (z1 + (tmp12 * Fix_0_765366865)) >> (Bits + Pass1Bits); + block[48 + x] = (z1 - (tmp13 * Fix_1_847759065)) >> (Bits + Pass1Bits); tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; - z1 = (tmp12 + tmp13) * fix_1_175875602; + z1 = (tmp12 + tmp13) * Fix_1_175875602; z1 += 1 << (Bits + Pass1Bits - 1); - tmp0 = tmp0 * fix_1_501321110; - tmp1 = tmp1 * fix_3_072711026; - tmp2 = tmp2 * fix_2_053119869; - tmp3 = tmp3 * fix_0_298631336; - tmp10 = tmp10 * -fix_0_899976223; - tmp11 = tmp11 * -fix_2_562915447; - tmp12 = tmp12 * -fix_0_390180644; - tmp13 = tmp13 * -fix_1_961570560; + tmp0 = tmp0 * Fix_1_501321110; + tmp1 = tmp1 * Fix_3_072711026; + tmp2 = tmp2 * Fix_2_053119869; + tmp3 = tmp3 * Fix_0_298631336; + tmp10 = tmp10 * -Fix_0_899976223; + tmp11 = tmp11 * -Fix_2_562915447; + tmp12 = tmp12 * -Fix_0_390180644; + tmp13 = tmp13 * -Fix_1_961570560; tmp12 += z1; tmp13 += z1; @@ -204,23 +207,23 @@ public static void Subtract128_TransformFDCT_Upscale8_Inplace(Span block) block[40 + x] = (tmp2 + tmp11 + tmp12) >> (Bits + Pass1Bits); block[56 + x] = (tmp3 + tmp10 + tmp13) >> (Bits + Pass1Bits); } - } - private const int w1 = 2841; // 2048*sqrt(2)*cos(1*pi/16) - private const int w2 = 2676; // 2048*sqrt(2)*cos(2*pi/16) - private const int w3 = 2408; // 2048*sqrt(2)*cos(3*pi/16) - private const int w5 = 1609; // 2048*sqrt(2)*cos(5*pi/16) - private const int w6 = 1108; // 2048*sqrt(2)*cos(6*pi/16) - private const int w7 = 565; // 2048*sqrt(2)*cos(7*pi/16) - - private const int w1pw7 = w1 + w7; - private const int w1mw7 = w1 - w7; - private const int w2pw6 = w2 + w6; - private const int w2mw6 = w2 - w6; - private const int w3pw5 = w3 + w5; - private const int w3mw5 = w3 - w5; - - private const int r2 = 181; // 256/sqrt(2) + + private const int W1 = 2841; // 2048*sqrt(2)*cos(1*pi/16) + private const int W2 = 2676; // 2048*sqrt(2)*cos(2*pi/16) + private const int W3 = 2408; // 2048*sqrt(2)*cos(3*pi/16) + private const int W5 = 1609; // 2048*sqrt(2)*cos(5*pi/16) + private const int W6 = 1108; // 2048*sqrt(2)*cos(6*pi/16) + private const int W7 = 565; // 2048*sqrt(2)*cos(7*pi/16) + + private const int W1pw7 = W1 + W7; + private const int W1mw7 = W1 - W7; + private const int W2pw6 = W2 + W6; + private const int W2mw6 = W2 - W6; + private const int W3pw5 = W3 + W5; + private const int W3mw5 = W3 - W5; + + private const int R2 = 181; // 256/sqrt(2) /// /// Performs a 2-D Inverse Discrete Cosine Transformation. @@ -235,7 +238,6 @@ public static void Subtract128_TransformFDCT_Upscale8_Inplace(Span block) /// ASSP, Vol. ASSP- 32, pp. 803-816, Aug. 1984. /// /// The source block of coefficients - // [Obsolete("Looks like this method produces really bad results for bigger values!")] public static void TransformIDCTInplace(Span src) { // Horizontal 1-D IDCT. @@ -270,19 +272,19 @@ public static void TransformIDCTInplace(Span src) int x7 = src[y8 + 3]; // Stage 1. - int x8 = w7 * (x4 + x5); - x4 = x8 + (w1mw7 * x4); - x5 = x8 - (w1pw7 * x5); - x8 = w3 * (x6 + x7); - x6 = x8 - (w3mw5 * x6); - x7 = x8 - (w3pw5 * x7); + int x8 = W7 * (x4 + x5); + x4 = x8 + (W1mw7 * x4); + x5 = x8 - (W1pw7 * x5); + x8 = W3 * (x6 + x7); + x6 = x8 - (W3mw5 * x6); + x7 = x8 - (W3pw5 * x7); // Stage 2. x8 = x0 + x1; x0 -= x1; - x1 = w6 * (x3 + x2); - x2 = x1 - (w2pw6 * x2); - x3 = x1 + (w2mw6 * x3); + x1 = W6 * (x3 + x2); + x2 = x1 - (W2pw6 * x2); + x3 = x1 + (W2mw6 * x3); x1 = x4 + x6; x4 -= x6; x6 = x5 + x7; @@ -293,8 +295,8 @@ public static void TransformIDCTInplace(Span src) x8 -= x3; x3 = x0 + x2; x0 -= x2; - x2 = ((r2 * (x4 + x5)) + 128) >> 8; - x4 = ((r2 * (x4 - x5)) + 128) >> 8; + x2 = ((R2 * (x4 + x5)) + 128) >> 8; + x4 = ((R2 * (x4 - x5)) + 128) >> 8; // Stage 4. src[y8 + 0] = (x7 + x1) >> 8; @@ -325,19 +327,19 @@ public static void TransformIDCTInplace(Span src) int y7 = src[24 + x]; // Stage 1. - int y8 = (w7 * (y4 + y5)) + 4; - y4 = (y8 + (w1mw7 * y4)) >> 3; - y5 = (y8 - (w1pw7 * y5)) >> 3; - y8 = (w3 * (y6 + y7)) + 4; - y6 = (y8 - (w3mw5 * y6)) >> 3; - y7 = (y8 - (w3pw5 * y7)) >> 3; + int y8 = (W7 * (y4 + y5)) + 4; + y4 = (y8 + (W1mw7 * y4)) >> 3; + y5 = (y8 - (W1pw7 * y5)) >> 3; + y8 = (W3 * (y6 + y7)) + 4; + y6 = (y8 - (W3mw5 * y6)) >> 3; + y7 = (y8 - (W3pw5 * y7)) >> 3; // Stage 2. y8 = y0 + y1; y0 -= y1; - y1 = (w6 * (y3 + y2)) + 4; - y2 = (y1 - (w2pw6 * y2)) >> 3; - y3 = (y1 + (w2mw6 * y3)) >> 3; + y1 = (W6 * (y3 + y2)) + 4; + y2 = (y1 - (W2pw6 * y2)) >> 3; + y3 = (y1 + (W2mw6 * y3)) >> 3; y1 = y4 + y6; y4 -= y6; y6 = y5 + y7; @@ -348,8 +350,8 @@ public static void TransformIDCTInplace(Span src) y8 -= y3; y3 = y0 + y2; y0 -= y2; - y2 = ((r2 * (y4 + y5)) + 128) >> 8; - y4 = ((r2 * (y4 - y5)) + 128) >> 8; + y2 = ((R2 * (y4 + y5)) + 128) >> 8; + y4 = ((R2 * (y4 - y5)) + 128) >> 8; // Stage 4. src[x] = (y7 + y1) >> 14; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.cs index 527cc3feda..4de576b256 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.cs @@ -1,13 +1,12 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Formats.Jpeg.Components; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Jpg.Utils { /// @@ -34,7 +33,6 @@ public static unsafe void DequantizeBlock(Block8x8F* blockPtr, Block8x8F* qtPtr, /// /// Transpose 8x8 block stored linearly in a (inplace) /// - /// internal static void Transpose8x8(Span data) { for (int i = 1; i < 8; i++) @@ -43,8 +41,8 @@ internal static void Transpose8x8(Span data) for (int j = 0; j < i; j++) { float tmp = data[i8 + j]; - data[i8 + j] = data[j * 8 + i]; - data[j * 8 + i] = tmp; + data[i8 + j] = data[(j * 8) + i]; + data[(j * 8) + i] = tmp; } } } @@ -59,7 +57,7 @@ internal static void Transpose8x8(Span src, Span dest) int i8 = i * 8; for (int j = 0; j < 8; j++) { - dest[j * 8 + i] = src[i8 + j]; + dest[(j * 8) + i] = src[i8 + j]; } } } @@ -67,9 +65,6 @@ internal static void Transpose8x8(Span src, Span dest) /// /// Copies color values from block to the destination image buffer. /// - /// - /// - /// internal static unsafe void CopyColorsTo(ref Block8x8F block, Span buffer, int stride) { fixed (Block8x8F* p = &block) @@ -128,11 +123,11 @@ public static unsafe void QuantizeRational(Block8x8F* src, int* dest, Block8x8F* } /// - /// Rounds a rational number defined as dividend/divisor into an integer + /// Rounds a rational number defined as dividend/divisor into an integer. /// - /// The dividend - /// The divisor - /// + /// The dividend. + /// The divisor. + /// The rounded value. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int RationalRound(int dividend, int divisor) { diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs index 296f424fa5..973181ed57 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Collections.Generic; using System.Linq; @@ -72,4 +75,4 @@ internal static void SaveSpectralImage( } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs index 64a394cc98..2e8c0de272 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngChunkTypeTests.cs @@ -1,4 +1,7 @@ -using System.Buffers.Binary; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Buffers.Binary; using System.Text; using SixLabors.ImageSharp.Formats.Png; using Xunit; @@ -26,4 +29,4 @@ private static PngChunkType GetType(string text) return (PngChunkType)BinaryPrimitives.ReadInt32BigEndian(Encoding.ASCII.GetBytes(text)); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs index 660d5b7246..ee4001c203 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System.Buffers.Binary; using System.IO; using System.Text; @@ -6,8 +9,8 @@ using SixLabors.ImageSharp.PixelFormats; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Png { public partial class PngDecoderTests @@ -15,19 +18,21 @@ public partial class PngDecoderTests // Contains the png marker, IHDR and pHYs chunks of a 1x1 pixel 32bit png 1 a single black pixel. private static readonly byte[] Raw1X1PngIhdrAndpHYs = { - // PNG Identifier + // PNG Identifier 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // IHDR 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, + // IHDR CRC 0x90, 0x77, 0x53, 0xDE, // pHYS 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0E, 0xC3, 0x00, 0x00, 0x0E, 0xC3, 0x01, + // pHYS CRC 0xC7, 0x6F, 0xA8, 0x64 }; @@ -53,7 +58,7 @@ public partial class PngDecoderTests [Theory] [InlineData((uint)PngChunkType.Header)] // IHDR [InlineData((uint)PngChunkType.Palette)] // PLTE - // [InlineData(PngChunkTypes.Data)] //TODO: Figure out how to test this + /* [InlineData(PngChunkTypes.Data)] TODO: Figure out how to test this */ public void Decode_IncorrectCRCForCriticalChunk_ExceptionIsThrown(uint chunkType) { string chunkName = GetChunkTypeName(chunkType); @@ -84,7 +89,7 @@ private static string GetChunkTypeName(uint value) private static void WriteHeaderChunk(MemoryStream memStream) { - // Writes a 1x1 32bit png header chunk containing a single black pixel + // Writes a 1x1 32bit png header chunk containing a single black pixel. memStream.Write(Raw1X1PngIhdrAndpHYs, 0, Raw1X1PngIhdrAndpHYs.Length); } @@ -99,7 +104,7 @@ private static void WriteChunk(MemoryStream memStream, string chunkName) private static void WriteDataChunk(MemoryStream memStream) { - // Writes a 1x1 32bit png data chunk containing a single black pixel + // Writes a 1x1 32bit png data chunk containing a single black pixel. memStream.Write(Raw1X1PngIdatAndIend, 0, Raw1X1PngIdatAndIend.Length); memStream.Position = 0; } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs index 3b05b00ce0..a88962e5f8 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System.IO; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Png; @@ -11,6 +9,7 @@ using SixLabors.ImageSharp.Tests.TestUtilities.ReferenceCodecs; using Xunit; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Png { public partial class PngDecoderTests @@ -52,7 +51,7 @@ public partial class PngDecoderTests }; public static readonly string[] TestImages64Bpp = -{ + { TestImages.Png.Rgba64Bpp, TestImages.Png.Rgb48BppTrans }; diff --git a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs index 6aaa0c80ce..03fdf70bc6 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs @@ -85,18 +85,18 @@ public class PngEncoderTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Png.Splash, 11810, 11810 , PixelResolutionUnit.PixelsPerMeter}, - { TestImages.Png.Ratio1x4, 1, 4 , PixelResolutionUnit.AspectRatio}, + { TestImages.Png.Splash, 11810, 11810, PixelResolutionUnit.PixelsPerMeter }, + { TestImages.Png.Ratio1x4, 1, 4, PixelResolutionUnit.AspectRatio }, { TestImages.Png.Ratio4x1, 4, 1, PixelResolutionUnit.AspectRatio } }; [Theory] [WithFile(TestImages.Png.Palette8Bpp, nameof(PngColorTypes), PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(PngColorTypes), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(PngColorTypes), 47, 8, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(PngColorTypes), 49, 7, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PngColorTypes), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PngColorTypes), 47, 8, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PngColorTypes), 49, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(PngColorTypes), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(PngColorTypes), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PngColorTypes), 7, 5, PixelTypes.Rgba32)] public void WorksWithDifferentSizes(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { @@ -110,7 +110,7 @@ public void WorksWithDifferentSizes(TestImageProvider provider, } [Theory] - [WithTestPatternImages(nameof(PngColorTypes), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] + [WithTestPatternImage(nameof(PngColorTypes), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] public void IsNotBoundToSinglePixelType(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { @@ -128,7 +128,7 @@ public void IsNotBoundToSinglePixelType(TestImageProvider provid } [Theory] - [WithTestPatternImages(nameof(PngFilterMethods), 24, 24, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PngFilterMethods), 24, 24, PixelTypes.Rgba32)] public void WorksWithAllFilterMethods(TestImageProvider provider, PngFilterMethod pngFilterMethod) where TPixel : struct, IPixel { @@ -145,7 +145,7 @@ public void WorksWithAllFilterMethods(TestImageProvider provider } [Theory] - [WithTestPatternImages(nameof(CompressionLevels), 24, 24, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(CompressionLevels), 24, 24, PixelTypes.Rgba32)] public void WorksWithAllCompressionLevels(TestImageProvider provider, int compressionLevel) where TPixel : struct, IPixel { @@ -163,21 +163,21 @@ public void WorksWithAllCompressionLevels(TestImageProvider prov } [Theory] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Rgb, PngBitDepth.Bit8)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.Rgb, PngBitDepth.Bit16)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.RgbWithAlpha, PngBitDepth.Bit8)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.RgbWithAlpha, PngBitDepth.Bit16)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit1)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit2)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit4)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit8)] - [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit1)] - [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit2)] - [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit4)] - [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit8)] - [WithTestPatternImages(24, 24, PixelTypes.Rgb48, PngColorType.Grayscale, PngBitDepth.Bit16)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit8)] - [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit16)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Rgb, PngBitDepth.Bit8)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.Rgb, PngBitDepth.Bit16)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.RgbWithAlpha, PngBitDepth.Bit8)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.RgbWithAlpha, PngBitDepth.Bit16)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit1)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit2)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit4)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit8)] + [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit1)] + [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit2)] + [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit4)] + [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit8)] + [WithTestPatternImage(24, 24, PixelTypes.Rgb48, PngColorType.Grayscale, PngBitDepth.Bit16)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit8)] + [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit16)] public void WorksWithAllBitDepths(TestImageProvider provider, PngColorType pngColorType, PngBitDepth pngBitDepth) where TPixel : struct, IPixel { @@ -236,7 +236,8 @@ public void WritesFileMarker(TestImageProvider provider) image.Save(ms, new PngEncoder()); byte[] data = ms.ToArray().Take(8).ToArray(); - byte[] expected = { + byte[] expected = + { 0x89, // Set the high bit. 0x50, // P 0x4E, // N @@ -396,6 +397,7 @@ private static void TestPngEncoderCore( // Compare to the Magick reference decoder. IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + // We compare using both our decoder and the reference decoder as pixel transformation // occurs within the encoder itself leaving the input image unaffected. // This means we are benefiting from testing our decoder also. diff --git a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs index 4b11ad3e27..fe25497247 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs @@ -16,8 +16,8 @@ public class PngMetadataTests public static readonly TheoryData RatioFiles = new TheoryData { - { TestImages.Png.Splash, 11810, 11810 , PixelResolutionUnit.PixelsPerMeter}, - { TestImages.Png.Ratio1x4, 1, 4 , PixelResolutionUnit.AspectRatio}, + { TestImages.Png.Splash, 11810, 11810, PixelResolutionUnit.PixelsPerMeter }, + { TestImages.Png.Ratio1x4, 1, 4, PixelResolutionUnit.AspectRatio }, { TestImages.Png.Ratio4x1, 4, 1, PixelResolutionUnit.AspectRatio } }; @@ -126,9 +126,10 @@ public void Encode_UseCompression_WhenTextIsGreaterThenThreshold_Works(T using (Image input = provider.GetImage(decoder)) 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); - // this will be a iTXt chunk. + + // This will be a iTXt chunk. var expectedTextNoneLatin = new PngTextData("large-text-non-latin", new string('Ф', 100), "language-tag", "translated-keyword"); PngMetadata inputMetadata = input.Metadata.GetFormatMetadata(PngFormat.Instance); inputMetadata.TextData.Add(expectedText); diff --git a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs index 1f8147ea95..1fe69eee1e 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs @@ -2,118 +2,117 @@ // Licensed under the Apache License, Version 2.0. using System.IO; -using Xunit; - +using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; -using SixLabors.ImageSharp.Formats.Png; +using Xunit; namespace SixLabors.ImageSharp.Tests.Formats.Png { public class PngSmokeTests { [Theory] - [WithTestPatternImages(300, 300, PixelTypes.Rgba32)] + [WithTestPatternImage(300, 300, PixelTypes.Rgba32)] public void GeneralTest(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? using (Image image = provider.GetImage()) - using (MemoryStream ms = new MemoryStream()) + using (var ms = new MemoryStream()) { // image.Save(provider.Utility.GetTestOutputFileName("bmp")); - image.Save(ms, new PngEncoder()); ms.Position = 0; - using (Image img2 = Image.Load(ms, new PngDecoder())) + using (var img2 = Image.Load(ms, new PngDecoder())) { ImageComparer.Tolerant().VerifySimilarity(image, img2); + // 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 - // paletted image has alpha of 0 - //[Theory] - //[WithTestPatternImages(100, 100, PixelTypes.Rgba32)] - //public void CanSaveIndexedPng(TestImageProvider provider) - // where TPixel : struct, IPixel - //{ - // // does saving a file then reopening mean both files are identical??? - // using (Image image = provider.GetImage()) - // using (MemoryStream ms = new MemoryStream()) - // { - // // image.Save(provider.Utility.GetTestOutputFileName("bmp")); - // image.Save(ms, new PngEncoder() { PaletteSize = 256 }); - // ms.Position = 0; - // using (Image img2 = Image.Load(ms, new PngDecoder())) - // { - // ImageComparer.VerifySimilarity(image, img2, 0.03f); - // } - // } - //} + /* JJS: Disabled for now as the decoder now correctly decodes the full pixel components if the + paletted image has alpha of 0 + [Theory] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] + public void CanSaveIndexedPng(TestImageProvider provider) + where TPixel : struct, IPixel + { + // does saving a file then reopening mean both files are identical??? + using (Image image = provider.GetImage()) + using (MemoryStream ms = new MemoryStream()) + { + // image.Save(provider.Utility.GetTestOutputFileName("bmp")); + image.Save(ms, new PngEncoder() { PaletteSize = 256 }); + ms.Position = 0; + using (Image img2 = Image.Load(ms, new PngDecoder())) + { + ImageComparer.VerifySimilarity(image, img2, 0.03f); + } + } + }*/ - // JJS: Commented out for now since the test does not take into lossy nature of indexing. - //[Theory] - //[WithTestPatternImages(100, 100, PixelTypes.Color)] - //public void CanSaveIndexedPngTwice(TestImageProvider provider) - // where TPixel : struct, IPixel - //{ - // // does saving a file then reopening mean both files are identical??? - // using (Image source = provider.GetImage()) - // using (MemoryStream ms = new MemoryStream()) - // { - // source.Metadata.Quality = 256; - // source.Save(ms, new PngEncoder(), new PngEncoderOptions { - // Threshold = 200 - // }); - // ms.Position = 0; - // using (Image img1 = Image.Load(ms, new PngDecoder())) - // { - // using (MemoryStream ms2 = new MemoryStream()) - // { - // img1.Save(ms2, new PngEncoder(), new PngEncoderOptions - // { - // Threshold = 200 - // }); - // ms2.Position = 0; - // using (Image img2 = Image.Load(ms2, new PngDecoder())) - // { - // using (PixelAccessor pixels1 = img1.Lock()) - // using (PixelAccessor pixels2 = img2.Lock()) - // { - // for (int y = 0; y < img1.Height; y++) - // { - // for (int x = 0; x < img1.Width; x++) - // { - // Assert.Equal(pixels1[x, y], pixels2[x, y]); - // } - // } - // } - // } - // } - // } - // } - //} + /* JJS: Commented out for now since the test does not take into lossy nature of indexing. + [Theory] + [WithTestPatternImages(100, 100, PixelTypes.Color)] + public void CanSaveIndexedPngTwice(TestImageProvider provider) + where TPixel : struct, IPixel + { + // does saving a file then reopening mean both files are identical??? + using (Image source = provider.GetImage()) + using (MemoryStream ms = new MemoryStream()) + { + source.Metadata.Quality = 256; + source.Save(ms, new PngEncoder(), new PngEncoderOptions { + Threshold = 200 + }); + ms.Position = 0; + using (Image img1 = Image.Load(ms, new PngDecoder())) + { + using (MemoryStream ms2 = new MemoryStream()) + { + img1.Save(ms2, new PngEncoder(), new PngEncoderOptions + { + Threshold = 200 + }); + ms2.Position = 0; + using (Image img2 = Image.Load(ms2, new PngDecoder())) + { + using (PixelAccessor pixels1 = img1.Lock()) + using (PixelAccessor pixels2 = img2.Lock()) + { + for (int y = 0; y < img1.Height; y++) + { + for (int x = 0; x < img1.Width; x++) + { + Assert.Equal(pixels1[x, y], pixels2[x, y]); + } + } + } + } + } + } + } + }*/ [Theory] - [WithTestPatternImages(300, 300, PixelTypes.Rgba32)] + [WithTestPatternImage(300, 300, PixelTypes.Rgba32)] public void Resize(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? using (Image image = provider.GetImage()) - using (MemoryStream ms = new MemoryStream()) + using (var ms = new MemoryStream()) { // image.Save(provider.Utility.GetTestOutputFileName("png")); 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()); ms.Position = 0; - using (Image img2 = Image.Load(ms, new PngDecoder())) + using (var img2 = Image.Load(ms, new PngDecoder())) { ImageComparer.Tolerant().VerifySimilarity(image, img2); } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs index 03ad10de40..1f8cbd6a9b 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs @@ -1,13 +1,12 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using SixLabors.ImageSharp.Formats.Tga; using SixLabors.ImageSharp.PixelFormats; using Xunit; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Tga { using static TestImages.Tga; diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs index 9d34684f7a..26fe7cbdad 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System.IO; using SixLabors.ImageSharp.Formats.Tga; @@ -10,6 +8,7 @@ using Xunit; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Formats.Tga { using static TestImages.Tga; @@ -70,7 +69,7 @@ public void Encode_WithCompression_PreserveBitsPerPixel(string imagePath, TgaBit { input.Save(memStream, options); memStream.Position = 0; - using (Image output = Image.Load(memStream)) + using (var output = Image.Load(memStream)) { TgaMetadata meta = output.Metadata.GetTgaMetadata(); Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); @@ -82,7 +81,8 @@ public void Encode_WithCompression_PreserveBitsPerPixel(string imagePath, TgaBit [Theory] [WithFile(Bit32, PixelTypes.Rgba32)] public void Encode_Bit8_Works(TestImageProvider provider, TgaBitsPerPixel bitsPerPixel = TgaBitsPerPixel.Pixel8) - // using tolerant comparer here. The results from magick differ slightly. Maybe a different ToGrey method is used. The image looks otherwise ok. + + // Using tolerant comparer here. The results from magick differ slightly. Maybe a different ToGrey method is used. The image looks otherwise ok. where TPixel : struct, IPixel => TestTgaEncoderCore(provider, bitsPerPixel, TgaCompression.None, useExactComparer: false, compareTolerance: 0.03f); [Theory] @@ -103,7 +103,8 @@ public void Encode_Bit32_Works(TestImageProvider provider, TgaBi [Theory] [WithFile(Bit32, PixelTypes.Rgba32)] public void Encode_Bit8_WithRunLengthEncoding_Works(TestImageProvider provider, TgaBitsPerPixel bitsPerPixel = TgaBitsPerPixel.Pixel8) - // using tolerant comparer here. The results from magick differ slightly. Maybe a different ToGrey method is used. The image looks otherwise ok. + + // Using tolerant comparer here. The results from magick differ slightly. Maybe a different ToGrey method is used. The image looks otherwise ok. where TPixel : struct, IPixel => TestTgaEncoderCore(provider, bitsPerPixel, TgaCompression.RunLength, useExactComparer: false, compareTolerance: 0.03f); [Theory] @@ -131,7 +132,7 @@ private static void TestTgaEncoderCore( { using (Image image = provider.GetImage()) { - var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression}; + var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; using (var memStream = new MemoryStream()) { diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaFileHeaderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaFileHeaderTests.cs index c227b79576..4797397e19 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaFileHeaderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaFileHeaderTests.cs @@ -11,11 +11,12 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga { public class TgaFileHeaderTests { - private static readonly byte[] Data = { + private static readonly byte[] Data = + { 0, 0, 15 // invalid tga image type - }; + }; private MemoryStream Stream { get; } = new MemoryStream(Data); diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs index a2f2e86d7d..090aecb797 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.IO; @@ -11,10 +14,11 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tga { public static class TgaTestUtils { - public static void CompareWithReferenceDecoder(TestImageProvider provider, - Image image, - bool useExactComparer = true, - float compareTolerance = 0.01f) + public static void CompareWithReferenceDecoder( + TestImageProvider provider, + Image image, + bool useExactComparer = true, + float compareTolerance = 0.01f) where TPixel : struct, IPixel { string path = TestImageProvider.GetFilePathOrNull(provider); @@ -23,7 +27,7 @@ public static void CompareWithReferenceDecoder(TestImageProvider throw new InvalidOperationException("CompareToOriginal() works only with file providers!"); } - TestFile testFile = TestFile.Create(path); + var testFile = TestFile.Create(path); Image magickImage = DecodeWithMagick(Configuration.Default, new FileInfo(testFile.FullPath)); if (useExactComparer) { diff --git a/tests/ImageSharp.Tests/GlobalSuppressions.cs b/tests/ImageSharp.Tests/GlobalSuppressions.cs index 2709d32ebc..95fba0dffc 100644 --- a/tests/ImageSharp.Tests/GlobalSuppressions.cs +++ b/tests/ImageSharp.Tests/GlobalSuppressions.cs @@ -1,10 +1,12 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. - +#pragma warning disable SA1404 // Code analysis suppression should have justification [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1013:Public method should be marked as test")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Assertions", "xUnit2013:Do not use equality check to check for collection size.")] - +#pragma warning restore SA1404 // Code analysis suppression should have justification diff --git a/tests/ImageSharp.Tests/GraphicsOptionsTests.cs b/tests/ImageSharp.Tests/GraphicsOptionsTests.cs index e4892e5618..851aba6baf 100644 --- a/tests/ImageSharp.Tests/GraphicsOptionsTests.cs +++ b/tests/ImageSharp.Tests/GraphicsOptionsTests.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.Tests { public class GraphicsOptionsTests { - private static readonly GraphicsOptionsComparer graphicsOptionsComparer = new GraphicsOptionsComparer(); + private static readonly GraphicsOptionsComparer GraphicsOptionsComparer = new GraphicsOptionsComparer(); private readonly GraphicsOptions newGraphicsOptions = new GraphicsOptions(); private readonly GraphicsOptions cloneGraphicsOptions = new GraphicsOptions().DeepClone(); @@ -69,7 +69,7 @@ public void NonDefaultClone() GraphicsOptions actual = expected.DeepClone(); - Assert.Equal(expected, actual, graphicsOptionsComparer); + Assert.Equal(expected, actual, GraphicsOptionsComparer); } [Fact] @@ -84,7 +84,7 @@ public void CloneIsDeep() actual.BlendPercentage = .25F; actual.ColorBlendingMode = PixelColorBlendingMode.HardLight; - Assert.NotEqual(expected, actual, graphicsOptionsComparer); + Assert.NotEqual(expected, actual, GraphicsOptionsComparer); } } } diff --git a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs index 4b5c87c7f5..41921144c2 100644 --- a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs +++ b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs @@ -20,11 +20,11 @@ namespace SixLabors.ImageSharp.Tests.Helpers { public class ParallelHelperTests { - private readonly ITestOutputHelper Output; + private readonly ITestOutputHelper output; public ParallelHelperTests(ITestOutputHelper output) { - this.Output = output; + this.output = output; } /// @@ -95,7 +95,6 @@ public void IterateRows_OverMinimumPixelsLimit_ShouldVisitAllRows( var rectangle = new Rectangle(0, minY, 10, maxY - minY); - int[] expectedData = Enumerable.Repeat(0, minY).Concat(Enumerable.Range(minY, maxY - minY)).ToArray(); var actualData = new int[maxY]; @@ -186,7 +185,6 @@ public void IterateRowsWithTempBuffer_OverMinimumPixelsLimit_ShouldVisitAllRows( }); Assert.Equal(expectedData, actualData); - } public static TheoryData IterateRows_WithEffectiveMinimumPixelsLimit_Data = @@ -321,10 +319,12 @@ void FillRow(int y, Buffer2D buffer) // Fill actual data using IterateRows: var settings = new ParallelExecutionSettings(maxDegreeOfParallelism, memoryAllocator); - ParallelHelper.IterateRows(rect, settings, + ParallelHelper.IterateRows( + rect, + settings, rows => { - this.Output.WriteLine(rows.ToString()); + this.output.WriteLine(rows.ToString()); for (int y = rows.Min; y < rows.Max; y++) { FillRow(y, actual); @@ -343,7 +343,7 @@ void FillRow(int y, Buffer2D buffer) [InlineData(10, -10)] public void IterateRowsRequiresValidRectangle(int width, int height) { - var parallelSettings = new ParallelExecutionSettings(); + var parallelSettings = default(ParallelExecutionSettings); var rect = new Rectangle(0, 0, width, height); @@ -360,7 +360,7 @@ public void IterateRowsRequiresValidRectangle(int width, int height) [InlineData(10, -10)] public void IterateRowsWithTempBufferRequiresValidRectangle(int width, int height) { - var parallelSettings = new ParallelExecutionSettings(); + var parallelSettings = default(ParallelExecutionSettings); var rect = new Rectangle(0, 0, width, height); diff --git a/tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs b/tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs index 6c7a1f2752..e2486fb4ae 100644 --- a/tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs +++ b/tests/ImageSharp.Tests/Helpers/TolerantMathTests.cs @@ -4,8 +4,8 @@ using System; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Helpers { public class TolerantMathTests @@ -165,4 +165,4 @@ public void Floor(double value, double expected) Assert.Equal(expected, actual); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Helpers/Vector4UtilsTests.cs b/tests/ImageSharp.Tests/Helpers/Vector4UtilsTests.cs index f2e98b131a..af789a9b6a 100644 --- a/tests/ImageSharp.Tests/Helpers/Vector4UtilsTests.cs +++ b/tests/ImageSharp.Tests/Helpers/Vector4UtilsTests.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. using System; @@ -11,7 +11,7 @@ namespace SixLabors.ImageSharp.Tests.Helpers { public class Vector4UtilsTests { - private readonly ApproximateFloatComparer ApproximateFloatComparer = new ApproximateFloatComparer(1e-6f); + private readonly ApproximateFloatComparer approximateFloatComparer = new ApproximateFloatComparer(1e-6f); [Theory] [InlineData(0)] @@ -21,11 +21,15 @@ public void Premultiply_VectorSpan(int length) { var rnd = new Random(42); Vector4[] source = rnd.GenerateRandomVectorArray(length, 0, 1); - Vector4[] expected = source.Select(v => { Vector4Utils.Premultiply(ref v); return v; }).ToArray(); + Vector4[] expected = source.Select(v => + { + Vector4Utils.Premultiply(ref v); + return v; + }).ToArray(); Vector4Utils.Premultiply(source); - Assert.Equal(expected, source, this.ApproximateFloatComparer); + Assert.Equal(expected, source, this.approximateFloatComparer); } [Theory] @@ -36,11 +40,15 @@ public void UnPremultiply_VectorSpan(int length) { var rnd = new Random(42); Vector4[] source = rnd.GenerateRandomVectorArray(length, 0, 1); - Vector4[] expected = source.Select(v => { Vector4Utils.UnPremultiply(ref v); return v; }).ToArray(); + Vector4[] expected = source.Select(v => + { + Vector4Utils.UnPremultiply(ref v); + return v; + }).ToArray(); Vector4Utils.UnPremultiply(source); - Assert.Equal(expected, source, this.ApproximateFloatComparer); + Assert.Equal(expected, source, this.approximateFloatComparer); } } } diff --git a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs index 2d5e81173b..9703aea9b6 100644 --- a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs +++ b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs @@ -108,7 +108,6 @@ public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() for (int i = 0, o = 0; i < expected.Length / 2; i++, o += 2) { - Assert.Equal(2, reader.Read(buffer, 0, 2)); Assert.Equal(expected[o], buffer[0]); Assert.Equal(expected[o + 1], buffer[1]); diff --git a/tests/ImageSharp.Tests/IO/LocalFileSystem.cs b/tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs similarity index 100% rename from tests/ImageSharp.Tests/IO/LocalFileSystem.cs rename to tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs diff --git a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs index 035babcb8b..343b1ae77e 100644 --- a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; @@ -26,7 +29,7 @@ public void Clone_WhenDisposed_Throws() } [Theory] - [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgra32(TestImageProvider provider) { using (Image image = provider.GetImage()) @@ -52,7 +55,7 @@ public void CloneAs_ToBgra32(TestImageProvider provider) } [Theory] - [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgr24(TestImageProvider provider) { using (Image image = provider.GetImage()) @@ -77,7 +80,7 @@ public void CloneAs_ToBgr24(TestImageProvider provider) } [Theory] - [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToArgb32(TestImageProvider provider) { using (Image image = provider.GetImage()) @@ -103,7 +106,7 @@ public void CloneAs_ToArgb32(TestImageProvider provider) } [Theory] - [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToRgb24(TestImageProvider provider) { using (Image image = provider.GetImage()) diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs index 80ab860efe..6997300d59 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; using System.Linq; @@ -104,11 +104,7 @@ public void Constructor_FramesMustHaveSameSize() { new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 1, 1) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 1, 1) }); }); Assert.StartsWith("Frame must have the same dimensions as the image.", ex.Message); @@ -134,11 +130,7 @@ public void RemoveAtFrame_CanRemoveFrameZeroIfMultipleFramesExist() { var collection = new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 10, 10) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 10, 10) }); collection.RemoveFrame(0); Assert.Equal(1, collection.Count); @@ -149,11 +141,7 @@ public void RootFrameIsFrameAtIndexZero() { var collection = new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 10, 10) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 10, 10) }); Assert.Equal(collection.RootFrame, collection[0]); } @@ -163,11 +151,7 @@ public void ConstructorPopulatesFrames() { var collection = new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 10, 10) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 10, 10) }); Assert.Equal(2, collection.Count); } @@ -177,11 +161,7 @@ public void DisposeClearsCollection() { var collection = new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 10, 10) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 10, 10) }); collection.Dispose(); @@ -193,11 +173,7 @@ public void Dispose_DisposesAllInnerFrames() { var collection = new ImageFrameCollection( this.Image, - new[] - { - new ImageFrame(Configuration.Default, 10, 10), - new ImageFrame(Configuration.Default, 10, 10) - }); + new[] { new ImageFrame(Configuration.Default, 10, 10), new ImageFrame(Configuration.Default, 10, 10) }); IPixelSource[] framesSnapShot = collection.OfType>().ToArray(); collection.Dispose(); @@ -206,13 +182,13 @@ public void Dispose_DisposesAllInnerFrames() framesSnapShot, f => { - // the pixel source of the frame is null after its been disposed. + // The pixel source of the frame is null after its been disposed. Assert.Null(f.PixelBuffer); }); } [Theory] - [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { @@ -228,7 +204,7 @@ public void CloneFrame(TestImageProvider provider) } [Theory] - [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs index e41bb4c176..10d9a44890 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; using System.Linq; @@ -61,7 +61,6 @@ public void InsertFrame_OfDifferentPixelType() var actualFrame = (ImageFrame)this.Collection[0]; actualFrame.ComparePixelBufferTo(expectedAllBlue); - } [Fact] @@ -118,11 +117,9 @@ public void InsertNewFrame_FramesNotBeNull() Assert.StartsWith("Value cannot be null.", ex.Message); } - [Fact] public void RemoveAtFrame_ThrowIfRemovingLastFrame() { - InvalidOperationException ex = Assert.Throws( () => { @@ -147,7 +144,7 @@ public void RootFrameIsFrameAtIndexZero() } [Theory] - [WithTestPatternImages(10, 10, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImage(10, 10, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { @@ -168,7 +165,7 @@ public void CloneFrame(TestImageProvider provider) } [Theory] - [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { @@ -267,6 +264,7 @@ public void Contains_FalseIfNonMember() /// /// Integration test for end-to end API validation. /// + /// The pixel type of the image. [Theory] [WithFile(TestImages.Gif.Giphy, PixelTypes.Rgba32)] public void ConstructGif_FromDifferentPixelTypes(TestImageProvider provider) @@ -276,7 +274,6 @@ public void ConstructGif_FromDifferentPixelTypes(TestImageProvider(source.GetConfiguration(), source.Width, source.Height)) { // Giphy.gif has 5 frames - ImportFrameAs(source.Frames, dest.Frames, 0); ImportFrameAs(source.Frames, dest.Frames, 1); ImportFrameAs(source.Frames, dest.Frames, 2); @@ -311,7 +308,6 @@ private static void ImportFrameAs(ImageFrameCollection source, ImageFram private static void CompareGifMetadata(ImageFrame a, ImageFrame b) { // TODO: all metadata classes should be equatable! - GifFrameMetadata aData = a.Metadata.GetGifMetadata(); GifFrameMetadata bData = b.Metadata.GetGifMetadata(); diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.cs index d475513fa6..d81defbcda 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using SixLabors.ImageSharp.PixelFormats; @@ -7,6 +10,7 @@ namespace SixLabors.ImageSharp.Tests public abstract partial class ImageFrameCollectionTests : IDisposable { protected Image Image { get; } + protected ImageFrameCollection Collection { get; } public ImageFrameCollectionTests() diff --git a/tests/ImageSharp.Tests/Image/ImageSaveTests.cs b/tests/ImageSharp.Tests/Image/ImageSaveTests.cs index 25bc3f6049..156e51578b 100644 --- a/tests/ImageSharp.Tests/Image/ImageSaveTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageSaveTests.cs @@ -3,22 +3,21 @@ using System; using System.IO; - +using Moq; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.IO; using SixLabors.ImageSharp.PixelFormats; -using Moq; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { /// - /// Tests the class. + /// Tests the class. /// public class ImageSaveTests : IDisposable { - private readonly Image Image; + private readonly Image image; private readonly Mock fileSystem; private readonly Mock encoder; private readonly Mock encoderNotInFormat; @@ -42,7 +41,7 @@ public ImageSaveTests() }; config.ImageFormatsManager.AddImageFormatDetector(this.localMimeTypeDetector); config.ImageFormatsManager.SetEncoder(this.localImageFormat.Object, this.encoder.Object); - this.Image = new Image(config, 1, 1); + this.image = new Image(config, 1, 1); } [Fact] @@ -50,38 +49,37 @@ public void SavePath() { var stream = new MemoryStream(); this.fileSystem.Setup(x => x.Create("path.png")).Returns(stream); - this.Image.Save("path.png"); + this.image.Save("path.png"); - this.encoder.Verify(x => x.Encode(this.Image, stream)); + this.encoder.Verify(x => x.Encode(this.image, stream)); } - [Fact] public void SavePathWithEncoder() { var stream = new MemoryStream(); this.fileSystem.Setup(x => x.Create("path.jpg")).Returns(stream); - this.Image.Save("path.jpg", this.encoderNotInFormat.Object); + this.image.Save("path.jpg", this.encoderNotInFormat.Object); - this.encoderNotInFormat.Verify(x => x.Encode(this.Image, stream)); + this.encoderNotInFormat.Verify(x => x.Encode(this.image, stream)); } [Fact] public void ToBase64String() { - string str = this.Image.ToBase64String(this.localImageFormat.Object); + string str = this.image.ToBase64String(this.localImageFormat.Object); - this.encoder.Verify(x => x.Encode(this.Image, It.IsAny())); + this.encoder.Verify(x => x.Encode(this.image, It.IsAny())); } [Fact] public void SaveStreamWithMime() { var stream = new MemoryStream(); - this.Image.Save(stream, this.localImageFormat.Object); + this.image.Save(stream, this.localImageFormat.Object); - this.encoder.Verify(x => x.Encode(this.Image, stream)); + this.encoder.Verify(x => x.Encode(this.image, stream)); } [Fact] @@ -89,14 +87,14 @@ public void SaveStreamWithEncoder() { var stream = new MemoryStream(); - this.Image.Save(stream, this.encoderNotInFormat.Object); + this.image.Save(stream, this.encoderNotInFormat.Object); - this.encoderNotInFormat.Verify(x => x.Encode(this.Image, stream)); + this.encoderNotInFormat.Verify(x => x.Encode(this.image, stream)); } public void Dispose() { - this.Image.Dispose(); + this.image.Dispose(); } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs index 96747b0d29..dcf4dcfe84 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs @@ -6,8 +6,8 @@ using SixLabors.ImageSharp.Formats; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { public partial class ImageTests diff --git a/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs b/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs index ec6705d0ec..dff83df26d 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.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. using System; @@ -17,7 +17,7 @@ public partial class ImageTests public abstract class ImageLoadTestBase : IDisposable { protected Image localStreamReturnImageRgba32; - + protected Image localStreamReturnImageAgnostic; protected Mock localDecoder; @@ -28,7 +28,7 @@ public abstract class ImageLoadTestBase : IDisposable protected readonly string MockFilePath = Guid.NewGuid().ToString(); - internal readonly Mock localFileSystemMock = new Mock(); + internal readonly Mock LocalFileSystemMock = new Mock(); protected readonly TestFileSystem topLevelFileSystem = new TestFileSystem(); @@ -57,7 +57,7 @@ protected ImageLoadTestBase() this.localDecoder = new Mock(); this.localMimeTypeDetector = new MockImageFormatDetector(this.localImageFormatMock.Object); - + this.localDecoder.Setup(x => x.Decode(It.IsAny(), It.IsAny())) .Callback((c, s) => { @@ -68,7 +68,7 @@ protected ImageLoadTestBase() } }) .Returns(this.localStreamReturnImageRgba32); - + this.localDecoder.Setup(x => x.Decode(It.IsAny(), It.IsAny())) .Callback((c, s) => { @@ -79,7 +79,6 @@ protected ImageLoadTestBase() } }) .Returns(this.localStreamReturnImageAgnostic); - this.LocalConfiguration = new Configuration { @@ -92,18 +91,18 @@ protected ImageLoadTestBase() this.Marker = Guid.NewGuid().ToByteArray(); this.DataStream = this.TestFormat.CreateStream(this.Marker); - this.localFileSystemMock.Setup(x => x.OpenRead(this.MockFilePath)).Returns(this.DataStream); + this.LocalFileSystemMock.Setup(x => x.OpenRead(this.MockFilePath)).Returns(this.DataStream); this.topLevelFileSystem.AddFile(this.MockFilePath, this.DataStream); - this.LocalConfiguration.FileSystem = this.localFileSystemMock.Object; + this.LocalConfiguration.FileSystem = this.LocalFileSystemMock.Object; this.TopLevelConfiguration.FileSystem = this.topLevelFileSystem; } public void Dispose() { - // clean up the global object; + // Clean up the global object; this.localStreamReturnImageRgba32?.Dispose(); this.localStreamReturnImageAgnostic?.Dispose(); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_PassLocalConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_PassLocalConfiguration.cs index 58e19c9f70..cb3400758f 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_PassLocalConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_PassLocalConfiguration.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; @@ -92,7 +92,7 @@ public void WhenPathIsNull_Throws() Assert.Throws( () => { - Image.Load(this.TopLevelConfiguration,(string)null); + Image.Load(this.TopLevelConfiguration, (string)null); }); } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs index 4d3a229c55..58a67f9df6 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; @@ -17,12 +17,12 @@ public partial class ImageTests public class Load_FileSystemPath_UseDefaultConfiguration { private string Path { get; } = TestFile.GetInputFileFullPath(TestImages.Bmp.Bit8); - + private static void VerifyDecodedImage(Image img) { Assert.Equal(new Size(127, 64), img.Size()); } - + [Fact] public void Path_Specific() { @@ -31,7 +31,7 @@ public void Path_Specific() VerifyDecodedImage(img); } } - + [Fact] public void Path_Agnostic() { @@ -40,8 +40,7 @@ public void Path_Agnostic() VerifyDecodedImage(img); } } - - + [Fact] public void Path_Decoder_Specific() { @@ -50,7 +49,7 @@ public void Path_Decoder_Specific() VerifyDecodedImage(img); } } - + [Fact] public void Path_Decoder_Agnostic() { @@ -59,7 +58,7 @@ public void Path_Decoder_Agnostic() VerifyDecodedImage(img); } } - + [Fact] public void Path_OutFormat_Specific() { @@ -79,6 +78,7 @@ public void Path_OutFormat_Agnostic() Assert.IsType(format); } } + [Fact] public void WhenFileNotFound_Throws() { diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs index 19887d9bcc..f65dccc7e9 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs @@ -17,14 +17,14 @@ public partial class ImageTests public class Load_FromBytes_UseGlobalConfiguration { private static byte[] ByteArray { get; } = TestFile.Create(TestImages.Bmp.Bit8).Bytes; - + private static Span ByteSpan => new Span(ByteArray); private static void VerifyDecodedImage(Image img) { Assert.Equal(new Size(127, 64), img.Size()); } - + [Theory] [InlineData(false)] [InlineData(true)] @@ -47,7 +47,6 @@ public void Bytes_Agnostic(bool useSpan) } } - [Theory] [InlineData(false)] [InlineData(true)] @@ -82,7 +81,7 @@ public void Bytes_OutFormat_Specific(bool useSpan) Assert.IsType(format); } } - + [Theory] [InlineData(false)] [InlineData(true)] @@ -97,4 +96,4 @@ public void Bytes_OutFormat_Agnostic(bool useSpan) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs index 980ed17ceb..a35557c83e 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs @@ -18,14 +18,14 @@ public partial class ImageTests public class Load_FromStream_UseDefaultConfiguration : IDisposable { private static readonly byte[] Data = TestFile.Create(TestImages.Bmp.Bit8).Bytes; - + private MemoryStream Stream { get; } = new MemoryStream(Data); - + private static void VerifyDecodedImage(Image img) { Assert.Equal(new Size(127, 64), img.Size()); } - + [Fact] public void Stream_Specific() { @@ -34,7 +34,7 @@ public void Stream_Specific() VerifyDecodedImage(img); } } - + [Fact] public void Stream_Agnostic() { @@ -43,7 +43,7 @@ public void Stream_Agnostic() VerifyDecodedImage(img); } } - + [Fact] public void Stream_OutFormat_Specific() { @@ -53,7 +53,7 @@ public void Stream_OutFormat_Specific() Assert.IsType(format); } } - + [Fact] public void Stream_Decoder_Specific() { @@ -62,7 +62,7 @@ public void Stream_Decoder_Specific() VerifyDecodedImage(img); } } - + [Fact] public void Stream_Decoder_Agnostic() { @@ -71,7 +71,7 @@ public void Stream_Decoder_Agnostic() VerifyDecodedImage(img); } } - + [Fact] public void Stream_OutFormat_Agnostic() { @@ -88,4 +88,4 @@ public void Dispose() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs index e00a70e392..dc65ecfef9 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs @@ -1,8 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -// ReSharper disable InconsistentNaming - using System; using System.IO; @@ -12,6 +10,7 @@ using SixLabors.ImageSharp.PixelFormats; using Xunit; +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { using SixLabors.ImageSharp.Formats; diff --git a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs index 04d05f6dc7..ea5df2694f 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs @@ -11,7 +11,6 @@ using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Metadata; using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; using Xunit; // ReSharper disable InconsistentNaming @@ -25,7 +24,7 @@ public class WrapMemory /// A exposing the locked pixel memory of a instance. /// TODO: This should be an example in https://github.com/SixLabors/Samples /// - class BitmapMemoryManager : MemoryManager + public class BitmapMemoryManager : MemoryManager { private readonly Bitmap bitmap; diff --git a/tests/ImageSharp.Tests/Image/ImageTests.cs b/tests/ImageSharp.Tests/Image/ImageTests.cs index 1e48f14c86..99bdfceccb 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.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. using SixLabors.ImageSharp.Advanced; @@ -7,8 +7,8 @@ using SixLabors.ImageSharp.Tests.Memory; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { /// @@ -25,7 +25,7 @@ public void Width_Height() { Assert.Equal(11, image.Width); Assert.Equal(23, image.Height); - Assert.Equal(11*23, image.GetPixelSpan().Length); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); image.ComparePixelBufferTo(default(Rgba32)); Assert.Equal(Configuration.Default, image.GetConfiguration()); @@ -74,7 +74,7 @@ public void CreateUninitialized() configuration.MemoryAllocator = new TestMemoryAllocator(dirtyValue); var metadata = new ImageMetadata(); - using (Image image = Image.CreateUninitialized(configuration, 21, 22, metadata)) + using (var image = Image.CreateUninitialized(configuration, 21, 22, metadata)) { Assert.Equal(21, image.Width); Assert.Equal(22, image.Height); diff --git a/tests/ImageSharp.Tests/Issues/Issue594.cs b/tests/ImageSharp.Tests/Issues/Issue594.cs index 927f0a5edc..8ddd9caf83 100644 --- a/tests/ImageSharp.Tests/Issues/Issue594.cs +++ b/tests/ImageSharp.Tests/Issues/Issue594.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Numerics; using SixLabors.ImageSharp.PixelFormats; using Xunit; @@ -13,8 +16,8 @@ public class Issue594 public void NormalizedByte4() { // Test PackedValue - Assert.Equal((uint)0x0, new NormalizedByte4(Vector4.Zero).PackedValue); - Assert.Equal((uint)0x7F7F7F7F, new NormalizedByte4(Vector4.One).PackedValue); + Assert.Equal(0x0U, new NormalizedByte4(Vector4.Zero).PackedValue); + Assert.Equal(0x7F7F7F7FU, new NormalizedByte4(Vector4.One).PackedValue); Assert.Equal(0x81818181, new NormalizedByte4(-Vector4.One).PackedValue); // Test ToVector4 @@ -46,48 +49,48 @@ public void NormalizedByte4() n.FromRgba32(new Rgba32(141, 90, 192, 39)); Assert.Equal(0xA740DA0D, n.PackedValue); - Assert.Equal((uint)958796544, new NormalizedByte4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); + Assert.Equal(958796544U, new NormalizedByte4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); - //var rgb = default(Rgb24); - //var rgba = default(Rgba32); - //var bgr = default(Bgr24); - //var bgra = default(Bgra32); - //var argb = default(Argb32); + // var rgb = default(Rgb24); + // var rgba = default(Rgba32); + // var bgr = default(Bgr24); + // var bgra = default(Bgra32); + // var argb = default(Argb32); - //new NormalizedByte4(x, y, z, w).ToRgb24(ref rgb); - //Assert.Equal(rgb, new Rgb24(141, 90, 192)); + // new NormalizedByte4(x, y, z, w).ToRgb24(ref rgb); + // Assert.Equal(rgb, new Rgb24(141, 90, 192)); - //new NormalizedByte4(x, y, z, w).ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(141, 90, 192, 39)); + // new NormalizedByte4(x, y, z, w).ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(141, 90, 192, 39)); - //new NormalizedByte4(x, y, z, w).ToBgr24(ref bgr); - //Assert.Equal(bgr, new Bgr24(141, 90, 192)); + // new NormalizedByte4(x, y, z, w).ToBgr24(ref bgr); + // Assert.Equal(bgr, new Bgr24(141, 90, 192)); - //new NormalizedByte4(x, y, z, w).ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(141, 90, 192, 39)); // this assert fails in Release build on linux (#594) + // new NormalizedByte4(x, y, z, w).ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(141, 90, 192, 39)); // this assert fails in Release build on linux (#594) - //new NormalizedByte4(x, y, z, w).ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(141, 90, 192, 39)); + // new NormalizedByte4(x, y, z, w).ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(141, 90, 192, 39)); // http://community.monogame.net/t/normalizedbyte4-texture2d-gives-different-results-from-xna/8012/8 - //var r = default(NormalizedByte4); - //r.FromRgba32(new Rgba32(9, 115, 202, 127)); - //r.ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); - - //r.PackedValue = 0xff4af389; - //r.ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); - - //r = default(NormalizedByte4); - //r.FromArgb32(new Argb32(9, 115, 202, 127)); - //r.ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(9, 115, 202, 127)); - - //r = default(NormalizedByte4); - //r.FromBgra32(new Bgra32(9, 115, 202, 127)); - //r.ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(9, 115, 202, 127)); + // var r = default(NormalizedByte4); + // r.FromRgba32(new Rgba32(9, 115, 202, 127)); + // r.ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); + + // r.PackedValue = 0xff4af389; + // r.ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); + + // r = default(NormalizedByte4); + // r.FromArgb32(new Argb32(9, 115, 202, 127)); + // r.ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(9, 115, 202, 127)); + + // r = default(NormalizedByte4); + // r.FromBgra32(new Bgra32(9, 115, 202, 127)); + // r.ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(9, 115, 202, 127)); } // This test fails for unknown reason in Release mode on linux and is meant to help reproducing the issue @@ -96,8 +99,8 @@ public void NormalizedByte4() public void NormalizedShort4() { // Test PackedValue - Assert.Equal((ulong)0x0, new NormalizedShort4(Vector4.Zero).PackedValue); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, new NormalizedShort4(Vector4.One).PackedValue); + Assert.Equal(0x0UL, new NormalizedShort4(Vector4.Zero).PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, new NormalizedShort4(Vector4.One).PackedValue); Assert.Equal(0x8001800180018001, new NormalizedShort4(-Vector4.One).PackedValue); // Test ToVector4 @@ -117,7 +120,7 @@ public void NormalizedShort4() // Test FromScaledVector4. var pixel = default(NormalizedShort4); pixel.FromScaledVector4(scaled); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, pixel.PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, pixel.PackedValue); // Test Ordering float x = 0.1f; @@ -125,43 +128,43 @@ public void NormalizedShort4() float z = 0.5f; float w = -0.7f; Assert.Equal(0xa6674000d99a0ccd, new NormalizedShort4(x, y, z, w).PackedValue); - Assert.Equal((ulong)4150390751449251866, new NormalizedShort4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); + Assert.Equal(4150390751449251866UL, new NormalizedShort4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); - //var rgb = default(Rgb24); - //var rgba = default(Rgba32); - //var bgr = default(Bgr24); - //var bgra = default(Bgra32); - //var argb = default(Argb32); + // var rgb = default(Rgb24); + // var rgba = default(Rgba32); + // var bgr = default(Bgr24); + // var bgra = default(Bgra32); + // var argb = default(Argb32); - //new NormalizedShort4(x, y, z, w).ToRgb24(ref rgb); - //Assert.Equal(rgb, new Rgb24(141, 90, 192)); + // new NormalizedShort4(x, y, z, w).ToRgb24(ref rgb); + // Assert.Equal(rgb, new Rgb24(141, 90, 192)); - //new NormalizedShort4(x, y, z, w).ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(141, 90, 192, 39)); // this assert fails in Release build on linux (#594) + // new NormalizedShort4(x, y, z, w).ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(141, 90, 192, 39)); // this assert fails in Release build on linux (#594) - //new NormalizedShort4(x, y, z, w).ToBgr24(ref bgr); - //Assert.Equal(bgr, new Bgr24(141, 90, 192)); + // new NormalizedShort4(x, y, z, w).ToBgr24(ref bgr); + // Assert.Equal(bgr, new Bgr24(141, 90, 192)); - //new NormalizedShort4(x, y, z, w).ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(141, 90, 192, 39)); + // new NormalizedShort4(x, y, z, w).ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(141, 90, 192, 39)); - //new NormalizedShort4(x, y, z, w).ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(141, 90, 192, 39)); + // new NormalizedShort4(x, y, z, w).ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(141, 90, 192, 39)); - //var r = default(NormalizedShort4); - //r.FromRgba32(new Rgba32(9, 115, 202, 127)); - //r.ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); + // var r = default(NormalizedShort4); + // r.FromRgba32(new Rgba32(9, 115, 202, 127)); + // r.ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(9, 115, 202, 127)); - //r = default(NormalizedShort4); - //r.FromBgra32(new Bgra32(9, 115, 202, 127)); - //r.ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(9, 115, 202, 127)); + // r = default(NormalizedShort4); + // r.FromBgra32(new Bgra32(9, 115, 202, 127)); + // r.ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(9, 115, 202, 127)); - //r = default(NormalizedShort4); - //r.FromArgb32(new Argb32(9, 115, 202, 127)); - //r.ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(9, 115, 202, 127)); + // r = default(NormalizedShort4); + // r.FromArgb32(new Argb32(9, 115, 202, 127)); + // r.ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(9, 115, 202, 127)); } // This test fails for unknown reason in Release mode on linux and is meant to help reproducing the issue @@ -170,8 +173,8 @@ public void NormalizedShort4() public void Short4() { // Test the limits. - Assert.Equal((ulong)0x0, new Short4(Vector4.Zero).PackedValue); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, new Short4(Vector4.One * 0x7FFF).PackedValue); + Assert.Equal(0x0UL, new Short4(Vector4.Zero).PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, new Short4(Vector4.One * 0x7FFF).PackedValue); Assert.Equal(0x8000800080008000, new Short4(Vector4.One * -0x8000).PackedValue); // Test ToVector4. @@ -193,7 +196,7 @@ public void Short4() // Test FromScaledVector4. var pixel = default(Short4); pixel.FromScaledVector4(scaled); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, pixel.PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, pixel.PackedValue); // Test clamping. Assert.Equal(Vector4.One * 0x7FFF, new Short4(Vector4.One * 1234567.0f).ToVector4()); @@ -210,43 +213,43 @@ public void Short4() y = 12653; z = 29623; w = 193; - Assert.Equal((ulong)0x00c173b7316d2d1b, new Short4(x, y, z, w).PackedValue); + Assert.Equal(0x00c173b7316d2d1bUL, new Short4(x, y, z, w).PackedValue); - //var rgb = default(Rgb24); - //var rgba = default(Rgba32); - //var bgr = default(Bgr24); - //var bgra = default(Bgra32); - //var argb = default(Argb32); + // var rgb = default(Rgb24); + // var rgba = default(Rgba32); + // var bgr = default(Bgr24); + // var bgra = default(Bgra32); + // var argb = default(Argb32); - //new Short4(x, y, z, w).ToRgb24(ref rgb); - //Assert.Equal(rgb, new Rgb24(172, 177, 243)); // this assert fails in Release build on linux (#594) + // new Short4(x, y, z, w).ToRgb24(ref rgb); + // Assert.Equal(rgb, new Rgb24(172, 177, 243)); // this assert fails in Release build on linux (#594) - //new Short4(x, y, z, w).ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(172, 177, 243, 128)); + // new Short4(x, y, z, w).ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(172, 177, 243, 128)); - //new Short4(x, y, z, w).ToBgr24(ref bgr); - //Assert.Equal(bgr, new Bgr24(172, 177, 243)); + // new Short4(x, y, z, w).ToBgr24(ref bgr); + // Assert.Equal(bgr, new Bgr24(172, 177, 243)); - //new Short4(x, y, z, w).ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(172, 177, 243, 128)); + // new Short4(x, y, z, w).ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(172, 177, 243, 128)); - //new Short4(x, y, z, w).ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(172, 177, 243, 128)); + // new Short4(x, y, z, w).ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(172, 177, 243, 128)); - //var r = default(Short4); - //r.FromRgba32(new Rgba32(20, 38, 0, 255)); - //r.ToRgba32(ref rgba); - //Assert.Equal(rgba, new Rgba32(20, 38, 0, 255)); + // var r = default(Short4); + // r.FromRgba32(new Rgba32(20, 38, 0, 255)); + // r.ToRgba32(ref rgba); + // Assert.Equal(rgba, new Rgba32(20, 38, 0, 255)); - //r = default(Short4); - //r.FromBgra32(new Bgra32(20, 38, 0, 255)); - //r.ToBgra32(ref bgra); - //Assert.Equal(bgra, new Bgra32(20, 38, 0, 255)); + // r = default(Short4); + // r.FromBgra32(new Bgra32(20, 38, 0, 255)); + // r.ToBgra32(ref bgra); + // Assert.Equal(bgra, new Bgra32(20, 38, 0, 255)); - //r = default(Short4); - //r.FromArgb32(new Argb32(20, 38, 0, 255)); - //r.ToArgb32(ref argb); - //Assert.Equal(argb, new Argb32(20, 38, 0, 255)); + // r = default(Short4); + // r.FromArgb32(new Argb32(20, 38, 0, 255)); + // r.ToArgb32(ref argb); + // Assert.Equal(argb, new Argb32(20, 38, 0, 255)); } // Comparison helpers with small tolerance to allow for floating point rounding during computations. diff --git a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs index a0e4f54ac8..9eea5518f4 100644 --- a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs +++ b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs @@ -13,7 +13,6 @@ using Xunit; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Memory { public class Buffer2DTests @@ -87,7 +86,7 @@ public void Indexer(int width, int height, int x, int y) ref TestStructs.Foo actual = ref buffer[x, y]; - ref TestStructs.Foo expected = ref span[y * width + x]; + ref TestStructs.Foo expected = ref span[(y * width) + x]; Assert.True(Unsafe.AreSame(ref expected, ref actual)); } diff --git a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs index 9192798628..eaa2fea0f0 100644 --- a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs +++ b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs @@ -30,7 +30,7 @@ private static Buffer2D CreateTestBuffer(int w, int h) { for (int x = 0; x < w; x++) { - buffer[x, y] = y * 100 + x; + buffer[x, y] = (y * 100) + x; } } @@ -49,7 +49,7 @@ public void Indexer(int rx, int ry, int x, int y) BufferArea area = buffer.GetArea(r); int value = area[x, y]; - int expected = (ry + y) * 100 + rx + x; + int expected = ((ry + y) * 100) + rx + x; Assert.Equal(expected, value); } } @@ -71,7 +71,7 @@ public void GetRowSpan(int rx, int ry, int y, int w, int h) for (int i = 0; i < w; i++) { - int expected = (ry + y) * 100 + rx + i; + int expected = ((ry + y) * 100) + rx + i; int value = span[i]; Assert.Equal(expected, value); @@ -93,7 +93,7 @@ public void GetSubArea() Assert.Equal(buffer, area1.DestinationBuffer); Assert.Equal(expectedRect, area1.Rectangle); - int value00 = 12 * 100 + 10; + int value00 = (12 * 100) + 10; Assert.Equal(value00, area1[0, 0]); } } diff --git a/tests/ImageSharp.Tests/Memory/MemorySourceTests.cs b/tests/ImageSharp.Tests/Memory/MemorySourceTests.cs index 535204e8dc..5d3958dd87 100644 --- a/tests/ImageSharp.Tests/Memory/MemorySourceTests.cs +++ b/tests/ImageSharp.Tests/Memory/MemorySourceTests.cs @@ -150,13 +150,11 @@ public void WhenDestIsNotMemoryOwner_DifferentSize_Throws(bool sourceIsOwner) sourceOwner.Memory.Span[10] = color; // Act: - Assert.ThrowsAny( - () => MemorySource.SwapOrCopyContent(ref dest, ref source) - ); + Assert.ThrowsAny(() => MemorySource.SwapOrCopyContent(ref dest, ref source)); Assert.Equal(color, source.Memory.Span[10]); Assert.NotEqual(color, dest.Memory.Span[10]); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Memory/TestStructs.cs b/tests/ImageSharp.Tests/Memory/TestStructs.cs index 2c9417b117..858bb8e646 100644 --- a/tests/ImageSharp.Tests/Memory/TestStructs.cs +++ b/tests/ImageSharp.Tests/Memory/TestStructs.cs @@ -6,8 +6,6 @@ namespace SixLabors.ImageSharp.Tests.Memory { - - public static class TestStructs { public struct Foo : IEquatable @@ -29,6 +27,7 @@ internal static Foo[] CreateArray(int size) { result[i] = new Foo(i + 1, i + 1); } + return result; } @@ -39,16 +38,15 @@ internal static Foo[] CreateArray(int size) public override int GetHashCode() { int hashCode = -1817952719; - hashCode = hashCode * -1521134295 + base.GetHashCode(); - hashCode = hashCode * -1521134295 + this.A.GetHashCode(); - hashCode = hashCode * -1521134295 + this.B.GetHashCode(); + hashCode = (hashCode * -1521134295) + base.GetHashCode(); + hashCode = (hashCode * -1521134295) + this.A.GetHashCode(); + hashCode = (hashCode * -1521134295) + this.B.GetHashCode(); return hashCode; } public override string ToString() => $"({this.A},{this.B})"; } - /// /// sizeof(AlignedFoo) == sizeof(long) /// @@ -80,17 +78,18 @@ internal static AlignedFoo[] CreateArray(int size) { result[i] = new AlignedFoo(i + 1, i + 1); } + return result; } public override int GetHashCode() { int hashCode = -1817952719; - hashCode = hashCode * -1521134295 + base.GetHashCode(); - hashCode = hashCode * -1521134295 + this.A.GetHashCode(); - hashCode = hashCode * -1521134295 + this.B.GetHashCode(); + hashCode = (hashCode * -1521134295) + base.GetHashCode(); + hashCode = (hashCode * -1521134295) + this.A.GetHashCode(); + hashCode = (hashCode * -1521134295) + this.B.GetHashCode(); return hashCode; } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs index 9c86d060a6..d3177f6f59 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs @@ -21,7 +21,14 @@ public class ExifProfileTests { public enum TestImageWriteFormat { + /// + /// Writes a jpg file. + /// Jpeg, + + /// + /// Writes a png file. + /// Png } @@ -260,18 +267,18 @@ public void Syncs() exifProfile.Sync(metaData); - Assert.Equal(100, (metaData.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); - Assert.Equal(300, (metaData.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); + Assert.Equal(100, metaData.ExifProfile.GetValue(ExifTag.XResolution).Value.ToDouble()); + Assert.Equal(300, metaData.ExifProfile.GetValue(ExifTag.YResolution).Value.ToDouble()); metaData.VerticalResolution = 150; - Assert.Equal(100, (metaData.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); - Assert.Equal(300, (metaData.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); + Assert.Equal(100, metaData.ExifProfile.GetValue(ExifTag.XResolution).Value.ToDouble()); + Assert.Equal(300, metaData.ExifProfile.GetValue(ExifTag.YResolution).Value.ToDouble()); exifProfile.Sync(metaData); - Assert.Equal(100, (metaData.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); - Assert.Equal(150, (metaData.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); + Assert.Equal(100, metaData.ExifProfile.GetValue(ExifTag.XResolution).Value.ToDouble()); + Assert.Equal(150, metaData.ExifProfile.GetValue(ExifTag.YResolution).Value.ToDouble()); } [Fact] diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifTagDescriptionAttributeTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifTagDescriptionAttributeTests.cs index a6ad8df8b4..64219fce02 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifTagDescriptionAttributeTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifTagDescriptionAttributeTests.cs @@ -6,7 +6,7 @@ namespace SixLabors.ImageSharp.Tests { - public class ExifDescriptionAttributeTests + public class ExifTagDescriptionAttributeTests { [Fact] public void TestExifTag() diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs index d015fefc4c..e9b2549817 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using SixLabors.ImageSharp.Metadata.Profiles.Exif; using SixLabors.ImageSharp.Primitives; using Xunit; diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.CurvesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderCurvesTests.cs similarity index 86% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.CurvesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderCurvesTests.cs index b6fa98b61e..4ca7f84a57 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.CurvesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderCurvesTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataReaderCurvesTests [MemberData(nameof(IccTestDataCurves.OneDimensionalCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadOneDimensionalCurve(byte[] data, IccOneDimensionalCurve expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccOneDimensionalCurve output = reader.ReadOneDimensionalCurve(); @@ -23,7 +23,7 @@ internal void ReadOneDimensionalCurve(byte[] data, IccOneDimensionalCurve expect [MemberData(nameof(IccTestDataCurves.ResponseCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadResponseCurve(byte[] data, IccResponseCurve expected, int channelCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccResponseCurve output = reader.ReadResponseCurve(channelCount); @@ -34,7 +34,7 @@ internal void ReadResponseCurve(byte[] data, IccResponseCurve expected, int chan [MemberData(nameof(IccTestDataCurves.ParametricCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadParametricCurve(byte[] data, IccParametricCurve expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccParametricCurve output = reader.ReadParametricCurve(); @@ -45,7 +45,7 @@ internal void ReadParametricCurve(byte[] data, IccParametricCurve expected) [MemberData(nameof(IccTestDataCurves.CurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadCurveSegment(byte[] data, IccCurveSegment expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccCurveSegment output = reader.ReadCurveSegment(); @@ -56,7 +56,7 @@ internal void ReadCurveSegment(byte[] data, IccCurveSegment expected) [MemberData(nameof(IccTestDataCurves.FormulaCurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadFormulaCurveElement(byte[] data, IccFormulaCurveElement expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccFormulaCurveElement output = reader.ReadFormulaCurveElement(); @@ -67,7 +67,7 @@ internal void ReadFormulaCurveElement(byte[] data, IccFormulaCurveElement expect [MemberData(nameof(IccTestDataCurves.SampledCurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void ReadSampledCurveElement(byte[] data, IccSampledCurveElement expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccSampledCurveElement output = reader.ReadSampledCurveElement(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.LutTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderLutTests.cs similarity index 86% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.LutTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderLutTests.cs index 04284cb496..96c8975378 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.LutTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderLutTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataReaderLutTests [MemberData(nameof(IccTestDataLut.ClutTestData), MemberType = typeof(IccTestDataLut))] internal void ReadClut(byte[] data, IccClut expected, int inChannelCount, int outChannelCount, bool isFloat) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccClut output = reader.ReadClut(inChannelCount, outChannelCount, isFloat); @@ -23,7 +23,7 @@ internal void ReadClut(byte[] data, IccClut expected, int inChannelCount, int ou [MemberData(nameof(IccTestDataLut.Clut8TestData), MemberType = typeof(IccTestDataLut))] internal void ReadClut8(byte[] data, IccClut expected, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccClut output = reader.ReadClut8(inChannelCount, outChannelCount, gridPointCount); @@ -34,7 +34,7 @@ internal void ReadClut8(byte[] data, IccClut expected, int inChannelCount, int o [MemberData(nameof(IccTestDataLut.Clut16TestData), MemberType = typeof(IccTestDataLut))] internal void ReadClut16(byte[] data, IccClut expected, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccClut output = reader.ReadClut16(inChannelCount, outChannelCount, gridPointCount); @@ -45,7 +45,7 @@ internal void ReadClut16(byte[] data, IccClut expected, int inChannelCount, int [MemberData(nameof(IccTestDataLut.ClutF32TestData), MemberType = typeof(IccTestDataLut))] internal void ReadClutF32(byte[] data, IccClut expected, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccClut output = reader.ReadClutF32(inChannelCount, outChannelCount, gridPointCount); @@ -56,7 +56,7 @@ internal void ReadClutF32(byte[] data, IccClut expected, int inChannelCount, int [MemberData(nameof(IccTestDataLut.Lut8TestData), MemberType = typeof(IccTestDataLut))] internal void ReadLut8(byte[] data, IccLut expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccLut output = reader.ReadLut8(); @@ -67,7 +67,7 @@ internal void ReadLut8(byte[] data, IccLut expected) [MemberData(nameof(IccTestDataLut.Lut16TestData), MemberType = typeof(IccTestDataLut))] internal void ReadLut16(byte[] data, IccLut expected, int count) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccLut output = reader.ReadLut16(count); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MatrixTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMatrixTests.cs similarity index 86% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MatrixTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMatrixTests.cs index 7987e94102..8245d26e01 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MatrixTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMatrixTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataReaderMatrixTests [MemberData(nameof(IccTestDataMatrix.Matrix2D_FloatArrayTestData), MemberType = typeof(IccTestDataMatrix))] public void ReadMatrix2D(byte[] data, int xCount, int yCount, bool isSingle, float[,] expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float[,] output = reader.ReadMatrix(xCount, yCount, isSingle); @@ -23,7 +23,7 @@ public void ReadMatrix2D(byte[] data, int xCount, int yCount, bool isSingle, flo [MemberData(nameof(IccTestDataMatrix.Matrix1D_ArrayTestData), MemberType = typeof(IccTestDataMatrix))] public void ReadMatrix1D(byte[] data, int yCount, bool isSingle, float[] expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float[] output = reader.ReadMatrix(yCount, isSingle); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MultiProcessElementTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMultiProcessElementTests.cs similarity index 66% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MultiProcessElementTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMultiProcessElementTests.cs index f9e5428cd4..412d5fc073 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.MultiProcessElementTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderMultiProcessElementTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -9,10 +9,10 @@ namespace SixLabors.ImageSharp.Tests.Icc public class IccDataReaderMultiProcessElementTests { [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.MultiProcessElementTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.MultiProcessElementTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void ReadMultiProcessElement(byte[] data, IccMultiProcessElement expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccMultiProcessElement output = reader.ReadMultiProcessElement(); @@ -20,10 +20,10 @@ internal void ReadMultiProcessElement(byte[] data, IccMultiProcessElement expect } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.CurveSetTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.CurveSetTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void ReadCurveSetProcessElement(byte[] data, IccCurveSetProcessElement expected, int inChannelCount, int outChannelCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccCurveSetProcessElement output = reader.ReadCurveSetProcessElement(inChannelCount, outChannelCount); @@ -31,10 +31,10 @@ internal void ReadCurveSetProcessElement(byte[] data, IccCurveSetProcessElement } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.MatrixTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.MatrixTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void ReadMatrixProcessElement(byte[] data, IccMatrixProcessElement expected, int inChannelCount, int outChannelCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccMatrixProcessElement output = reader.ReadMatrixProcessElement(inChannelCount, outChannelCount); @@ -42,10 +42,10 @@ internal void ReadMatrixProcessElement(byte[] data, IccMatrixProcessElement expe } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.ClutTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.ClutTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void ReadClutProcessElement(byte[] data, IccClutProcessElement expected, int inChannelCount, int outChannelCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccClutProcessElement output = reader.ReadClutProcessElement(inChannelCount, outChannelCount); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.NonPrimitivesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderNonPrimitivesTests.cs similarity index 85% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.NonPrimitivesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderNonPrimitivesTests.cs index 6296390a0a..a050f38596 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.NonPrimitivesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderNonPrimitivesTests.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. using System; @@ -14,7 +14,7 @@ public class IccDataReaderNonPrimitivesTests [MemberData(nameof(IccTestDataNonPrimitives.DateTimeTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void ReadDateTime(byte[] data, DateTime expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); DateTime output = reader.ReadDateTime(); @@ -25,7 +25,7 @@ public void ReadDateTime(byte[] data, DateTime expected) [MemberData(nameof(IccTestDataNonPrimitives.VersionNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void ReadVersionNumber(byte[] data, IccVersion expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccVersion output = reader.ReadVersionNumber(); @@ -36,7 +36,7 @@ public void ReadVersionNumber(byte[] data, IccVersion expected) [MemberData(nameof(IccTestDataNonPrimitives.XyzNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void ReadXyzNumber(byte[] data, Vector3 expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); Vector3 output = reader.ReadXyzNumber(); @@ -47,7 +47,7 @@ public void ReadXyzNumber(byte[] data, Vector3 expected) [MemberData(nameof(IccTestDataNonPrimitives.ProfileIdTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadProfileId(byte[] data, IccProfileId expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccProfileId output = reader.ReadProfileId(); @@ -58,7 +58,7 @@ internal void ReadProfileId(byte[] data, IccProfileId expected) [MemberData(nameof(IccTestDataNonPrimitives.PositionNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadPositionNumber(byte[] data, IccPositionNumber expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccPositionNumber output = reader.ReadPositionNumber(); @@ -69,7 +69,7 @@ internal void ReadPositionNumber(byte[] data, IccPositionNumber expected) [MemberData(nameof(IccTestDataNonPrimitives.ResponseNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadResponseNumber(byte[] data, IccResponseNumber expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccResponseNumber output = reader.ReadResponseNumber(); @@ -80,7 +80,7 @@ internal void ReadResponseNumber(byte[] data, IccResponseNumber expected) [MemberData(nameof(IccTestDataNonPrimitives.NamedColorTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadNamedColor(byte[] data, IccNamedColor expected, uint coordinateCount) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccNamedColor output = reader.ReadNamedColor(coordinateCount); @@ -91,7 +91,7 @@ internal void ReadNamedColor(byte[] data, IccNamedColor expected, uint coordinat [MemberData(nameof(IccTestDataNonPrimitives.ProfileDescriptionReadTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadProfileDescription(byte[] data, IccProfileDescription expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccProfileDescription output = reader.ReadProfileDescription(); @@ -102,7 +102,7 @@ internal void ReadProfileDescription(byte[] data, IccProfileDescription expected [MemberData(nameof(IccTestDataNonPrimitives.ColorantTableEntryTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadColorantTableEntry(byte[] data, IccColorantTableEntry expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccColorantTableEntry output = reader.ReadColorantTableEntry(); @@ -113,7 +113,7 @@ internal void ReadColorantTableEntry(byte[] data, IccColorantTableEntry expected [MemberData(nameof(IccTestDataNonPrimitives.ScreeningChannelTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void ReadScreeningChannel(byte[] data, IccScreeningChannel expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); IccScreeningChannel output = reader.ReadScreeningChannel(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.PrimitivesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderPrimitivesTests.cs similarity index 82% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.PrimitivesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderPrimitivesTests.cs index 0275303291..bd9eb1ea8d 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.PrimitivesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderPrimitivesTests.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. using System; @@ -13,7 +13,7 @@ public class IccDataReaderPrimitivesTests [MemberData(nameof(IccTestDataPrimitives.AsciiTestData), MemberType = typeof(IccTestDataPrimitives))] public void ReadAsciiString(byte[] textBytes, int length, string expected) { - IccDataReader reader = CreateReader(textBytes); + IccDataReader reader = this.CreateReader(textBytes); string output = reader.ReadAsciiString(length); @@ -23,7 +23,7 @@ public void ReadAsciiString(byte[] textBytes, int length, string expected) [Fact] public void ReadAsciiStringWithNegativeLengthThrowsArgumentException() { - IccDataReader reader = CreateReader(new byte[4]); + IccDataReader reader = this.CreateReader(new byte[4]); Assert.Throws(() => reader.ReadAsciiString(-1)); } @@ -31,7 +31,7 @@ public void ReadAsciiStringWithNegativeLengthThrowsArgumentException() [Fact] public void ReadUnicodeStringWithNegativeLengthThrowsArgumentException() { - IccDataReader reader = CreateReader(new byte[4]); + IccDataReader reader = this.CreateReader(new byte[4]); Assert.Throws(() => reader.ReadUnicodeString(-1)); } @@ -40,7 +40,7 @@ public void ReadUnicodeStringWithNegativeLengthThrowsArgumentException() [MemberData(nameof(IccTestDataPrimitives.Fix16TestData), MemberType = typeof(IccTestDataPrimitives))] public void ReadFix16(byte[] data, float expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float output = reader.ReadFix16(); @@ -51,7 +51,7 @@ public void ReadFix16(byte[] data, float expected) [MemberData(nameof(IccTestDataPrimitives.UFix16TestData), MemberType = typeof(IccTestDataPrimitives))] public void ReadUFix16(byte[] data, float expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float output = reader.ReadUFix16(); @@ -62,7 +62,7 @@ public void ReadUFix16(byte[] data, float expected) [MemberData(nameof(IccTestDataPrimitives.U1Fix15TestData), MemberType = typeof(IccTestDataPrimitives))] public void ReadU1Fix15(byte[] data, float expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float output = reader.ReadU1Fix15(); @@ -73,7 +73,7 @@ public void ReadU1Fix15(byte[] data, float expected) [MemberData(nameof(IccTestDataPrimitives.UFix8TestData), MemberType = typeof(IccTestDataPrimitives))] public void ReadUFix8(byte[] data, float expected) { - IccDataReader reader = CreateReader(data); + IccDataReader reader = this.CreateReader(data); float output = reader.ReadUFix8(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntryTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderTagDataEntryTests.cs similarity index 99% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntryTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderTagDataEntryTests.cs index dc2c5b6acc..a18fb1ab88 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntryTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataReader/IccDataReaderTagDataEntryTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.CurvesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterCurvesTests.cs similarity index 87% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.CurvesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterCurvesTests.cs index 585bda648b..39ebf33749 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.CurvesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterCurvesTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataWriterCurvesTests [MemberData(nameof(IccTestDataCurves.OneDimensionalCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteOneDimensionalCurve(byte[] expected, IccOneDimensionalCurve data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteOneDimensionalCurve(data); byte[] output = writer.GetData(); @@ -24,7 +24,7 @@ internal void WriteOneDimensionalCurve(byte[] expected, IccOneDimensionalCurve d [MemberData(nameof(IccTestDataCurves.ResponseCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteResponseCurve(byte[] expected, IccResponseCurve data, int channelCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteResponseCurve(data); byte[] output = writer.GetData(); @@ -36,7 +36,7 @@ internal void WriteResponseCurve(byte[] expected, IccResponseCurve data, int cha [MemberData(nameof(IccTestDataCurves.ParametricCurveTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteParametricCurve(byte[] expected, IccParametricCurve data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteParametricCurve(data); byte[] output = writer.GetData(); @@ -48,7 +48,7 @@ internal void WriteParametricCurve(byte[] expected, IccParametricCurve data) [MemberData(nameof(IccTestDataCurves.CurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteCurveSegment(byte[] expected, IccCurveSegment data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteCurveSegment(data); byte[] output = writer.GetData(); @@ -60,7 +60,7 @@ internal void WriteCurveSegment(byte[] expected, IccCurveSegment data) [MemberData(nameof(IccTestDataCurves.FormulaCurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteFormulaCurveElement(byte[] expected, IccFormulaCurveElement data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteFormulaCurveElement(data); byte[] output = writer.GetData(); @@ -72,7 +72,7 @@ internal void WriteFormulaCurveElement(byte[] expected, IccFormulaCurveElement d [MemberData(nameof(IccTestDataCurves.SampledCurveSegmentTestData), MemberType = typeof(IccTestDataCurves))] internal void WriteSampledCurveElement(byte[] expected, IccSampledCurveElement data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteSampledCurveElement(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.LutTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests.cs similarity index 86% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.LutTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests.cs index 621673ce42..6245d8bb6e 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.LutTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataWriterLutTests [MemberData(nameof(IccTestDataLut.ClutTestData), MemberType = typeof(IccTestDataLut))] internal void WriteClutAll(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, bool isFloat) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteClut(data); byte[] output = writer.GetData(); @@ -24,7 +24,7 @@ internal void WriteClutAll(byte[] expected, IccClut data, int inChannelCount, in [MemberData(nameof(IccTestDataLut.Clut8TestData), MemberType = typeof(IccTestDataLut))] internal void WriteClut8(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteClut8(data); byte[] output = writer.GetData(); @@ -36,7 +36,7 @@ internal void WriteClut8(byte[] expected, IccClut data, int inChannelCount, int [MemberData(nameof(IccTestDataLut.Clut16TestData), MemberType = typeof(IccTestDataLut))] internal void WriteClut16(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteClut16(data); byte[] output = writer.GetData(); @@ -48,7 +48,7 @@ internal void WriteClut16(byte[] expected, IccClut data, int inChannelCount, int [MemberData(nameof(IccTestDataLut.ClutF32TestData), MemberType = typeof(IccTestDataLut))] internal void WriteClutF32(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteClutF32(data); byte[] output = writer.GetData(); @@ -60,7 +60,7 @@ internal void WriteClutF32(byte[] expected, IccClut data, int inChannelCount, in [MemberData(nameof(IccTestDataLut.Lut8TestData), MemberType = typeof(IccTestDataLut))] internal void WriteLut8(byte[] expected, IccLut data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLut8(data); byte[] output = writer.GetData(); @@ -72,7 +72,7 @@ internal void WriteLut8(byte[] expected, IccLut data) [MemberData(nameof(IccTestDataLut.Lut16TestData), MemberType = typeof(IccTestDataLut))] internal void WriteLut16(byte[] expected, IccLut data, int count) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLut16(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests1.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests1.cs new file mode 100644 index 0000000000..15cd27b94f --- /dev/null +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests1.cs @@ -0,0 +1,88 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.Metadata.Profiles.Icc; +using Xunit; + +namespace SixLabors.ImageSharp.Tests.Icc +{ + public class IccDataWriterLutTests1 + { + [Theory] + [MemberData(nameof(IccTestDataLut.ClutTestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClutAll(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, bool isFloat) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Clut8TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClut8(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut8(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Clut16TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClut16(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut16(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.ClutF32TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClutF32(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClutF32(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Lut8TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteLut8(byte[] expected, IccLut data) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteLut8(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Lut16TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteLut16(byte[] expected, IccLut data, int count) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteLut16(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + private IccDataWriter CreateWriter() + { + return new IccDataWriter(); + } + } +} diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests2.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests2.cs new file mode 100644 index 0000000000..7c301c754c --- /dev/null +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterLutTests2.cs @@ -0,0 +1,88 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.Metadata.Profiles.Icc; +using Xunit; + +namespace SixLabors.ImageSharp.Tests.Icc +{ + public class IccDataWriterLutTests2 + { + [Theory] + [MemberData(nameof(IccTestDataLut.ClutTestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClutAll(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, bool isFloat) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Clut8TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClut8(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut8(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Clut16TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClut16(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClut16(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.ClutF32TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteClutF32(byte[] expected, IccClut data, int inChannelCount, int outChannelCount, byte[] gridPointCount) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteClutF32(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Lut8TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteLut8(byte[] expected, IccLut data) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteLut8(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + [Theory] + [MemberData(nameof(IccTestDataLut.Lut16TestData), MemberType = typeof(IccTestDataLut))] + internal void WriteLut16(byte[] expected, IccLut data, int count) + { + IccDataWriter writer = this.CreateWriter(); + + writer.WriteLut16(data); + byte[] output = writer.GetData(); + + Assert.Equal(expected, output); + } + + private IccDataWriter CreateWriter() + { + return new IccDataWriter(); + } + } +} diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MatrixTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMatrixTests.cs similarity index 88% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MatrixTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMatrixTests.cs index 15bf762e25..f7f8df9fbc 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MatrixTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMatrixTests.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. using System.Numerics; @@ -16,7 +16,7 @@ public class IccDataWriterMatrixTests [MemberData(nameof(IccTestDataMatrix.Matrix2D_FloatArrayTestData), MemberType = typeof(IccTestDataMatrix))] public void WriteMatrix2D_Array(byte[] expected, int xCount, int yCount, bool isSingle, float[,] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrix(data, isSingle); byte[] output = writer.GetData(); @@ -28,7 +28,7 @@ public void WriteMatrix2D_Array(byte[] expected, int xCount, int yCount, bool is [MemberData(nameof(IccTestDataMatrix.Matrix2D_Matrix4x4TestData), MemberType = typeof(IccTestDataMatrix))] public void WriteMatrix2D_Matrix4x4(byte[] expected, int xCount, int yCount, bool isSingle, Matrix4x4 data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrix(data, isSingle); byte[] output = writer.GetData(); @@ -40,7 +40,7 @@ public void WriteMatrix2D_Matrix4x4(byte[] expected, int xCount, int yCount, boo [MemberData(nameof(IccTestDataMatrix.Matrix2D_DenseMatrixTestData), MemberType = typeof(IccTestDataMatrix))] internal void WriteMatrix2D_DenseMatrix(byte[] expected, int xCount, int yCount, bool isSingle, in DenseMatrix data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrix(data, isSingle); byte[] output = writer.GetData(); @@ -52,7 +52,7 @@ internal void WriteMatrix2D_DenseMatrix(byte[] expected, int xCount, int yCount, [MemberData(nameof(IccTestDataMatrix.Matrix1D_ArrayTestData), MemberType = typeof(IccTestDataMatrix))] public void WriteMatrix1D_Array(byte[] expected, int yCount, bool isSingle, float[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrix(data, isSingle); byte[] output = writer.GetData(); @@ -64,7 +64,7 @@ public void WriteMatrix1D_Array(byte[] expected, int yCount, bool isSingle, floa [MemberData(nameof(IccTestDataMatrix.Matrix1D_Vector3TestData), MemberType = typeof(IccTestDataMatrix))] public void WriteMatrix1D_Vector3(byte[] expected, int yCount, bool isSingle, Vector3 data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrix(data, isSingle); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MultiProcessElementTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMultiProcessElementTests.cs similarity index 66% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MultiProcessElementTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMultiProcessElementTests.cs index 829b556afb..2888958b07 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.MultiProcessElementTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterMultiProcessElementTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -9,10 +9,10 @@ namespace SixLabors.ImageSharp.Tests.Icc public class IccDataWriterMultiProcessElementTests { [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.MultiProcessElementTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.MultiProcessElementTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void WriteMultiProcessElement(byte[] expected, IccMultiProcessElement data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMultiProcessElement(data); byte[] output = writer.GetData(); @@ -21,10 +21,10 @@ internal void WriteMultiProcessElement(byte[] expected, IccMultiProcessElement d } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.CurveSetTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.CurveSetTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void WriteCurveSetProcessElement(byte[] expected, IccCurveSetProcessElement data, int inChannelCount, int outChannelCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteCurveSetProcessElement(data); byte[] output = writer.GetData(); @@ -33,10 +33,10 @@ internal void WriteCurveSetProcessElement(byte[] expected, IccCurveSetProcessEle } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.MatrixTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.MatrixTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void WriteMatrixProcessElement(byte[] expected, IccMatrixProcessElement data, int inChannelCount, int outChannelCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMatrixProcessElement(data); byte[] output = writer.GetData(); @@ -45,10 +45,10 @@ internal void WriteMatrixProcessElement(byte[] expected, IccMatrixProcessElement } [Theory] - [MemberData(nameof(IccTestDataMultiProcessElement.ClutTestData), MemberType = typeof(IccTestDataMultiProcessElement))] + [MemberData(nameof(IccTestDataMultiProcessElements.ClutTestData), MemberType = typeof(IccTestDataMultiProcessElements))] internal void WriteClutProcessElement(byte[] expected, IccClutProcessElement data, int inChannelCount, int outChannelCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteClutProcessElement(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.NonPrimitivesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterNonPrimitivesTests.cs similarity index 87% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.NonPrimitivesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterNonPrimitivesTests.cs index ed8a10551e..c88ea3a953 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.NonPrimitivesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterNonPrimitivesTests.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. using System; @@ -14,7 +14,7 @@ public class IccDataWriterNonPrimitivesTests [MemberData(nameof(IccTestDataNonPrimitives.DateTimeTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void WriteDateTime(byte[] expected, DateTime data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteDateTime(data); byte[] output = writer.GetData(); @@ -26,7 +26,7 @@ public void WriteDateTime(byte[] expected, DateTime data) [MemberData(nameof(IccTestDataNonPrimitives.VersionNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void WriteVersionNumber(byte[] expected, IccVersion data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteVersionNumber(data); byte[] output = writer.GetData(); @@ -38,7 +38,7 @@ public void WriteVersionNumber(byte[] expected, IccVersion data) [MemberData(nameof(IccTestDataNonPrimitives.XyzNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] public void WriteXyzNumber(byte[] expected, Vector3 data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteXyzNumber(data); byte[] output = writer.GetData(); @@ -50,7 +50,7 @@ public void WriteXyzNumber(byte[] expected, Vector3 data) [MemberData(nameof(IccTestDataNonPrimitives.ProfileIdTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WriteProfileId(byte[] expected, IccProfileId data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteProfileId(data); byte[] output = writer.GetData(); @@ -62,7 +62,7 @@ internal void WriteProfileId(byte[] expected, IccProfileId data) [MemberData(nameof(IccTestDataNonPrimitives.PositionNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WritePositionNumber(byte[] expected, IccPositionNumber data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WritePositionNumber(data); byte[] output = writer.GetData(); @@ -74,7 +74,7 @@ internal void WritePositionNumber(byte[] expected, IccPositionNumber data) [MemberData(nameof(IccTestDataNonPrimitives.ResponseNumberTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WriteResponseNumber(byte[] expected, IccResponseNumber data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteResponseNumber(data); byte[] output = writer.GetData(); @@ -86,7 +86,7 @@ internal void WriteResponseNumber(byte[] expected, IccResponseNumber data) [MemberData(nameof(IccTestDataNonPrimitives.NamedColorTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WriteNamedColor(byte[] expected, IccNamedColor data, uint coordinateCount) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteNamedColor(data); byte[] output = writer.GetData(); @@ -98,7 +98,7 @@ internal void WriteNamedColor(byte[] expected, IccNamedColor data, uint coordina [MemberData(nameof(IccTestDataNonPrimitives.ProfileDescriptionWriteTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WriteProfileDescription(byte[] expected, IccProfileDescription data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteProfileDescription(data); byte[] output = writer.GetData(); @@ -110,7 +110,7 @@ internal void WriteProfileDescription(byte[] expected, IccProfileDescription dat [MemberData(nameof(IccTestDataNonPrimitives.ScreeningChannelTestData), MemberType = typeof(IccTestDataNonPrimitives))] internal void WriteScreeningChannel(byte[] expected, IccScreeningChannel data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteScreeningChannel(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.PrimitivesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterPrimitivesTests.cs similarity index 86% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.PrimitivesTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterPrimitivesTests.cs index 464a701411..20e4a71419 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.PrimitivesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterPrimitivesTests.cs @@ -13,7 +13,7 @@ public class IccDataWriterPrimitivesTests [MemberData(nameof(IccTestDataPrimitives.AsciiWriteTestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteAsciiString(byte[] expected, string data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteAsciiString(data); byte[] output = writer.GetData(); @@ -25,7 +25,7 @@ public void WriteAsciiString(byte[] expected, string data) [MemberData(nameof(IccTestDataPrimitives.AsciiPaddingTestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteAsciiStringPadded(byte[] expected, int length, string data, bool ensureNullTerminator) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteAsciiString(data, length, ensureNullTerminator); byte[] output = writer.GetData(); @@ -36,7 +36,7 @@ public void WriteAsciiStringPadded(byte[] expected, int length, string data, boo [Fact] public void WriteAsciiStringWithNullWritesEmpty() { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); int count = writer.WriteAsciiString(null); byte[] output = writer.GetData(); @@ -48,7 +48,7 @@ public void WriteAsciiStringWithNullWritesEmpty() [Fact] public void WriteAsciiStringWithNegativeLengthThrowsArgumentException() { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); Assert.Throws(() => writer.WriteAsciiString("abcd", -1, false)); } @@ -56,7 +56,7 @@ public void WriteAsciiStringWithNegativeLengthThrowsArgumentException() [Fact] public void WriteUnicodeStringWithNullWritesEmpty() { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); int count = writer.WriteUnicodeString(null); byte[] output = writer.GetData(); @@ -69,7 +69,7 @@ public void WriteUnicodeStringWithNullWritesEmpty() [MemberData(nameof(IccTestDataPrimitives.Fix16TestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteFix16(byte[] expected, float data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteFix16(data); byte[] output = writer.GetData(); @@ -81,7 +81,7 @@ public void WriteFix16(byte[] expected, float data) [MemberData(nameof(IccTestDataPrimitives.UFix16TestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteUFix16(byte[] expected, float data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUFix16(data); byte[] output = writer.GetData(); @@ -93,7 +93,7 @@ public void WriteUFix16(byte[] expected, float data) [MemberData(nameof(IccTestDataPrimitives.U1Fix15TestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteU1Fix15(byte[] expected, float data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteU1Fix15(data); byte[] output = writer.GetData(); @@ -105,7 +105,7 @@ public void WriteU1Fix15(byte[] expected, float data) [MemberData(nameof(IccTestDataPrimitives.UFix8TestData), MemberType = typeof(IccTestDataPrimitives))] public void WriteUFix8(byte[] expected, float data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUFix8(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntryTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTagDataEntryTests.cs similarity index 88% rename from tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntryTests.cs rename to tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTagDataEntryTests.cs index 269a8d561b..85e11c8560 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntryTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTagDataEntryTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -12,7 +12,7 @@ public class IccDataWriterTagDataEntryTests [MemberData(nameof(IccTestDataTagDataEntry.UnknownTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUnknownTagDataEntry(byte[] expected, IccUnknownTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUnknownTagDataEntry(data); byte[] output = writer.GetData(); @@ -24,7 +24,7 @@ internal void WriteUnknownTagDataEntry(byte[] expected, IccUnknownTagDataEntry d [MemberData(nameof(IccTestDataTagDataEntry.ChromaticityTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteChromaticityTagDataEntry(byte[] expected, IccChromaticityTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteChromaticityTagDataEntry(data); byte[] output = writer.GetData(); @@ -36,7 +36,7 @@ internal void WriteChromaticityTagDataEntry(byte[] expected, IccChromaticityTagD [MemberData(nameof(IccTestDataTagDataEntry.ColorantOrderTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteColorantOrderTagDataEntry(byte[] expected, IccColorantOrderTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteColorantOrderTagDataEntry(data); byte[] output = writer.GetData(); @@ -48,7 +48,7 @@ internal void WriteColorantOrderTagDataEntry(byte[] expected, IccColorantOrderTa [MemberData(nameof(IccTestDataTagDataEntry.ColorantTableTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteColorantTableTagDataEntry(byte[] expected, IccColorantTableTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteColorantTableTagDataEntry(data); byte[] output = writer.GetData(); @@ -60,7 +60,7 @@ internal void WriteColorantTableTagDataEntry(byte[] expected, IccColorantTableTa [MemberData(nameof(IccTestDataTagDataEntry.CurveTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteCurveTagDataEntry(byte[] expected, IccCurveTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteCurveTagDataEntry(data); byte[] output = writer.GetData(); @@ -72,7 +72,7 @@ internal void WriteCurveTagDataEntry(byte[] expected, IccCurveTagDataEntry data) [MemberData(nameof(IccTestDataTagDataEntry.DataTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteDataTagDataEntry(byte[] expected, IccDataTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteDataTagDataEntry(data); byte[] output = writer.GetData(); @@ -84,7 +84,7 @@ internal void WriteDataTagDataEntry(byte[] expected, IccDataTagDataEntry data, u [MemberData(nameof(IccTestDataTagDataEntry.DateTimeTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteDateTimeTagDataEntry(byte[] expected, IccDateTimeTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteDateTimeTagDataEntry(data); byte[] output = writer.GetData(); @@ -96,7 +96,7 @@ internal void WriteDateTimeTagDataEntry(byte[] expected, IccDateTimeTagDataEntry [MemberData(nameof(IccTestDataTagDataEntry.Lut16TagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteLut16TagDataEntry(byte[] expected, IccLut16TagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLut16TagDataEntry(data); byte[] output = writer.GetData(); @@ -108,11 +108,11 @@ internal void WriteLut16TagDataEntry(byte[] expected, IccLut16TagDataEntry data) [MemberData(nameof(IccTestDataTagDataEntry.Lut8TagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteLut8TagDataEntry(byte[] expected, IccLut8TagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLut8TagDataEntry(data); byte[] output = writer.GetData(); - + Assert.Equal(expected, output); } @@ -120,7 +120,7 @@ internal void WriteLut8TagDataEntry(byte[] expected, IccLut8TagDataEntry data) [MemberData(nameof(IccTestDataTagDataEntry.LutAToBTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteLutAToBTagDataEntry(byte[] expected, IccLutAToBTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLutAtoBTagDataEntry(data); byte[] output = writer.GetData(); @@ -132,7 +132,7 @@ internal void WriteLutAToBTagDataEntry(byte[] expected, IccLutAToBTagDataEntry d [MemberData(nameof(IccTestDataTagDataEntry.LutBToATagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteLutBToATagDataEntry(byte[] expected, IccLutBToATagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteLutBtoATagDataEntry(data); byte[] output = writer.GetData(); @@ -144,7 +144,7 @@ internal void WriteLutBToATagDataEntry(byte[] expected, IccLutBToATagDataEntry d [MemberData(nameof(IccTestDataTagDataEntry.MeasurementTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteMeasurementTagDataEntry(byte[] expected, IccMeasurementTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMeasurementTagDataEntry(data); byte[] output = writer.GetData(); @@ -156,7 +156,7 @@ internal void WriteMeasurementTagDataEntry(byte[] expected, IccMeasurementTagDat [MemberData(nameof(IccTestDataTagDataEntry.MultiLocalizedUnicodeTagDataEntryTestData_Write), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteMultiLocalizedUnicodeTagDataEntry(byte[] expected, IccMultiLocalizedUnicodeTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMultiLocalizedUnicodeTagDataEntry(data); byte[] output = writer.GetData(); @@ -168,7 +168,7 @@ internal void WriteMultiLocalizedUnicodeTagDataEntry(byte[] expected, IccMultiLo [MemberData(nameof(IccTestDataTagDataEntry.MultiProcessElementsTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteMultiProcessElementsTagDataEntry(byte[] expected, IccMultiProcessElementsTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteMultiProcessElementsTagDataEntry(data); byte[] output = writer.GetData(); @@ -180,7 +180,7 @@ internal void WriteMultiProcessElementsTagDataEntry(byte[] expected, IccMultiPro [MemberData(nameof(IccTestDataTagDataEntry.NamedColor2TagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteNamedColor2TagDataEntry(byte[] expected, IccNamedColor2TagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteNamedColor2TagDataEntry(data); byte[] output = writer.GetData(); @@ -192,7 +192,7 @@ internal void WriteNamedColor2TagDataEntry(byte[] expected, IccNamedColor2TagDat [MemberData(nameof(IccTestDataTagDataEntry.ParametricCurveTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteParametricCurveTagDataEntry(byte[] expected, IccParametricCurveTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteParametricCurveTagDataEntry(data); byte[] output = writer.GetData(); @@ -204,7 +204,7 @@ internal void WriteParametricCurveTagDataEntry(byte[] expected, IccParametricCur [MemberData(nameof(IccTestDataTagDataEntry.ProfileSequenceDescTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteProfileSequenceDescTagDataEntry(byte[] expected, IccProfileSequenceDescTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteProfileSequenceDescTagDataEntry(data); byte[] output = writer.GetData(); @@ -216,7 +216,7 @@ internal void WriteProfileSequenceDescTagDataEntry(byte[] expected, IccProfileSe [MemberData(nameof(IccTestDataTagDataEntry.ProfileSequenceIdentifierTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteProfileSequenceIdentifierTagDataEntry(byte[] expected, IccProfileSequenceIdentifierTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteProfileSequenceIdentifierTagDataEntry(data); byte[] output = writer.GetData(); @@ -228,7 +228,7 @@ internal void WriteProfileSequenceIdentifierTagDataEntry(byte[] expected, IccPro [MemberData(nameof(IccTestDataTagDataEntry.ResponseCurveSet16TagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteResponseCurveSet16TagDataEntry(byte[] expected, IccResponseCurveSet16TagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteResponseCurveSet16TagDataEntry(data); byte[] output = writer.GetData(); @@ -240,7 +240,7 @@ internal void WriteResponseCurveSet16TagDataEntry(byte[] expected, IccResponseCu [MemberData(nameof(IccTestDataTagDataEntry.Fix16ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteFix16ArrayTagDataEntry(byte[] expected, IccFix16ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteFix16ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -252,7 +252,7 @@ internal void WriteFix16ArrayTagDataEntry(byte[] expected, IccFix16ArrayTagDataE [MemberData(nameof(IccTestDataTagDataEntry.SignatureTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteSignatureTagDataEntry(byte[] expected, IccSignatureTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteSignatureTagDataEntry(data); byte[] output = writer.GetData(); @@ -264,7 +264,7 @@ internal void WriteSignatureTagDataEntry(byte[] expected, IccSignatureTagDataEnt [MemberData(nameof(IccTestDataTagDataEntry.TextTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteTextTagDataEntry(byte[] expected, IccTextTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteTextTagDataEntry(data); byte[] output = writer.GetData(); @@ -276,7 +276,7 @@ internal void WriteTextTagDataEntry(byte[] expected, IccTextTagDataEntry data, u [MemberData(nameof(IccTestDataTagDataEntry.UFix16ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUFix16ArrayTagDataEntry(byte[] expected, IccUFix16ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUFix16ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -288,7 +288,7 @@ internal void WriteUFix16ArrayTagDataEntry(byte[] expected, IccUFix16ArrayTagDat [MemberData(nameof(IccTestDataTagDataEntry.UInt16ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUInt16ArrayTagDataEntry(byte[] expected, IccUInt16ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUInt16ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -300,7 +300,7 @@ internal void WriteUInt16ArrayTagDataEntry(byte[] expected, IccUInt16ArrayTagDat [MemberData(nameof(IccTestDataTagDataEntry.UInt32ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUInt32ArrayTagDataEntry(byte[] expected, IccUInt32ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUInt32ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -312,7 +312,7 @@ internal void WriteUInt32ArrayTagDataEntry(byte[] expected, IccUInt32ArrayTagDat [MemberData(nameof(IccTestDataTagDataEntry.UInt64ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUInt64ArrayTagDataEntry(byte[] expected, IccUInt64ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUInt64ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -324,7 +324,7 @@ internal void WriteUInt64ArrayTagDataEntry(byte[] expected, IccUInt64ArrayTagDat [MemberData(nameof(IccTestDataTagDataEntry.UInt8ArrayTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUInt8ArrayTagDataEntry(byte[] expected, IccUInt8ArrayTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUInt8ArrayTagDataEntry(data); byte[] output = writer.GetData(); @@ -336,7 +336,7 @@ internal void WriteUInt8ArrayTagDataEntry(byte[] expected, IccUInt8ArrayTagDataE [MemberData(nameof(IccTestDataTagDataEntry.ViewingConditionsTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteViewingConditionsTagDataEntry(byte[] expected, IccViewingConditionsTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteViewingConditionsTagDataEntry(data); byte[] output = writer.GetData(); @@ -348,7 +348,7 @@ internal void WriteViewingConditionsTagDataEntry(byte[] expected, IccViewingCond [MemberData(nameof(IccTestDataTagDataEntry.XYZTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteXyzTagDataEntry(byte[] expected, IccXyzTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteXyzTagDataEntry(data); byte[] output = writer.GetData(); @@ -360,7 +360,7 @@ internal void WriteXyzTagDataEntry(byte[] expected, IccXyzTagDataEntry data, uin [MemberData(nameof(IccTestDataTagDataEntry.TextDescriptionTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteTextDescriptionTagDataEntry(byte[] expected, IccTextDescriptionTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteTextDescriptionTagDataEntry(data); byte[] output = writer.GetData(); @@ -372,7 +372,7 @@ internal void WriteTextDescriptionTagDataEntry(byte[] expected, IccTextDescripti [MemberData(nameof(IccTestDataTagDataEntry.CrdInfoTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteCrdInfoTagDataEntry(byte[] expected, IccCrdInfoTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteCrdInfoTagDataEntry(data); byte[] output = writer.GetData(); @@ -384,7 +384,7 @@ internal void WriteCrdInfoTagDataEntry(byte[] expected, IccCrdInfoTagDataEntry d [MemberData(nameof(IccTestDataTagDataEntry.ScreeningTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteScreeningTagDataEntry(byte[] expected, IccScreeningTagDataEntry data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteScreeningTagDataEntry(data); byte[] output = writer.GetData(); @@ -396,7 +396,7 @@ internal void WriteScreeningTagDataEntry(byte[] expected, IccScreeningTagDataEnt [MemberData(nameof(IccTestDataTagDataEntry.UcrBgTagDataEntryTestData), MemberType = typeof(IccTestDataTagDataEntry))] internal void WriteUcrBgTagDataEntry(byte[] expected, IccUcrBgTagDataEntry data, uint size) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteUcrBgTagDataEntry(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTests.cs index b7b446699c..7249e03aa1 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/DataWriter/IccDataWriterTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -11,7 +11,7 @@ public class IccDataWriterTests [Fact] public void WriteEmpty() { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteEmpty(4); byte[] output = writer.GetData(); @@ -24,7 +24,7 @@ public void WriteEmpty() [InlineData(4, 4)] public void WritePadding(int writePosition, int expectedLength) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteEmpty(writePosition); writer.WritePadding(); @@ -37,7 +37,7 @@ public void WritePadding(int writePosition, int expectedLength) [MemberData(nameof(IccTestDataArray.UInt8TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayUInt8(byte[] data, byte[] expected) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); @@ -49,7 +49,7 @@ public void WriteArrayUInt8(byte[] data, byte[] expected) [MemberData(nameof(IccTestDataArray.UInt16TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayUInt16(byte[] expected, ushort[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); @@ -61,7 +61,7 @@ public void WriteArrayUInt16(byte[] expected, ushort[] data) [MemberData(nameof(IccTestDataArray.Int16TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayInt16(byte[] expected, short[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); @@ -73,7 +73,7 @@ public void WriteArrayInt16(byte[] expected, short[] data) [MemberData(nameof(IccTestDataArray.UInt32TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayUInt32(byte[] expected, uint[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); @@ -85,7 +85,7 @@ public void WriteArrayUInt32(byte[] expected, uint[] data) [MemberData(nameof(IccTestDataArray.Int32TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayInt32(byte[] expected, int[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); @@ -97,7 +97,7 @@ public void WriteArrayInt32(byte[] expected, int[] data) [MemberData(nameof(IccTestDataArray.UInt64TestData), MemberType = typeof(IccTestDataArray))] public void WriteArrayUInt64(byte[] expected, ulong[] data) { - IccDataWriter writer = CreateWriter(); + IccDataWriter writer = this.CreateWriter(); writer.WriteArray(data); byte[] output = writer.GetData(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs index b4ed52a3d9..1502b8b30e 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -11,7 +11,7 @@ public class IccReaderTests [Fact] public void ReadProfile_NoEntries() { - IccReader reader = CreateReader(); + IccReader reader = this.CreateReader(); IccProfile output = reader.Read(IccTestDataProfiles.Header_Random_Array); @@ -42,7 +42,7 @@ public void ReadProfile_NoEntries() [Fact] public void ReadProfile_DuplicateEntry() { - IccReader reader = CreateReader(); + IccReader reader = this.CreateReader(); IccProfile output = reader.Read(IccTestDataProfiles.Profile_Random_Array); @@ -50,7 +50,6 @@ public void ReadProfile_DuplicateEntry() Assert.True(ReferenceEquals(output.Entries[0], output.Entries[1])); } - private IccReader CreateReader() { return new IccReader(); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs index e66554b85b..c4ac921b10 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs @@ -11,7 +11,7 @@ public class IccWriterTests [Fact] public void WriteProfile_NoEntries() { - IccWriter writer = CreateWriter(); + IccWriter writer = this.CreateWriter(); var profile = new IccProfile { @@ -25,7 +25,7 @@ public void WriteProfile_NoEntries() [Fact] public void WriteProfile_DuplicateEntry() { - IccWriter writer = CreateWriter(); + IccWriter writer = this.CreateWriter(); byte[] output = writer.Write(IccTestDataProfiles.Profile_Random_Val); diff --git a/tests/ImageSharp.Tests/PixelFormats/Argb32Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Argb32Tests.cs index 1ccf485fe0..74b9ef1c80 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Argb32Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Argb32Tests.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. using System; @@ -75,7 +75,7 @@ public void ConstructorAssignsProperties() public void Argb32_PackedValue() { Assert.Equal(0x80001a00u, new Argb32(+0.1f, -0.3f, +0.5f, -0.7f).PackedValue); - Assert.Equal((uint)0x0, new Argb32(Vector4.Zero).PackedValue); + Assert.Equal(0x0U, new Argb32(Vector4.Zero).PackedValue); Assert.Equal(0xFFFFFFFF, new Argb32(Vector4.One).PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/Bgr24Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Bgr24Tests.cs index 7638c5f862..1723497390 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Bgr24Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Bgr24Tests.cs @@ -14,7 +14,7 @@ public void AreEqual() { var color1 = new Bgr24(byte.MaxValue, 0, byte.MaxValue); var color2 = new Bgr24(byte.MaxValue, 0, byte.MaxValue); - + Assert.Equal(color1, color2); } @@ -77,7 +77,6 @@ public void Equals_WhenFalse(byte r1, byte g1, byte b1, byte r2, byte g2, byte b Assert.False(a.Equals((object)b)); } - [Fact] public void FromRgba32() { diff --git a/tests/ImageSharp.Tests/PixelFormats/Bgr565Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Bgr565Tests.cs index 3043626cab..4dbd00cbbb 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Bgr565Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Bgr565Tests.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. using System.Numerics; @@ -45,6 +45,7 @@ public void Bgr565_PackedValue() Assert.Equal(6160, new Bgr565(0.1F, -0.3F, 0.5F).PackedValue); Assert.Equal(0x0, new Bgr565(Vector3.Zero).PackedValue); Assert.Equal(0xFFFF, new Bgr565(Vector3.One).PackedValue); + // Make sure the swizzle is correct. Assert.Equal(0xF800, new Bgr565(Vector3.UnitX).PackedValue); Assert.Equal(0x07E0, new Bgr565(Vector3.UnitY).PackedValue); @@ -191,10 +192,10 @@ public void Bgr565_FromBgr24() // arrange var bgr = default(Bgr565); ushort expected = ushort.MaxValue; - + // act bgr.FromBgr24(new Bgr24(byte.MaxValue, byte.MaxValue, byte.MaxValue)); - + // assert Assert.Equal(expected, bgr.PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/Bgra32Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Bgra32Tests.cs index 28c022709f..6ee14c0159 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Bgra32Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Bgra32Tests.cs @@ -17,7 +17,7 @@ public void AreEqual() { var color1 = new Bgra32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); var color2 = new Bgra32(byte.MaxValue, byte.MaxValue, byte.MaxValue); - + Assert.Equal(color1, color2); } @@ -89,7 +89,6 @@ public void Equality_WhenFalse(byte b1, byte g1, byte r1, byte a1, byte b2, byte Assert.False(x.Equals((object)y)); } - [Fact] public void FromRgba32() { diff --git a/tests/ImageSharp.Tests/PixelFormats/Bgra5551Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Bgra5551Tests.cs index 41ebfc9550..e36d54b52e 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Bgra5551Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Bgra5551Tests.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. using System.Numerics; @@ -19,7 +19,7 @@ public void AreEqual() var color2 = new Bgra5551(new Vector4(0.0f)); var color3 = new Bgra5551(new Vector4(1.0f, 0.0f, 0.0f, 1.0f)); var color4 = new Bgra5551(1.0f, 0.0f, 0.0f, 1.0f); - + Assert.Equal(color1, color2); Assert.Equal(color3, color4); } @@ -73,7 +73,7 @@ public void Bgra5551_ToScaledVector4() // arrange var bgra = new Bgra5551(Vector4.One); - // act + // act Vector4 actual = bgra.ToScaledVector4(); // assert @@ -121,7 +121,7 @@ public void Bgra5551_FromBgra5551() var actual = default(Bgra5551); var expected = new Bgra5551(1.0f, 0.0f, 1.0f, 1.0f); - // act + // act bgra.FromBgra5551(expected); actual.FromBgra5551(bgra); @@ -171,10 +171,10 @@ public void Bgra5551_FromArgb32() // arrange var bgra = default(Bgra5551); ushort expectedPackedValue = ushort.MaxValue; - + // act bgra.FromArgb32(new Argb32(255, 255, 255, 255)); - + // assert Assert.Equal(expectedPackedValue, bgra.PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/Byte4Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Byte4Tests.cs index 2eb5553d7c..487adc2412 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Byte4Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Byte4Tests.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. using System.Numerics; @@ -42,9 +42,9 @@ public void AreNotEqual() [Fact] public void Byte4_PackedValue() { - Assert.Equal((uint)128, new Byte4(127.5f, -12.3f, 0.5f, -0.7f).PackedValue); - Assert.Equal((uint)0x1a7b362d, new Byte4(0x2d, 0x36, 0x7b, 0x1a).PackedValue); - Assert.Equal((uint)0x0, new Byte4(Vector4.Zero).PackedValue); + Assert.Equal(128U, new Byte4(127.5f, -12.3f, 0.5f, -0.7f).PackedValue); + Assert.Equal(0x1a7b362dU, new Byte4(0x2d, 0x36, 0x7b, 0x1a).PackedValue); + Assert.Equal(0x0U, new Byte4(Vector4.Zero).PackedValue); Assert.Equal(0xFFFFFFFF, new Byte4(Vector4.One * 255).PackedValue); } @@ -195,10 +195,10 @@ public void Byte4_FromRgba32() // arrange var byte4 = default(Byte4); uint expectedPackedValue1 = uint.MaxValue; - + // act byte4.FromRgba32(new Rgba32(255, 255, 255, 255)); - + // assert Assert.Equal(expectedPackedValue1, byte4.PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/HalfSingleTests.cs b/tests/ImageSharp.Tests/PixelFormats/HalfSingleTests.cs index 85a3b8b320..b1ae7fd139 100644 --- a/tests/ImageSharp.Tests/PixelFormats/HalfSingleTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/HalfSingleTests.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. using System.Numerics; @@ -41,7 +41,7 @@ public void HalfSingle_ToScaledVector4() // arrange var halfSingle = new HalfSingle(-1F); - // act + // act Vector4 actual = halfSingle.ToScaledVector4(); // assert @@ -54,7 +54,7 @@ public void HalfSingle_ToScaledVector4() [Fact] public void HalfSingle_FromScaledVector4() { - // arrange + // arrange Vector4 scaled = new HalfSingle(-1F).ToScaledVector4(); int expected = 48128; var halfSingle = default(HalfSingle); diff --git a/tests/ImageSharp.Tests/PixelFormats/HalfVector2Tests.cs b/tests/ImageSharp.Tests/PixelFormats/HalfVector2Tests.cs index 57da5438ca..1712a6e1ee 100644 --- a/tests/ImageSharp.Tests/PixelFormats/HalfVector2Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/HalfVector2Tests.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. using System.Numerics; @@ -77,7 +77,7 @@ public void HalfVector2_FromBgra5551() { // arrange var halfVector2 = default(HalfVector2); - + // act halfVector2.FromBgra5551(new Bgra5551(1.0f, 1.0f, 1.0f, 1.0f)); diff --git a/tests/ImageSharp.Tests/PixelFormats/HalfVector4Tests.cs b/tests/ImageSharp.Tests/PixelFormats/HalfVector4Tests.cs index ed1a0b7209..c529e1b51b 100644 --- a/tests/ImageSharp.Tests/PixelFormats/HalfVector4Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/HalfVector4Tests.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. using System.Numerics; @@ -40,7 +40,7 @@ public void HalfVector4_ToScaledVector4() // arrange var halfVector4 = new HalfVector4(-Vector4.One); - // act + // act Vector4 actual = halfVector4.ToScaledVector4(); // assert @@ -58,7 +58,7 @@ public void HalfVector4_FromScaledVector4() Vector4 scaled = new HalfVector4(-Vector4.One).ToScaledVector4(); ulong expected = 13547034390470638592uL; - // act + // act halfVector4.FromScaledVector4(scaled); ulong actual = halfVector4.PackedValue; diff --git a/tests/ImageSharp.Tests/PixelFormats/L8Tests.cs b/tests/ImageSharp.Tests/PixelFormats/L8Tests.cs index 13999ee3b2..f9bb084dee 100644 --- a/tests/ImageSharp.Tests/PixelFormats/L8Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/L8Tests.cs @@ -146,7 +146,6 @@ public void L8_FromRgba32(byte rgb) Assert.Equal(expected, actual); } - [Theory] [MemberData(nameof(LuminanceData))] public void L8_ToRgba32(byte luminance) @@ -199,7 +198,6 @@ public void L8_FromRgba32_IsInverseOf_ToRgba32(byte luminance) Assert.Equal(original, mirror); } - [Theory] [MemberData(nameof(LuminanceData))] public void Rgba32_ToL8_IsInverseOf_L8_ToRgba32(byte luminance) @@ -224,10 +222,10 @@ public void ToVector4_IsRgba32Compatible(byte luminance) Rgba32 rgba = default; original.ToRgba32(ref rgba); - var L8Vector = original.ToVector4(); + var l8Vector = original.ToVector4(); var rgbaVector = original.ToVector4(); - Assert.Equal(L8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); + Assert.Equal(l8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] @@ -239,7 +237,7 @@ public void FromVector4_IsRgba32Compatible(byte luminance) Rgba32 rgba = default; original.ToRgba32(ref rgba); - Vector4 rgbaVector = original.ToVector4(); + var rgbaVector = original.ToVector4(); L8 mirror = default; mirror.FromVector4(rgbaVector); @@ -256,10 +254,10 @@ public void ToScaledVector4_IsRgba32Compatible(byte luminance) Rgba32 rgba = default; original.ToRgba32(ref rgba); - Vector4 L8Vector = original.ToScaledVector4(); + Vector4 l8Vector = original.ToScaledVector4(); Vector4 rgbaVector = original.ToScaledVector4(); - Assert.Equal(L8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); + Assert.Equal(l8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] diff --git a/tests/ImageSharp.Tests/PixelFormats/La16Tests.cs b/tests/ImageSharp.Tests/PixelFormats/La16Tests.cs index 3663350067..3ad2dccdd2 100644 --- a/tests/ImageSharp.Tests/PixelFormats/La16Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/La16Tests.cs @@ -149,7 +149,6 @@ public void La16_FromRgba32(byte rgb) Assert.Equal(255, gray.A); } - [Theory] [MemberData(nameof(LuminanceData))] public void La16_ToRgba32(byte luminance) @@ -203,7 +202,6 @@ public void La16_FromRgba32_IsInverseOf_ToRgba32(byte luminance) Assert.Equal(original, mirror); } - [Theory] [MemberData(nameof(LuminanceData))] public void Rgba32_ToLa16_IsInverseOf_La16_ToRgba32(byte luminance) @@ -228,10 +226,10 @@ public void ToVector4_IsRgba32Compatible(byte luminance) Rgba32 rgba = default; original.ToRgba32(ref rgba); - var La16Vector = original.ToVector4(); + var la16Vector = original.ToVector4(); var rgbaVector = original.ToVector4(); - Assert.Equal(La16Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); + Assert.Equal(la16Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] @@ -260,10 +258,10 @@ public void ToScaledVector4_IsRgba32Compatible(byte luminance) Rgba32 rgba = default; original.ToRgba32(ref rgba); - Vector4 La16Vector = original.ToScaledVector4(); + Vector4 la16Vector = original.ToScaledVector4(); Vector4 rgbaVector = original.ToScaledVector4(); - Assert.Equal(La16Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); + Assert.Equal(la16Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] diff --git a/tests/ImageSharp.Tests/PixelFormats/NormalizedByte4Tests.cs b/tests/ImageSharp.Tests/PixelFormats/NormalizedByte4Tests.cs index 7f02493b47..0ab7033983 100644 --- a/tests/ImageSharp.Tests/PixelFormats/NormalizedByte4Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/NormalizedByte4Tests.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. using System.Numerics; @@ -43,9 +43,9 @@ public void AreNotEqual() public void NormalizedByte4_PackedValues() { Assert.Equal(0xA740DA0D, new NormalizedByte4(0.1f, -0.3f, 0.5f, -0.7f).PackedValue); - Assert.Equal((uint)958796544, new NormalizedByte4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); - Assert.Equal((uint)0x0, new NormalizedByte4(Vector4.Zero).PackedValue); - Assert.Equal((uint)0x7F7F7F7F, new NormalizedByte4(Vector4.One).PackedValue); + Assert.Equal(958796544U, new NormalizedByte4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); + Assert.Equal(0x0U, new NormalizedByte4(Vector4.Zero).PackedValue); + Assert.Equal(0x7F7F7F7FU, new NormalizedByte4(Vector4.One).PackedValue); Assert.Equal(0x81818181, new NormalizedByte4(-Vector4.One).PackedValue); } @@ -83,7 +83,7 @@ public void NormalizedByte4_FromScaledVector4() Vector4 scaled = new NormalizedByte4(-Vector4.One).ToScaledVector4(); uint expected = 0x81818181; - // act + // act pixel.FromScaledVector4(scaled); uint actual = pixel.PackedValue; diff --git a/tests/ImageSharp.Tests/PixelFormats/NormalizedShort2Tests.cs b/tests/ImageSharp.Tests/PixelFormats/NormalizedShort2Tests.cs index ff9350b701..a726cee4e6 100644 --- a/tests/ImageSharp.Tests/PixelFormats/NormalizedShort2Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/NormalizedShort2Tests.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. using System.Numerics; @@ -14,9 +14,10 @@ public void NormalizedShort2_PackedValue() { Assert.Equal(0xE6672CCC, new NormalizedShort2(0.35f, -0.2f).PackedValue); Assert.Equal(3650751693, new NormalizedShort2(0.1f, -0.3f).PackedValue); - Assert.Equal((uint)0x0, new NormalizedShort2(Vector2.Zero).PackedValue); - Assert.Equal((uint)0x7FFF7FFF, new NormalizedShort2(Vector2.One).PackedValue); + Assert.Equal(0x0U, new NormalizedShort2(Vector2.Zero).PackedValue); + Assert.Equal(0x7FFF7FFFU, new NormalizedShort2(Vector2.One).PackedValue); Assert.Equal(0x80018001, new NormalizedShort2(-Vector2.One).PackedValue); + // TODO: I don't think this can ever pass since the bytes are already truncated. // Assert.Equal(3650751693, n.PackedValue); } @@ -34,8 +35,8 @@ public void NormalizedShort2_ToVector2() [Fact] public void NormalizedShort2_ToVector4() { - Assert.Equal(new Vector4(1, 1, 0, 1), (new NormalizedShort2(Vector2.One)).ToVector4()); - Assert.Equal(new Vector4(0, 0, 0, 1), (new NormalizedShort2(Vector2.Zero)).ToVector4()); + Assert.Equal(new Vector4(1, 1, 0, 1), new NormalizedShort2(Vector2.One).ToVector4()); + Assert.Equal(new Vector4(0, 0, 0, 1), new NormalizedShort2(Vector2.Zero).ToVector4()); } [Fact] diff --git a/tests/ImageSharp.Tests/PixelFormats/NormalizedShort4Tests.cs b/tests/ImageSharp.Tests/PixelFormats/NormalizedShort4Tests.cs index 834bae685c..96334be02e 100644 --- a/tests/ImageSharp.Tests/PixelFormats/NormalizedShort4Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/NormalizedShort4Tests.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. using System.Numerics; @@ -43,9 +43,9 @@ public void AreNotEqual() public void NormalizedShort4_PackedValues() { Assert.Equal(0xa6674000d99a0ccd, new NormalizedShort4(0.1f, -0.3f, 0.5f, -0.7f).PackedValue); - Assert.Equal((ulong)4150390751449251866, new NormalizedShort4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); - Assert.Equal((ulong)0x0, new NormalizedShort4(Vector4.Zero).PackedValue); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, new NormalizedShort4(Vector4.One).PackedValue); + Assert.Equal(4150390751449251866UL, new NormalizedShort4(0.0008f, 0.15f, 0.30f, 0.45f).PackedValue); + Assert.Equal(0x0UL, new NormalizedShort4(Vector4.Zero).PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, new NormalizedShort4(Vector4.One).PackedValue); Assert.Equal(0x8001800180018001, new NormalizedShort4(-Vector4.One).PackedValue); } @@ -84,7 +84,7 @@ public void NormalizedShort4_FromScaledVector4() Vector4 scaled = new NormalizedShort4(Vector4.One).ToScaledVector4(); ulong expected = 0x7FFF7FFF7FFF7FFF; - // act + // act pixel.FromScaledVector4(scaled); ulong actual = pixel.PackedValue; diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperationsTests.Blender.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs similarity index 98% rename from tests/ImageSharp.Tests/PixelFormats/PixelOperationsTests.Blender.cs rename to tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs index 74360e8574..2a37ff8970 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperationsTests.Blender.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenderTests.cs @@ -22,8 +22,7 @@ public class PixelBlenderTests { new TestPixel(), typeof(DefaultPixelBlenders.LightenSrcOver), PixelColorBlendingMode.Lighten }, { new TestPixel(), typeof(DefaultPixelBlenders.AddSrcOver), PixelColorBlendingMode.Add }, { new TestPixel(), typeof(DefaultPixelBlenders.SubtractSrcOver), PixelColorBlendingMode.Subtract }, - { new TestPixel(), typeof(DefaultPixelBlenders.MultiplySrcOver), PixelColorBlendingMode.Multiply }, - + { new TestPixel(), typeof(DefaultPixelBlenders.MultiplySrcOver), PixelColorBlendingMode.Multiply }, { new TestPixel(), typeof(DefaultPixelBlenders.NormalSrcOver), PixelColorBlendingMode.Normal }, { new TestPixel(), typeof(DefaultPixelBlenders.ScreenSrcOver), PixelColorBlendingMode.Screen }, { new TestPixel(), typeof(DefaultPixelBlenders.HardLightSrcOver), PixelColorBlendingMode.HardLight }, @@ -33,7 +32,7 @@ public class PixelBlenderTests { new TestPixel(), typeof(DefaultPixelBlenders.AddSrcOver), PixelColorBlendingMode.Add }, { new TestPixel(), typeof(DefaultPixelBlenders.SubtractSrcOver), PixelColorBlendingMode.Subtract }, { new TestPixel(), typeof(DefaultPixelBlenders.MultiplySrcOver), PixelColorBlendingMode.Multiply }, - }; + }; [Theory] [MemberData(nameof(BlenderMappings))] @@ -55,7 +54,6 @@ public void ReturnsCorrectBlender(TestPixel pixel, Type type, Pi { Rgba32.MistyRose, Rgba32.MidnightBlue, 1, PixelColorBlendingMode.Add, new Rgba32(0xFFFFFDFF) }, { Rgba32.MistyRose, Rgba32.MidnightBlue, 1, PixelColorBlendingMode.Subtract, new Rgba32(0xFF71CBE6) }, { Rgba32.MistyRose, Rgba32.MidnightBlue, 1, PixelColorBlendingMode.Multiply, new Rgba32(0xFF631619) }, - }; [Theory] @@ -63,11 +61,9 @@ public void ReturnsCorrectBlender(TestPixel pixel, Type type, Pi public void TestColorBlendingModes(Rgba32 backdrop, Rgba32 source, float opacity, PixelColorBlendingMode mode, Rgba32 expectedResult) { PixelBlender blender = PixelOperations.Instance.GetPixelBlender(mode, PixelAlphaCompositionMode.SrcOver); - Rgba32 actualResult = blender.Blend(backdrop, source, opacity); // var str = actualResult.Rgba.ToString("X8"); // used to extract expectedResults - Assert.Equal(actualResult.ToVector4(), expectedResult.ToVector4()); } @@ -96,7 +92,6 @@ public void TestAlphaCompositionModes(Rgba32 backdrop, Rgba32 source, float opac Rgba32 actualResult = blender.Blend(backdrop, source, opacity); // var str = actualResult.Rgba.ToString("X8"); // used to extract expectedResults - Assert.Equal(actualResult.ToVector4(), expectedResult.ToVector4()); } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs index 693dd6bd81..a91ea09776 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs @@ -26,7 +26,7 @@ public class PorterDuffCompositorTests PixelAlphaCompositionMode.DestOut, PixelAlphaCompositionMode.Clear, PixelAlphaCompositionMode.Xor - }; + }; [Theory] [WithFile(TestImages.Png.PDDest, nameof(CompositingOperators), PixelTypes.Rgba32)] @@ -46,7 +46,10 @@ public void PorterDuffOutputIsCorrect(TestImageProvider provider, PixelA { string combinedMode = mode.ToString(); - if (combinedMode != "Src" && combinedMode.StartsWith("Src")) combinedMode = combinedMode.Substring(3); + if (combinedMode != "Src" && combinedMode.StartsWith("Src")) + { + combinedMode = combinedMode.Substring(3); + } res.DebugSave(provider, combinedMode); res.CompareToReferenceOutput(provider, combinedMode); diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests.cs index e397f70b08..7831dc1242 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests.cs @@ -10,9 +10,10 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelBlenders { public class PorterDuffFunctionsTests { - public static TheoryData NormalBlendFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(0.6f, 0.6f, 0.6f, 1) }, + public static TheoryData NormalBlendFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(0.6f, 0.6f, 0.6f, 1) } }; [Theory] @@ -23,15 +24,11 @@ public void NormalBlendFunction(TestVector4 back, TestVector4 source, float amou Assert.Equal(expected, actual); } - public static TheoryData MultiplyFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(0.6f, 0.6f, 0.6f, 1) }, - { - new TestVector4(0.9f,0.9f,0.9f,0.9f), - new TestVector4(0.4f,0.4f,0.4f,0.4f), - .5f, - new TestVector4(0.7834783f, 0.7834783f, 0.7834783f, 0.92f) - }, + public static TheoryData MultiplyFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(0.6f, 0.6f, 0.6f, 1) }, + { new TestVector4(0.9f, 0.9f, 0.9f, 0.9f), new TestVector4(0.4f, 0.4f, 0.4f, 0.4f), .5f, new TestVector4(0.7834783f, 0.7834783f, 0.7834783f, 0.92f) } }; [Theory] @@ -42,15 +39,11 @@ public void MultiplyFunction(TestVector4 back, TestVector4 source, float amount, VectorAssert.Equal(expected, actual, 5); } - public static TheoryData AddFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(.6f, .6f, .6f, 1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2075676f, .2075676f, .2075676f, .37f) - }, + public static TheoryData AddFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(.6f, .6f, .6f, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2075676f, .2075676f, .2075676f, .37f) } }; [Theory] @@ -61,15 +54,11 @@ public void AddFunction(TestVector4 back, TestVector4 source, float amount, Test VectorAssert.Equal(expected, actual, 5); } - public static TheoryData SubtractFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(0,0,0,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(1,1,1, 1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2027027f, .2027027f, .2027027f, .37f) - }, + public static TheoryData SubtractFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(0, 0, 0, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(1, 1, 1, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2027027f, .2027027f, .2027027f, .37f) } }; [Theory] @@ -80,15 +69,11 @@ public void SubtractFunction(TestVector4 back, TestVector4 source, float amount, VectorAssert.Equal(expected, actual, 5); } - public static TheoryData ScreenFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(1,1,1, 1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2383784f, .2383784f, .2383784f, .37f) - }, + public static TheoryData ScreenFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(1, 1, 1, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2383784f, .2383784f, .2383784f, .37f) } }; [Theory] @@ -99,15 +84,11 @@ public void ScreenFunction(TestVector4 back, TestVector4 source, float amount, T VectorAssert.Equal(expected, actual, 5); } - public static TheoryData DarkenFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(.6f,.6f,.6f, 1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2189189f, .2189189f, .2189189f, .37f) - }, + public static TheoryData DarkenFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(.6f, .6f, .6f, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2189189f, .2189189f, .2189189f, .37f) } }; [Theory] @@ -118,15 +99,11 @@ public void DarkenFunction(TestVector4 back, TestVector4 source, float amount, T VectorAssert.Equal(expected, actual, 5); } - public static TheoryData LightenFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(1,1,1,1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.227027f, .227027f, .227027f, .37f) - }, + public static TheoryData LightenFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(1, 1, 1, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.227027f, .227027f, .227027f, .37f) }, }; [Theory] @@ -137,15 +114,11 @@ public void LightenFunction(TestVector4 back, TestVector4 source, float amount, VectorAssert.Equal(expected, actual, 5); } - public static TheoryData OverlayFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(1,1,1,1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2124324f, .2124324f, .2124324f, .37f) - }, + public static TheoryData OverlayFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(1, 1, 1, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2124324f, .2124324f, .2124324f, .37f) }, }; [Theory] @@ -156,15 +129,11 @@ public void OverlayFunction(TestVector4 back, TestVector4 source, float amount, VectorAssert.Equal(expected, actual, 5); } - public static TheoryData HardLightFunctionData = new TheoryData { - { new TestVector4(1,1,1,1), new TestVector4(1,1,1,1), 1, new TestVector4(1,1,1,1) }, - { new TestVector4(1,1,1,1), new TestVector4(0,0,0,.8f), .5f, new TestVector4(0.6f,0.6f,0.6f,1f) }, - { - new TestVector4(0.2f,0.2f,0.2f,0.3f), - new TestVector4(0.3f,0.3f,0.3f,0.2f), - .5f, - new TestVector4(.2124324f, .2124324f, .2124324f, .37f) - }, + public static TheoryData HardLightFunctionData = new TheoryData + { + { new TestVector4(1, 1, 1, 1), new TestVector4(1, 1, 1, 1), 1, new TestVector4(1, 1, 1, 1) }, + { new TestVector4(1, 1, 1, 1), new TestVector4(0, 0, 0, .8f), .5f, new TestVector4(0.6f, 0.6f, 0.6f, 1f) }, + { new TestVector4(0.2f, 0.2f, 0.2f, 0.3f), new TestVector4(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestVector4(.2124324f, .2124324f, .2124324f, .37f) }, }; [Theory] diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests_TPixel.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTestsTPixel.cs similarity index 80% rename from tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests_TPixel.cs rename to tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTestsTPixel.cs index 859be6b205..f85c716e45 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTests_TPixel.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffFunctionsTestsTPixel.cs @@ -17,9 +17,10 @@ private static Span AsSpan(T value) return new Span(new[] { value }); } - public static TheoryData NormalBlendFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(0.6f, 0.6f, 0.6f, 1) }, + public static TheoryData NormalBlendFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(0.6f, 0.6f, 0.6f, 1) } }; private Configuration Configuration => Configuration.Default; @@ -52,12 +53,13 @@ public void NormalBlendFunctionBlenderBulk(TestPixel back, TestP VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData MultiplyFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(0.6f, 0.6f, 0.6f, 1) }, + public static TheoryData MultiplyFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(0.6f, 0.6f, 0.6f, 1) }, { - new TestPixel(0.9f,0.9f,0.9f,0.9f), - new TestPixel(0.4f,0.4f,0.4f,0.4f), + new TestPixel(0.9f, 0.9f, 0.9f, 0.9f), + new TestPixel(0.4f, 0.4f, 0.4f, 0.4f), .5f, new TestPixel(0.7834783f, 0.7834783f, 0.7834783f, 0.92f) }, @@ -91,15 +93,26 @@ public void MultiplyFunctionBlenderBulk(TestPixel back, TestPixe VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData AddFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(1f, 1f, 1f, 1f) }, + public static TheoryData AddFunctionData = new TheoryData + { + { + new TestPixel(1, 1, 1, 1), + new TestPixel(1, 1, 1, 1), + 1, + new TestPixel(1, 1, 1, 1) + }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(1, 1, 1, 1), + new TestPixel(0, 0, 0, .8f), .5f, - new TestPixel(.2431373f, .2431373f, .2431373f, .372549f) + new TestPixel(1f, 1f, 1f, 1f) }, + { + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), + .5f, + new TestPixel(.2431373f, .2431373f, .2431373f, .372549f) + } }; [Theory] @@ -130,12 +143,13 @@ public void AddFunctionBlenderBulk(TestPixel back, TestPixel SubtractFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(0,0,0,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(1,1,1, 1f) }, + public static TheoryData SubtractFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(0, 0, 0, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(1, 1, 1, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.2027027f, .2027027f, .2027027f, .37f) }, @@ -169,12 +183,13 @@ public void SubtractFunctionBlenderBulk(TestPixel back, TestPixe VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData ScreenFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(1,1,1, 1f) }, + public static TheoryData ScreenFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(1, 1, 1, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.2383784f, .2383784f, .2383784f, .37f) }, @@ -208,12 +223,13 @@ public void ScreenFunctionBlenderBulk(TestPixel back, TestPixel< VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData DarkenFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(.6f,.6f,.6f, 1f) }, + public static TheoryData DarkenFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(.6f, .6f, .6f, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.2189189f, .2189189f, .2189189f, .37f) }, @@ -247,15 +263,16 @@ public void DarkenFunctionBlenderBulk(TestPixel back, TestPixel< VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData LightenFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(1,1,1,1f) }, + public static TheoryData LightenFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(1, 1, 1, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.227027f, .227027f, .227027f, .37f) - }, + } }; [Theory] @@ -286,15 +303,16 @@ public void LightenFunctionBlenderBulk(TestPixel back, TestPixel VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData OverlayFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(1,1,1,1f) }, + public static TheoryData OverlayFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(1, 1, 1, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.2124324f, .2124324f, .2124324f, .37f) - }, + } }; [Theory] @@ -325,12 +343,13 @@ public void OverlayFunctionBlenderBulk(TestPixel back, TestPixel VectorAssert.Equal(expected, dest[0], 2); } - public static TheoryData HardLightFunctionData = new TheoryData { - { new TestPixel(1,1,1,1), new TestPixel(1,1,1,1), 1, new TestPixel(1,1,1,1) }, - { new TestPixel(1,1,1,1), new TestPixel(0,0,0,.8f), .5f, new TestPixel(0.6f,0.6f,0.6f,1f) }, + public static TheoryData HardLightFunctionData = new TheoryData + { + { new TestPixel(1, 1, 1, 1), new TestPixel(1, 1, 1, 1), 1, new TestPixel(1, 1, 1, 1) }, + { new TestPixel(1, 1, 1, 1), new TestPixel(0, 0, 0, .8f), .5f, new TestPixel(0.6f, 0.6f, 0.6f, 1f) }, { - new TestPixel(0.2f,0.2f,0.2f,0.3f), - new TestPixel(0.3f,0.3f,0.3f,0.2f), + new TestPixel(0.2f, 0.2f, 0.2f, 0.3f), + new TestPixel(0.3f, 0.3f, 0.3f, 0.2f), .5f, new TestPixel(.2124324f, .2124324f, .2124324f, .37f) }, diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.ReferenceImplementations.cs b/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.ReferenceImplementations.cs index 6a678abc7f..9293333b89 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.ReferenceImplementations.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.ReferenceImplementations.cs @@ -1,11 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. - -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. - -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using System; using System.Runtime.CompilerServices; @@ -53,7 +47,8 @@ internal static void To( Configuration configuration, ReadOnlySpan sourcePixels, Span destinationPixels) - where TSourcePixel : struct, IPixel where TDestinationPixel : struct, IPixel + where TSourcePixel : struct, IPixel + where TDestinationPixel : struct, IPixel { Guard.NotNull(configuration, nameof(configuration)); Guard.DestinationShouldNotBeTooShort(sourcePixels, destinationPixels, nameof(destinationPixels)); @@ -75,12 +70,11 @@ internal static void To( // packs/unpacks the pixel without and conversion so we employ custom methods do do this. if (typeof(TDestinationPixel) == typeof(L16)) { - ref L16 L16Ref = ref MemoryMarshal.GetReference( - MemoryMarshal.Cast(destinationPixels)); + ref L16 l16Ref = ref MemoryMarshal.GetReference(MemoryMarshal.Cast(destinationPixels)); for (int i = 0; i < count; i++) { ref TSourcePixel sp = ref Unsafe.Add(ref sourceRef, i); - ref L16 dp = ref Unsafe.Add(ref L16Ref, i); + ref L16 dp = ref Unsafe.Add(ref l16Ref, i); dp.ConvertFromRgbaScaledVector4(sp.ToScaledVector4()); } @@ -89,12 +83,12 @@ internal static void To( if (typeof(TDestinationPixel) == typeof(L8)) { - ref L8 L8Ref = ref MemoryMarshal.GetReference( + ref L8 l8Ref = ref MemoryMarshal.GetReference( MemoryMarshal.Cast(destinationPixels)); for (int i = 0; i < count; i++) { ref TSourcePixel sp = ref Unsafe.Add(ref sourceRef, i); - ref L8 dp = ref Unsafe.Add(ref L8Ref, i); + ref L8 dp = ref Unsafe.Add(ref l8Ref, i); dp.ConvertFromRgbaScaledVector4(sp.ToScaledVector4()); } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.cs index f1f56fcd46..19623c3d8f 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelConverterTests.cs @@ -1,4 +1,7 @@ -using SixLabors.ImageSharp.PixelFormats; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats.Utils; using Xunit; diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelConversionModifiersExtensionsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelConversionModifiersExtensionsTests.cs index e98e14fc62..817c29aa1e 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelConversionModifiersExtensionsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelConversionModifiersExtensionsTests.cs @@ -1,9 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.PixelFormats; @@ -38,8 +34,7 @@ internal void IsDefined( } [Theory] - [InlineData(PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale | PixelConversionModifiers.SRgbCompand, - PixelConversionModifiers.Scale, PixelConversionModifiers.Premultiply | PixelConversionModifiers.SRgbCompand)] + [InlineData(PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale | PixelConversionModifiers.SRgbCompand, PixelConversionModifiers.Scale, PixelConversionModifiers.Premultiply | PixelConversionModifiers.SRgbCompand)] [InlineData(PixelConversionModifiers.None, PixelConversionModifiers.Premultiply, PixelConversionModifiers.None)] internal void Remove( PixelConversionModifiers baselineModifiers, @@ -62,4 +57,4 @@ internal void ApplyCompanding( Assert.Equal(expected, result); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Argb32OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Argb32OperationsTests.cs index c881ae96ba..9a0f4d8acb 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Argb32OperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Argb32OperationsTests.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. using SixLabors.ImageSharp.PixelFormats; @@ -12,7 +12,6 @@ public partial class PixelOperationsTests { public class Argb32OperationsTests : PixelOperationsTests { - public Argb32OperationsTests(ITestOutputHelper output) : base(output) { @@ -22,4 +21,4 @@ public Argb32OperationsTests(ITestOutputHelper output) public void IsSpecialImplementation() => Assert.IsType(PixelOperations.Instance); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.L16OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.L16OperationsTests.cs index ddcdc30bfd..87aed91e76 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.L16OperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.L16OperationsTests.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. using SixLabors.ImageSharp.PixelFormats; @@ -19,7 +19,6 @@ public L16OperationsTests(ITestOutputHelper output) [Fact] public void IsSpecialImplementation() => Assert.IsType(PixelOperations.Instance); - } } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La16OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La16OperationsTests.cs index f03aa5587f..a17594af6a 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La16OperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La16OperationsTests.cs @@ -19,7 +19,6 @@ public La16OperationsTests(ITestOutputHelper output) [Fact] public void IsSpecialImplementation() => Assert.IsType(PixelOperations.Instance); - } } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La32OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La32OperationsTests.cs index 2112a2fea3..dce9342866 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La32OperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.La32OperationsTests.cs @@ -19,7 +19,6 @@ public La32OperationsTests(ITestOutputHelper output) [Fact] public void IsSpecialImplementation() => Assert.IsType(PixelOperations.Instance); - } } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs index ef2531060e..0cea91c781 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs @@ -18,11 +18,13 @@ namespace SixLabors.ImageSharp.Tests.PixelFormats.PixelOperations { public partial class PixelOperationsTests { +#pragma warning disable SA1313 // Parameter names should begin with lower-case letter [Theory] [WithBlankImages(1, 1, PixelTypes.All)] public void GetGlobalInstance(TestImageProvider _) where T : struct, IPixel => Assert.NotNull(PixelOperations.Instance); } +#pragma warning restore SA1313 // Parameter names should begin with lower-case letter public abstract class PixelOperationsTests : MeasureFixture where TPixel : struct, IPixel @@ -113,8 +115,7 @@ public void FromVector4(int count) TestOperation( source, expected, - (s, d) => Operations.FromVector4Destructive(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.FromVector4Destructive(this.Configuration, s, d.GetSpan())); } [Theory] @@ -138,18 +139,18 @@ public void FromScaledVector4(int count) [MemberData(nameof(ArraySizesData))] public void FromCompandedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { SRgbCompanding.Expand(ref v); } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { SRgbCompanding.Compress(ref v); } - Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => sourceAction(ref v)); - TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => expectedAction(ref v)); + Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => SourceAction(ref v)); + TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -158,15 +159,14 @@ void expectedAction(ref Vector4 v) this.Configuration, s, d.GetSpan(), - PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Scale) - ); + PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Scale)); } [Theory] [MemberData(nameof(ArraySizesData))] public void FromPremultipliedVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { if (this.HasAlpha) { @@ -174,7 +174,7 @@ void sourceAction(ref Vector4 v) } } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { if (this.HasAlpha) { @@ -182,21 +182,20 @@ void expectedAction(ref Vector4 v) } } - Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => sourceAction(ref v)); - TPixel[] expected = CreateExpectedPixelData(source, (ref Vector4 v) => expectedAction(ref v)); + Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => SourceAction(ref v)); + TPixel[] expected = CreateExpectedPixelData(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, expected, - (s, d) => Operations.FromVector4Destructive(this.Configuration, s, d.GetSpan(), PixelConversionModifiers.Premultiply) - ); + (s, d) => Operations.FromVector4Destructive(this.Configuration, s, d.GetSpan(), PixelConversionModifiers.Premultiply)); } [Theory] [MemberData(nameof(ArraySizesData))] public void FromPremultipliedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { if (this.HasAlpha) { @@ -204,7 +203,7 @@ void sourceAction(ref Vector4 v) } } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { if (this.HasAlpha) { @@ -212,8 +211,8 @@ void expectedAction(ref Vector4 v) } } - Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => sourceAction(ref v)); - TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => expectedAction(ref v)); + Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => SourceAction(ref v)); + TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -222,15 +221,14 @@ void expectedAction(ref Vector4 v) this.Configuration, s, d.GetSpan(), - PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale) - ); + PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale)); } [Theory] [MemberData(nameof(ArraySizesData))] public void FromCompandedPremultipliedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { SRgbCompanding.Expand(ref v); @@ -240,7 +238,7 @@ void sourceAction(ref Vector4 v) } } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { if (this.HasAlpha) { @@ -250,8 +248,8 @@ void expectedAction(ref Vector4 v) SRgbCompanding.Compress(ref v); } - Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => sourceAction(ref v)); - TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => expectedAction(ref v)); + Vector4[] source = CreateVector4TestData(count, (ref Vector4 v) => SourceAction(ref v)); + TPixel[] expected = CreateScaledExpectedPixelData(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -260,8 +258,7 @@ void expectedAction(ref Vector4 v) this.Configuration, s, d.GetSpan(), - PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale) - ); + PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale)); } [Theory] @@ -274,11 +271,9 @@ public void ToVector4(int count) TestOperation( source, expected, - (s, d) => Operations.ToVector4(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.ToVector4(this.Configuration, s, d.GetSpan())); } - public static readonly TheoryData Generic_To_Data = new TheoryData { default(Rgba32), @@ -304,7 +299,6 @@ public void Generic_To(TDestPixel dummy) TestOperation(source, expected, (s, d) => Operations.To(this.Configuration, (ReadOnlySpan)s, d.GetSpan())); } - [Theory] [MemberData(nameof(ArraySizesData))] public void ToScaledVector4(int count) @@ -326,18 +320,18 @@ public void ToScaledVector4(int count) [MemberData(nameof(ArraySizesData))] public void ToCompandedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { SRgbCompanding.Compress(ref v); } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { SRgbCompanding.Expand(ref v); } - TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => sourceAction(ref v)); - Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => expectedAction(ref v)); + TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => SourceAction(ref v)); + Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -346,50 +340,48 @@ void expectedAction(ref Vector4 v) this.Configuration, s, d.GetSpan(), - PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Scale) - ); + PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Scale)); } [Theory] [MemberData(nameof(ArraySizesData))] public void ToPremultipliedVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { Vector4Utils.UnPremultiply(ref v); } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { Vector4Utils.Premultiply(ref v); } - TPixel[] source = CreatePixelTestData(count, (ref Vector4 v) => sourceAction(ref v)); - Vector4[] expected = CreateExpectedVector4Data(source, (ref Vector4 v) => expectedAction(ref v)); + TPixel[] source = CreatePixelTestData(count, (ref Vector4 v) => SourceAction(ref v)); + Vector4[] expected = CreateExpectedVector4Data(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, expected, - (s, d) => Operations.ToVector4(this.Configuration, s, d.GetSpan(), PixelConversionModifiers.Premultiply) - ); + (s, d) => Operations.ToVector4(this.Configuration, s, d.GetSpan(), PixelConversionModifiers.Premultiply)); } [Theory] [MemberData(nameof(ArraySizesData))] public void ToPremultipliedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { Vector4Utils.UnPremultiply(ref v); } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { Vector4Utils.Premultiply(ref v); } - TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => sourceAction(ref v)); - Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => expectedAction(ref v)); + TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => SourceAction(ref v)); + Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -405,20 +397,20 @@ void expectedAction(ref Vector4 v) [MemberData(nameof(ArraySizesData))] public void ToCompandedPremultipliedScaledVector4(int count) { - void sourceAction(ref Vector4 v) + void SourceAction(ref Vector4 v) { Vector4Utils.UnPremultiply(ref v); SRgbCompanding.Compress(ref v); } - void expectedAction(ref Vector4 v) + void ExpectedAction(ref Vector4 v) { SRgbCompanding.Expand(ref v); Vector4Utils.Premultiply(ref v); } - TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => sourceAction(ref v)); - Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => expectedAction(ref v)); + TPixel[] source = CreateScaledPixelTestData(count, (ref Vector4 v) => SourceAction(ref v)); + Vector4[] expected = CreateExpectedScaledVector4Data(source, (ref Vector4 v) => ExpectedAction(ref v)); TestOperation( source, @@ -427,8 +419,7 @@ void expectedAction(ref Vector4 v) this.Configuration, s, d.GetSpan(), - PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale) - ); + PixelConversionModifiers.SRgbCompand | PixelConversionModifiers.Premultiply | PixelConversionModifiers.Scale)); } [Theory] @@ -448,8 +439,7 @@ public void FromArgb32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromArgb32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromArgb32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -457,7 +447,7 @@ public void FromArgb32Bytes(int count) public void ToArgb32Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 4]; + byte[] expected = new byte[count * 4]; var argb = default(Argb32); for (int i = 0; i < count; i++) @@ -474,8 +464,7 @@ public void ToArgb32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToArgb32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToArgb32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -495,8 +484,7 @@ public void FromBgr24Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromBgr24Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromBgr24Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -504,7 +492,7 @@ public void FromBgr24Bytes(int count) public void ToBgr24Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 3]; + byte[] expected = new byte[count * 3]; var bgr = default(Bgr24); for (int i = 0; i < count; i++) @@ -519,8 +507,7 @@ public void ToBgr24Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToBgr24Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToBgr24Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -540,8 +527,7 @@ public void FromBgra32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromBgra32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromBgra32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -549,7 +535,7 @@ public void FromBgra32Bytes(int count) public void ToBgra32Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 4]; + byte[] expected = new byte[count * 4]; var bgra = default(Bgra32); for (int i = 0; i < count; i++) @@ -565,8 +551,7 @@ public void ToBgra32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToBgra32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToBgra32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -588,8 +573,7 @@ public void FromBgra5551Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromBgra5551Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromBgra5551Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -598,7 +582,7 @@ public void ToBgra5551Bytes(int count) { int size = Unsafe.SizeOf(); TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * size]; + byte[] expected = new byte[count * size]; Bgra5551 bgra = default; for (int i = 0; i < count; i++) @@ -613,8 +597,7 @@ public void ToBgra5551Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToBgra5551Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToBgra5551Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -625,7 +608,6 @@ public void FromL8(int count) L8[] source = sourceBytes.Select(b => new L8(b)).ToArray(); var expected = new TPixel[count]; - for (int i = 0; i < count; i++) { expected[i].FromL8(source[i]); @@ -634,8 +616,7 @@ public void FromL8(int count) TestOperation( source, expected, - (s, d) => Operations.FromL8(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.FromL8(this.Configuration, s, d.GetSpan())); } [Theory] @@ -653,8 +634,7 @@ public void ToL8(int count) TestOperation( source, expected, - (s, d) => Operations.ToL8(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.ToL8(this.Configuration, s, d.GetSpan())); } [Theory] @@ -678,8 +658,7 @@ public void FromL16(int count) TestOperation( source, expected, - (s, d) => Operations.FromL16(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.FromL16(this.Configuration, s, d.GetSpan())); } [Theory] @@ -697,8 +676,7 @@ public void ToL16(int count) TestOperation( source, expected, - (s, d) => Operations.ToL16(this.Configuration, s, d.GetSpan()) - ); + (s, d) => Operations.ToL16(this.Configuration, s, d.GetSpan())); } [Theory] @@ -720,8 +698,7 @@ public void FromLa16Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromLa16Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromLa16Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -730,7 +707,7 @@ public void ToLa16Bytes(int count) { int size = Unsafe.SizeOf(); TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * size]; + byte[] expected = new byte[count * size]; La16 la = default; for (int i = 0; i < count; i++) @@ -745,8 +722,7 @@ public void ToLa16Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToLa16Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToLa16Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -768,17 +744,16 @@ public void FromLa32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromLa32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromLa32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] [MemberData(nameof(ArraySizesData))] public void ToLa32Bytes(int count) { - var size = Unsafe.SizeOf(); + int size = Unsafe.SizeOf(); TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * size]; + byte[] expected = new byte[count * size]; La32 la = default; for (int i = 0; i < count; i++) @@ -795,8 +770,7 @@ public void ToLa32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToLa32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToLa32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -816,8 +790,7 @@ public void FromRgb24Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromRgb24Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromRgb24Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -825,7 +798,7 @@ public void FromRgb24Bytes(int count) public void ToRgb24Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 3]; + byte[] expected = new byte[count * 3]; var rgb = default(Rgb24); for (int i = 0; i < count; i++) @@ -840,8 +813,7 @@ public void ToRgb24Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToRgb24Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToRgb24Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -861,8 +833,7 @@ public void FromRgba32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromRgba32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromRgba32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -870,7 +841,7 @@ public void FromRgba32Bytes(int count) public void ToRgba32Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 4]; + byte[] expected = new byte[count * 4]; var rgba = default(Rgba32); for (int i = 0; i < count; i++) @@ -886,8 +857,7 @@ public void ToRgba32Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToRgba32Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToRgba32Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -907,8 +877,7 @@ public void FromRgb48Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromRgb48Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromRgb48Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -916,7 +885,7 @@ public void FromRgb48Bytes(int count) public void ToRgb48Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 6]; + byte[] expected = new byte[count * 6]; Rgb48 rgb = default; for (int i = 0; i < count; i++) @@ -935,8 +904,7 @@ public void ToRgb48Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToRgb48Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToRgb48Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -956,8 +924,7 @@ public void FromRgba64Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.FromRgba64Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.FromRgba64Bytes(this.Configuration, s, d.GetSpan(), count)); } [Theory] @@ -965,7 +932,7 @@ public void FromRgba64Bytes(int count) public void ToRgba64Bytes(int count) { TPixel[] source = CreatePixelTestData(count); - var expected = new byte[count * 8]; + byte[] expected = new byte[count * 8]; Rgba64 rgba = default; for (int i = 0; i < count; i++) @@ -986,8 +953,7 @@ public void ToRgba64Bytes(int count) TestOperation( source, expected, - (s, d) => Operations.ToRgba64Bytes(this.Configuration, s, d.GetSpan(), count) - ); + (s, d) => Operations.ToRgba64Bytes(this.Configuration, s, d.GetSpan(), count)); } public delegate void RefAction(ref T1 arg1); @@ -1050,6 +1016,7 @@ internal static Vector4[] CreateVector4TestData(int length, RefAction v result[i] = v; } + return result; } @@ -1091,24 +1058,20 @@ internal static TPixel[] CreateScaledPixelTestData(int length, RefAction : IDisposable where TDest : struct { public TSource[] SourceBuffer { get; } + public IMemoryOwner ActualDestBuffer { get; } + public TDest[] ExpectedDestBuffer { get; } public TestBuffers(TSource[] source, TDest[] expectedDest) @@ -1158,6 +1123,7 @@ public void Verify() { // ReSharper disable PossibleNullReferenceException Assert.Equal(expected[i], actual[i], comparer); + // ReSharper restore PossibleNullReferenceException } } diff --git a/tests/ImageSharp.Tests/PixelFormats/Rg32Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Rg32Tests.cs index bccaaf8168..ad45b0771f 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Rg32Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Rg32Tests.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. using System.Numerics; @@ -15,10 +15,10 @@ public void Rg32_PackedValues() float x = 0xb6dc; float y = 0xA59f; Assert.Equal(0xa59fb6dc, new Rg32(x / 0xffff, y / 0xffff).PackedValue); - Assert.Equal((uint)6554, new Rg32(0.1f, -0.3f).PackedValue); + Assert.Equal(6554U, new Rg32(0.1f, -0.3f).PackedValue); // Test the limits. - Assert.Equal((uint)0x0, new Rg32(Vector2.Zero).PackedValue); + Assert.Equal(0x0U, new Rg32(Vector2.Zero).PackedValue); Assert.Equal(0xFFFFFFFF, new Rg32(Vector2.One).PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/Rgb48Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Rgb48Tests.cs index 3bddc21ab3..6ab7b9c954 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Rgb48Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Rgb48Tests.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. using System.Numerics; @@ -36,7 +36,7 @@ public void Rgb48_FromScaledVector4() var short3 = new Rgb48(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue); var expected = new Rgb48(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue); - // act + // act Vector4 scaled = short3.ToScaledVector4(); pixel.FromScaledVector4(scaled); @@ -75,4 +75,4 @@ public void Rgb48_FromBgra5551() Assert.Equal(expected, rgb.B); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/PixelFormats/Rgba1010102Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Rgba1010102Tests.cs index 56cb526a4d..7b3f71985c 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Rgba1010102Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Rgba1010102Tests.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. using System.Numerics; @@ -46,12 +46,12 @@ public void Rgba1010102_PackedValue() float y = 0x36d; float z = 0x3b7; float w = 0x1; - Assert.Equal((uint)0x7B7DB6DB, new Rgba1010102(x / 0x3ff, y / 0x3ff, z / 0x3ff, w / 3).PackedValue); + Assert.Equal(0x7B7DB6DBU, new Rgba1010102(x / 0x3ff, y / 0x3ff, z / 0x3ff, w / 3).PackedValue); - Assert.Equal((uint)536871014, new Rgba1010102(0.1f, -0.3f, 0.5f, -0.7f).PackedValue); + Assert.Equal(536871014U, new Rgba1010102(0.1f, -0.3f, 0.5f, -0.7f).PackedValue); // Test the limits. - Assert.Equal((uint)0x0, new Rgba1010102(Vector4.Zero).PackedValue); + Assert.Equal(0x0U, new Rgba1010102(Vector4.Zero).PackedValue); Assert.Equal(0xFFFFFFFF, new Rgba1010102(Vector4.One).PackedValue); } diff --git a/tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs index 1ab5f8e3df..a242dba41a 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs @@ -126,8 +126,9 @@ public unsafe void ByteLayout() public void Rgba32_PackedValues() { Assert.Equal(0x80001Au, new Rgba32(+0.1f, -0.3f, +0.5f, -0.7f).PackedValue); + // Test the limits. - Assert.Equal((uint)0x0, new Rgba32(Vector4.Zero).PackedValue); + Assert.Equal(0x0U, new Rgba32(Vector4.Zero).PackedValue); Assert.Equal(0xFFFFFFFF, new Rgba32(Vector4.One).PackedValue); } @@ -204,7 +205,7 @@ public void Rgba32_FromRgba32_ToRgba32() var actual = default(Rgba32); var expected = new Rgba32(0x1a, 0, 0x80, 0); - // act + // act rgba.FromRgba32(expected); actual.FromRgba32(rgba); @@ -220,7 +221,7 @@ public void Rgba32_FromBgra32_ToRgba32() var actual = default(Bgra32); var expected = new Bgra32(0x1a, 0, 0x80, 0); - // act + // act rgba.FromBgra32(expected); actual.FromRgba32(rgba); @@ -236,7 +237,7 @@ public void Rgba32_FromArgb32_ToArgb32() var actual = default(Argb32); var expected = new Argb32(0x1a, 0, 0x80, 0); - // act + // act rgba.FromArgb32(expected); actual.FromRgba32(rgba); diff --git a/tests/ImageSharp.Tests/PixelFormats/Rgba64Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Rgba64Tests.cs index 9cdf4125c7..34ec0bdef0 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Rgba64Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Rgba64Tests.cs @@ -12,15 +12,13 @@ public class Rgba64Tests [Fact] public void Rgba64_PackedValues() { - Assert.Equal((ulong)0x73334CCC2666147B, new Rgba64(5243, 9830, 19660, 29491).PackedValue); + Assert.Equal(0x73334CCC2666147BUL, new Rgba64(5243, 9830, 19660, 29491).PackedValue); // Test the limits. - Assert.Equal((ulong)0x0, new Rgba64(0, 0, 0, 0).PackedValue); - Assert.Equal(0xFFFFFFFFFFFFFFFF, new Rgba64( - ushort.MaxValue, - ushort.MaxValue, - ushort.MaxValue, - ushort.MaxValue).PackedValue); + Assert.Equal(0x0UL, new Rgba64(0, 0, 0, 0).PackedValue); + Assert.Equal( + 0xFFFFFFFFFFFFFFFF, + new Rgba64(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue, ushort.MaxValue).PackedValue); // Test data ordering Assert.Equal(0xC7AD8F5C570A1EB8, new Rgba64(0x1EB8, 0x570A, 0x8F5C, 0xC7AD).PackedValue); @@ -36,7 +34,7 @@ public void Rgba64_ToVector4() [Theory] [InlineData(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue, ushort.MaxValue)] [InlineData(0, 0, 0, 0)] - [InlineData(ushort.MaxValue/2, 100, 2222, 33333)] + [InlineData(ushort.MaxValue / 2, 100, 2222, 33333)] public void Rgba64_ToScaledVector4(ushort r, ushort g, ushort b, ushort a) { // arrange @@ -61,17 +59,15 @@ public void Rgba64_ToScaledVector4(ushort r, ushort g, ushort b, ushort a) [Theory] [InlineData(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue, ushort.MaxValue)] [InlineData(0, 0, 0, 0)] - [InlineData(ushort.MaxValue/2, 100, 2222, 33333)] + [InlineData(ushort.MaxValue / 2, 100, 2222, 33333)] public void Rgba64_FromScaledVector4(ushort r, ushort g, ushort b, ushort a) { // arrange - var source = new Rgba64(r, g, b, a); // act Vector4 scaled = source.ToScaledVector4(); - Rgba64 actual = default; actual.FromScaledVector4(scaled); @@ -105,7 +101,6 @@ public void Rgba64_ToRgba32() Assert.Equal(expected, actual); } - [Fact] public void Rgba64_FromBgra5551() { @@ -219,7 +214,6 @@ public void ConstructFrom_Vector4() Assert.Equal(expected, actual); } - [Fact] public void ToRgba32_Retval() { diff --git a/tests/ImageSharp.Tests/PixelFormats/Short2Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Short2Tests.cs index 4ae172ed4e..45f65eb4b7 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Short2Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Short2Tests.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. using System.Numerics; @@ -13,11 +13,12 @@ public class Short2Tests public void Short2_PackedValues() { // Test ordering - Assert.Equal((uint)0x361d2db1, new Short2(0x2db1, 0x361d).PackedValue); + Assert.Equal(0x361d2db1U, new Short2(0x2db1, 0x361d).PackedValue); Assert.Equal(4294639744, new Short2(127.5f, -5.3f).PackedValue); + // Test the limits. - Assert.Equal((uint)0x0, new Short2(Vector2.Zero).PackedValue); - Assert.Equal((uint)0x7FFF7FFF, new Short2(Vector2.One * 0x7FFF).PackedValue); + Assert.Equal(0x0U, new Short2(Vector2.Zero).PackedValue); + Assert.Equal(0x7FFF7FFFU, new Short2(Vector2.One * 0x7FFF).PackedValue); Assert.Equal(0x80008000, new Short2(Vector2.One * -0x8000).PackedValue); } @@ -34,9 +35,9 @@ public void Short2_ToVector2() [Fact] public void Short2_ToVector4() { - Assert.Equal(new Vector4(0x7FFF, 0x7FFF, 0, 1), (new Short2(Vector2.One * 0x7FFF)).ToVector4()); - Assert.Equal(new Vector4(0, 0, 0, 1), (new Short2(Vector2.Zero)).ToVector4()); - Assert.Equal(new Vector4(-0x8000, -0x8000, 0, 1), (new Short2(Vector2.One * -0x8000)).ToVector4()); + Assert.Equal(new Vector4(0x7FFF, 0x7FFF, 0, 1), new Short2(Vector2.One * 0x7FFF).ToVector4()); + Assert.Equal(new Vector4(0, 0, 0, 1), new Short2(Vector2.Zero).ToVector4()); + Assert.Equal(new Vector4(-0x8000, -0x8000, 0, 1), new Short2(Vector2.One * -0x8000).ToVector4()); } [Fact] @@ -70,7 +71,7 @@ public void Short2_FromScaledVector4() var short2 = new Short2(Vector2.One * 0x7FFF); const ulong expected = 0x7FFF7FFF; - // act + // act Vector4 scaled = short2.ToScaledVector4(); pixel.FromScaledVector4(scaled); uint actual = pixel.PackedValue; @@ -102,7 +103,7 @@ public void Short2_FromRgba32_ToRgba32() var actual = default(Rgba32); var expected = new Rgba32(20, 38, 0, 255); - // act + // act short2.FromRgba32(expected); short2.ToRgba32(ref actual); @@ -147,7 +148,7 @@ public void Short2_FromBgra5551() { // arrange var short2 = default(Short2); - + // act short2.FromBgra5551(new Bgra5551(1.0f, 1.0f, 1.0f, 1.0f)); diff --git a/tests/ImageSharp.Tests/PixelFormats/Short4Tests.cs b/tests/ImageSharp.Tests/PixelFormats/Short4Tests.cs index 45f8e25f43..54abf0db08 100644 --- a/tests/ImageSharp.Tests/PixelFormats/Short4Tests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/Short4Tests.cs @@ -15,10 +15,10 @@ public void Short4_PackedValues() var shortValue1 = new Short4(11547, 12653, 29623, 193); var shortValue2 = new Short4(0.1f, -0.3f, 0.5f, -0.7f); - Assert.Equal((ulong)0x00c173b7316d2d1b, shortValue1.PackedValue); + Assert.Equal(0x00c173b7316d2d1bUL, shortValue1.PackedValue); Assert.Equal(18446462598732840960, shortValue2.PackedValue); - Assert.Equal((ulong)0x0, new Short4(Vector4.Zero).PackedValue); - Assert.Equal((ulong)0x7FFF7FFF7FFF7FFF, new Short4(Vector4.One * 0x7FFF).PackedValue); + Assert.Equal(0x0UL, new Short4(Vector4.Zero).PackedValue); + Assert.Equal(0x7FFF7FFF7FFF7FFFUL, new Short4(Vector4.One * 0x7FFF).PackedValue); Assert.Equal(0x8000800080008000, new Short4(Vector4.One * -0x8000).PackedValue); } @@ -105,7 +105,7 @@ public void Short4_FromRgba32_ToRgba32() var actual = default(Rgba32); var expected = new Rgba32(20, 38, 0, 255); - // act + // act short4.FromRgba32(expected); short4.ToRgba32(ref actual); @@ -121,7 +121,7 @@ public void Short4_FromBgra32_ToRgba32() var actual = default(Bgra32); var expected = new Bgra32(20, 38, 0, 255); - // act + // act short4.FromBgra32(expected); Rgba32 temp = default; short4.ToRgba32(ref temp); @@ -139,7 +139,7 @@ public void Short4_FromArgb32_ToRgba32() var actual = default(Argb32); var expected = new Argb32(20, 38, 0, 255); - // act + // act short4.FromArgb32(expected); Rgba32 temp = default; short4.ToRgba32(ref temp); diff --git a/tests/ImageSharp.Tests/Primitives/ColorMatrixTests.cs b/tests/ImageSharp.Tests/Primitives/ColorMatrixTests.cs index 2fbe260ecd..f81d4e128b 100644 --- a/tests/ImageSharp.Tests/Primitives/ColorMatrixTests.cs +++ b/tests/ImageSharp.Tests/Primitives/ColorMatrixTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Globalization; using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing; @@ -8,7 +11,7 @@ namespace SixLabors.ImageSharp.Tests.Primitives { public class ColorMatrixTests { - private readonly ApproximateFloatComparer ApproximateFloatComparer = new ApproximateFloatComparer(1e-6f); + private readonly ApproximateFloatComparer approximateFloatComparer = new ApproximateFloatComparer(1e-6f); [Fact] public void ColorMatrixIdentityIsCorrect() @@ -16,7 +19,7 @@ public void ColorMatrixIdentityIsCorrect() ColorMatrix val = default; val.M11 = val.M22 = val.M33 = val.M44 = 1F; - Assert.Equal(val, ColorMatrix.Identity, this.ApproximateFloatComparer); + Assert.Equal(val, ColorMatrix.Identity, this.approximateFloatComparer); } [Fact] @@ -80,14 +83,14 @@ public void ColorMatrixMultiply() m.M53 = (value1.M51 * value2.M13) + (value1.M52 * value2.M23) + (value1.M53 * value2.M33) + (value1.M54 * value2.M53) + value2.M53; m.M54 = (value1.M51 * value2.M14) + (value1.M52 * value2.M24) + (value1.M53 * value2.M34) + (value1.M54 * value2.M54) + value2.M54; - Assert.Equal(m, value1 * value2, this.ApproximateFloatComparer); + Assert.Equal(m, value1 * value2, this.approximateFloatComparer); } [Fact] public void ColorMatrixMultiplyScalar() { ColorMatrix m = this.CreateAllTwos(); - Assert.Equal(this.CreateAllFours(), m * 2, this.ApproximateFloatComparer); + Assert.Equal(this.CreateAllFours(), m * 2, this.approximateFloatComparer); } [Fact] @@ -149,12 +152,14 @@ public void ColorMatrixToString() CultureInfo ci = CultureInfo.CurrentCulture; +#pragma warning disable SA1117 // Parameters should be on same line or separate lines string expected = string.Format(ci, "{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} {{M51:{16} M52:{17} M53:{18} M54:{19}}} }}", - m.M11.ToString(ci), m.M12.ToString(ci), m.M13.ToString(ci), m.M14.ToString(ci), - m.M21.ToString(ci), m.M22.ToString(ci), m.M23.ToString(ci), m.M24.ToString(ci), - m.M31.ToString(ci), m.M32.ToString(ci), m.M33.ToString(ci), m.M34.ToString(ci), - m.M41.ToString(ci), m.M42.ToString(ci), m.M43.ToString(ci), m.M44.ToString(ci), - m.M51.ToString(ci), m.M52.ToString(ci), m.M53.ToString(ci), m.M54.ToString(ci)); + m.M11.ToString(ci), m.M12.ToString(ci), m.M13.ToString(ci), m.M14.ToString(ci), + m.M21.ToString(ci), m.M22.ToString(ci), m.M23.ToString(ci), m.M24.ToString(ci), + m.M31.ToString(ci), m.M32.ToString(ci), m.M33.ToString(ci), m.M34.ToString(ci), + m.M41.ToString(ci), m.M42.ToString(ci), m.M43.ToString(ci), m.M44.ToString(ci), + m.M51.ToString(ci), m.M52.ToString(ci), m.M53.ToString(ci), m.M54.ToString(ci)); +#pragma warning restore SA1117 // Parameters should be on same line or separate lines Assert.Equal(expected, m.ToString()); } diff --git a/tests/ImageSharp.Tests/Processing/Binarization/BinaryDitherTest.cs b/tests/ImageSharp.Tests/Processing/Binarization/BinaryDitherTest.cs index 531ad69b83..f5a26dc179 100644 --- a/tests/ImageSharp.Tests/Processing/Binarization/BinaryDitherTest.cs +++ b/tests/ImageSharp.Tests/Processing/Binarization/BinaryDitherTest.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. using SixLabors.ImageSharp.Processing; @@ -39,6 +39,7 @@ public void BinaryDither_rect_CorrectProcessor() Assert.Equal(Color.White, p.UpperColor); Assert.Equal(Color.Black, p.LowerColor); } + [Fact] public void BinaryDither_index_CorrectProcessor() { @@ -58,7 +59,6 @@ public void BinaryDither_index_rect_CorrectProcessor() Assert.Equal(Color.HotPink, p.LowerColor); } - [Fact] public void BinaryDither_ErrorDiffuser_CorrectProcessor() { @@ -103,4 +103,4 @@ public void BinaryDither_ErrorDiffuser_rect_CorrectProcessorWithColors() Assert.Equal(Color.Yellow, p.LowerColor); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Binarization/OrderedDitherFactoryTests.cs b/tests/ImageSharp.Tests/Processing/Binarization/OrderedDitherFactoryTests.cs index c98f910464..3df130d25f 100644 --- a/tests/ImageSharp.Tests/Processing/Binarization/OrderedDitherFactoryTests.cs +++ b/tests/ImageSharp.Tests/Processing/Binarization/OrderedDitherFactoryTests.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. using SixLabors.ImageSharp.Primitives; @@ -10,6 +10,8 @@ namespace SixLabors.ImageSharp.Tests.Processing.Binarization { public class OrderedDitherFactoryTests { +#pragma warning disable SA1025 // Code should not contain multiple whitespace in a row + private static readonly DenseMatrix Expected2x2Matrix = new DenseMatrix( new uint[2, 2] { @@ -47,6 +49,7 @@ public class OrderedDitherFactoryTests { 63, 31, 55, 23, 61, 29, 53, 21 } }); +#pragma warning restore SA1025 // Code should not contain multiple whitespace in a row [Fact] public void OrderedDitherFactoryCreatesCorrect2x2Matrix() @@ -100,4 +103,4 @@ public void OrderedDitherFactoryCreatesCorrect8x8Matrix() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Convolution/DetectEdgesTest.cs b/tests/ImageSharp.Tests/Processing/Convolution/DetectEdgesTest.cs index 6a864d83a4..e0b1e1bbb1 100644 --- a/tests/ImageSharp.Tests/Processing/Convolution/DetectEdgesTest.cs +++ b/tests/ImageSharp.Tests/Processing/Convolution/DetectEdgesTest.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. using System.Collections.Generic; @@ -13,7 +13,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Convolution { public class DetectEdgesTest : BaseImageOperationsExtensionTest { - [Fact] public void DetectEdges_SobelProcessorDefaultsSet() { @@ -33,17 +32,19 @@ public void DetectEdges_Rect_SobelProcessorDefaultsSet() SobelProcessor processor = this.Verify(this.rect); Assert.True(processor.Grayscale); } - public static IEnumerable EdgeDetectionTheoryData => new[] { - new object[]{ new TestType(), EdgeDetectionOperators.Kayyali }, - new object[]{ new TestType(), EdgeDetectionOperators.Kirsch }, - new object[]{ new TestType(), EdgeDetectionOperators.Laplacian3x3 }, - new object[]{ new TestType(), EdgeDetectionOperators.Laplacian5x5 }, - new object[]{ new TestType(), EdgeDetectionOperators.LaplacianOfGaussian }, - new object[]{ new TestType(), EdgeDetectionOperators.Prewitt }, - new object[]{ new TestType(), EdgeDetectionOperators.RobertsCross }, - new object[]{ new TestType(), EdgeDetectionOperators.Robinson }, - new object[]{ new TestType(), EdgeDetectionOperators.Scharr }, - new object[]{ new TestType(), EdgeDetectionOperators.Sobel }, + + public static IEnumerable EdgeDetectionTheoryData => new[] + { + new object[] { new TestType(), EdgeDetectionOperators.Kayyali }, + new object[] { new TestType(), EdgeDetectionOperators.Kirsch }, + new object[] { new TestType(), EdgeDetectionOperators.Laplacian3x3 }, + new object[] { new TestType(), EdgeDetectionOperators.Laplacian5x5 }, + new object[] { new TestType(), EdgeDetectionOperators.LaplacianOfGaussian }, + new object[] { new TestType(), EdgeDetectionOperators.Prewitt }, + new object[] { new TestType(), EdgeDetectionOperators.RobertsCross }, + new object[] { new TestType(), EdgeDetectionOperators.Robinson }, + new object[] { new TestType(), EdgeDetectionOperators.Scharr }, + new object[] { new TestType(), EdgeDetectionOperators.Sobel }, }; [Theory] @@ -71,4 +72,4 @@ public void DetectEdges_filter_grayscale_SobelProcessorDefaultsSet(T Assert.Equal(grey, processor.Grayscale); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Convolution/Processors/LaplacianKernelFactoryTests.cs b/tests/ImageSharp.Tests/Processing/Convolution/Processors/LaplacianKernelFactoryTests.cs index 8b3524fe66..6bb374203d 100644 --- a/tests/ImageSharp.Tests/Processing/Convolution/Processors/LaplacianKernelFactoryTests.cs +++ b/tests/ImageSharp.Tests/Processing/Convolution/Processors/LaplacianKernelFactoryTests.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. using System; @@ -23,11 +23,11 @@ public class LaplacianKernelFactoryTests private static readonly DenseMatrix Expected5x5Matrix = new DenseMatrix( new float[,] { - { -1, -1, -1,-1, -1 }, - { -1, -1, -1,-1, -1 }, - { -1, -1, 24,-1, -1 }, - { -1, -1, -1,-1, -1 }, - { -1, -1, -1,-1, -1 } + { -1, -1, -1, -1, -1 }, + { -1, -1, -1, -1, -1 }, + { -1, -1, 24, -1, -1 }, + { -1, -1, -1, -1, -1 }, + { -1, -1, -1, -1, -1 } }); [Fact] @@ -65,4 +65,4 @@ public void LaplacianKernelFactoryCreatesCorrect5x5Matrix() } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Dithering/DitherTest.cs b/tests/ImageSharp.Tests/Processing/Dithering/DitherTest.cs index 53a50468b4..bb84bd4b1a 100644 --- a/tests/ImageSharp.Tests/Processing/Dithering/DitherTest.cs +++ b/tests/ImageSharp.Tests/Processing/Dithering/DitherTest.cs @@ -19,10 +19,10 @@ public static void Equal(ReadOnlySpan a, ReadOnlySpan b) True(a.SequenceEqual(b)); } } - + private readonly IOrderedDither orderedDither; private readonly IErrorDiffuser errorDiffuser; - private readonly Color[] TestPalette = + private readonly Color[] testPalette = { Color.Red, Color.Green, @@ -52,25 +52,25 @@ public void Dither_rect_CorrectProcessor() Assert.Equal(this.orderedDither, p.Dither); Assert.Equal(Color.WebSafePalette, p.Palette); } + [Fact] public void Dither_index_CorrectProcessor() { - this.operations.Dither(this.orderedDither, this.TestPalette); + this.operations.Dither(this.orderedDither, this.testPalette); OrderedDitherPaletteProcessor p = this.Verify(); Assert.Equal(this.orderedDither, p.Dither); - Assert.Equal(this.TestPalette, p.Palette); + Assert.Equal(this.testPalette, p.Palette); } [Fact] public void Dither_index_rect_CorrectProcessor() { - this.operations.Dither(this.orderedDither, this.TestPalette, this.rect); + this.operations.Dither(this.orderedDither, this.testPalette, this.rect); OrderedDitherPaletteProcessor p = this.Verify(this.rect); Assert.Equal(this.orderedDither, p.Dither); - Assert.Equal(this.TestPalette, p.Palette); + Assert.Equal(this.testPalette, p.Palette); } - [Fact] public void Dither_ErrorDiffuser_CorrectProcessor() { @@ -94,21 +94,21 @@ public void Dither_ErrorDiffuser_rect_CorrectProcessor() [Fact] public void Dither_ErrorDiffuser_CorrectProcessorWithColors() { - this.operations.Diffuse(this.errorDiffuser, .5F, this.TestPalette); + this.operations.Diffuse(this.errorDiffuser, .5F, this.testPalette); ErrorDiffusionPaletteProcessor p = this.Verify(); Assert.Equal(this.errorDiffuser, p.Diffuser); Assert.Equal(.5F, p.Threshold); - Assert.Equal(this.TestPalette, p.Palette); + Assert.Equal(this.testPalette, p.Palette); } [Fact] public void Dither_ErrorDiffuser_rect_CorrectProcessorWithColors() { - this.operations.Diffuse(this.errorDiffuser, .5F, this.TestPalette, this.rect); + this.operations.Diffuse(this.errorDiffuser, .5F, this.testPalette, this.rect); ErrorDiffusionPaletteProcessor p = this.Verify(this.rect); Assert.Equal(this.errorDiffuser, p.Diffuser); Assert.Equal(.5F, p.Threshold); - Assert.Equal(this.TestPalette, p.Palette); + Assert.Equal(this.testPalette, p.Palette); } } } diff --git a/tests/ImageSharp.Tests/Processing/Effects/BackgroundColorTest.cs b/tests/ImageSharp.Tests/Processing/Effects/BackgroundColorTest.cs index a137a9f438..37bd2e87aa 100644 --- a/tests/ImageSharp.Tests/Processing/Effects/BackgroundColorTest.cs +++ b/tests/ImageSharp.Tests/Processing/Effects/BackgroundColorTest.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Effects { public class BackgroundColorTest : BaseImageOperationsExtensionTest { - private static readonly GraphicsOptionsComparer graphicsOptionsComparer = new GraphicsOptionsComparer(); + private static readonly GraphicsOptionsComparer GraphicsOptionsComparer = new GraphicsOptionsComparer(); [Fact] public void BackgroundColor_amount_BackgroundColorProcessorDefaultsSet() @@ -18,7 +18,7 @@ public void BackgroundColor_amount_BackgroundColorProcessorDefaultsSet() this.operations.BackgroundColor(Color.BlanchedAlmond); BackgroundColorProcessor processor = this.Verify(); - Assert.Equal(new GraphicsOptions(), processor.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), processor.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.BlanchedAlmond, processor.Color); } @@ -28,7 +28,7 @@ public void BackgroundColor_amount_rect_BackgroundColorProcessorDefaultsSet() this.operations.BackgroundColor(Color.BlanchedAlmond, this.rect); BackgroundColorProcessor processor = this.Verify(this.rect); - Assert.Equal(new GraphicsOptions(), processor.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), processor.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.BlanchedAlmond, processor.Color); } @@ -38,7 +38,7 @@ public void BackgroundColor_amount_options_BackgroundColorProcessorDefaultsSet() this.operations.BackgroundColor(this.options, Color.BlanchedAlmond); BackgroundColorProcessor processor = this.Verify(); - Assert.Equal(this.options, processor.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(this.options, processor.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.BlanchedAlmond, processor.Color); } @@ -48,7 +48,7 @@ public void BackgroundColor_amount_rect_options_BackgroundColorProcessorDefaults this.operations.BackgroundColor(this.options, Color.BlanchedAlmond, this.rect); BackgroundColorProcessor processor = this.Verify(this.rect); - Assert.Equal(this.options, processor.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(this.options, processor.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.BlanchedAlmond, processor.Color); } } diff --git a/tests/ImageSharp.Tests/Processing/Effects/OilPaintTest.cs b/tests/ImageSharp.Tests/Processing/Effects/OilPaintTest.cs index 18842e1f36..797423394e 100644 --- a/tests/ImageSharp.Tests/Processing/Effects/OilPaintTest.cs +++ b/tests/ImageSharp.Tests/Processing/Effects/OilPaintTest.cs @@ -28,6 +28,7 @@ public void OilPaint_rect_OilPaintingProcessorDefaultsSet() Assert.Equal(10, processor.Levels); Assert.Equal(15, processor.BrushSize); } + [Fact] public void OilPaint_Levels_Brush_OilPaintingProcessorDefaultsSet() { @@ -48,4 +49,4 @@ public void OilPaint_Levels_Brush_rect_OilPaintingProcessorDefaultsSet() Assert.Equal(43, processor.BrushSize); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs b/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs index aecac22c0a..1cc5ee4542 100644 --- a/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs +++ b/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs @@ -12,16 +12,18 @@ namespace SixLabors.ImageSharp.Tests.Processing { internal class FakeImageOperationsProvider : IImageProcessingContextFactory { - private List ImageOperators = new List(); + private readonly List imageOperators = new List(); public bool HasCreated(Image source) where TPixel : struct, IPixel { return this.Created(source).Any(); } - public IEnumerable> Created(Image source) where TPixel : struct, IPixel + + public IEnumerable> Created(Image source) + where TPixel : struct, IPixel { - return this.ImageOperators.OfType>() + return this.imageOperators.OfType>() .Where(x => x.Source == source); } @@ -36,7 +38,7 @@ public IInternalImageProcessingContext CreateImageProcessingContext { var op = new FakeImageOperations(configuration, source, mutate); - this.ImageOperators.Add(op); + this.imageOperators.Add(op); return op; } @@ -87,6 +89,7 @@ public IImageProcessingContext ApplyProcessor(IImageProcessor processor) public struct AppliedOperation { public Rectangle? Rectangle { get; set; } + public IImageProcessor GenericProcessor { get; set; } public IImageProcessor NonGenericProcessor { get; set; } diff --git a/tests/ImageSharp.Tests/Processing/Filters/ColorBlindnessTest.cs b/tests/ImageSharp.Tests/Processing/Filters/ColorBlindnessTest.cs index e287fb7b5f..70c78ec81a 100644 --- a/tests/ImageSharp.Tests/Processing/Filters/ColorBlindnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Filters/ColorBlindnessTest.cs @@ -4,8 +4,8 @@ using System.Collections.Generic; using SixLabors.ImageSharp.Processing; -using SixLabors.ImageSharp.Processing.Processors.Filters; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Processing.Processors.Filters; using SixLabors.ImageSharp.Tests.TestUtilities; using Xunit; @@ -14,15 +14,16 @@ namespace SixLabors.ImageSharp.Tests.Processing.Filters { public class ColorBlindnessTest : BaseImageOperationsExtensionTest { - public static IEnumerable TheoryData = new[] { - new object[]{ new TestType(), ColorBlindnessMode.Achromatomaly }, - new object[]{ new TestType(), ColorBlindnessMode.Achromatopsia }, - new object[]{ new TestType(), ColorBlindnessMode.Deuteranomaly }, - new object[]{ new TestType(), ColorBlindnessMode.Deuteranopia }, - new object[]{ new TestType(), ColorBlindnessMode.Protanomaly }, - new object[]{ new TestType(), ColorBlindnessMode.Protanopia }, - new object[]{ new TestType(), ColorBlindnessMode.Tritanomaly }, - new object[]{ new TestType(), ColorBlindnessMode.Tritanopia } + public static IEnumerable TheoryData = new[] + { + new object[] { new TestType(), ColorBlindnessMode.Achromatomaly }, + new object[] { new TestType(), ColorBlindnessMode.Achromatopsia }, + new object[] { new TestType(), ColorBlindnessMode.Deuteranomaly }, + new object[] { new TestType(), ColorBlindnessMode.Deuteranopia }, + new object[] { new TestType(), ColorBlindnessMode.Protanomaly }, + new object[] { new TestType(), ColorBlindnessMode.Protanopia }, + new object[] { new TestType(), ColorBlindnessMode.Tritanomaly }, + new object[] { new TestType(), ColorBlindnessMode.Tritanopia } }; [Theory] @@ -33,6 +34,7 @@ public void ColorBlindness_CorrectProcessor(TestType testType, ColorBlindn this.operations.ColorBlindness(colorBlindness); this.Verify(); } + [Theory] [MemberData(nameof(TheoryData))] public void ColorBlindness_rect_CorrectProcessor(TestType testType, ColorBlindnessMode colorBlindness) diff --git a/tests/ImageSharp.Tests/Processing/Filters/GrayscaleTest.cs b/tests/ImageSharp.Tests/Processing/Filters/GrayscaleTest.cs index 08de55d6b1..9afaf16fd4 100644 --- a/tests/ImageSharp.Tests/Processing/Filters/GrayscaleTest.cs +++ b/tests/ImageSharp.Tests/Processing/Filters/GrayscaleTest.cs @@ -4,8 +4,8 @@ using System.Collections.Generic; using SixLabors.ImageSharp.Processing; -using SixLabors.ImageSharp.Processing.Processors.Filters; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Processing.Processors.Filters; using SixLabors.ImageSharp.Tests.TestUtilities; using Xunit; @@ -14,8 +14,9 @@ namespace SixLabors.ImageSharp.Tests.Processing.Filters { public class GrayscaleTest : BaseImageOperationsExtensionTest { - public static IEnumerable ModeTheoryData = new[] { - new object[]{ new TestType(), GrayscaleMode.Bt709 } + public static IEnumerable ModeTheoryData = new[] + { + new object[] { new TestType(), GrayscaleMode.Bt709 } }; [Theory] diff --git a/tests/ImageSharp.Tests/Processing/ImageOperationTests.cs b/tests/ImageSharp.Tests/Processing/ImageOperationTests.cs index 86a0d14854..0638441783 100644 --- a/tests/ImageSharp.Tests/Processing/ImageOperationTests.cs +++ b/tests/ImageSharp.Tests/Processing/ImageOperationTests.cs @@ -32,13 +32,15 @@ public ImageOperationTests() var processorMock = new Mock(); this.processorDefinition = processorMock.Object; - this.image = new Image(new Configuration - { - ImageOperationsProvider = this.provider - }, 1, 1); + this.image = new Image( + new Configuration + { + ImageOperationsProvider = this.provider + }, + 1, + 1); } - [Fact] public void MutateCallsImageOperationsProvider_Func_OriginalImage() { diff --git a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs index 32da38621a..3ab6049953 100644 --- a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs +++ b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs @@ -120,9 +120,10 @@ public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImagePro /// where it could happen that one too much start position was calculated in some cases. /// See: https://github.com/SixLabors/ImageSharp/pull/984 /// + /// The pixel type of the image. [Theory] - [WithTestPatternImages(110, 110, PixelTypes.Rgb24)] - [WithTestPatternImages(170, 170, PixelTypes.Rgb24)] + [WithTestPatternImage(110, 110, PixelTypes.Rgb24)] + [WithTestPatternImage(170, 170, PixelTypes.Rgb24)] public void Issue984(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Overlays/GlowTest.cs b/tests/ImageSharp.Tests/Processing/Overlays/GlowTest.cs index 32c4c6fe74..4c00b32132 100644 --- a/tests/ImageSharp.Tests/Processing/Overlays/GlowTest.cs +++ b/tests/ImageSharp.Tests/Processing/Overlays/GlowTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Overlays { public class GlowTest : BaseImageOperationsExtensionTest { - private static readonly GraphicsOptionsComparer graphicsOptionsComparer = new GraphicsOptionsComparer(); + private static readonly GraphicsOptionsComparer GraphicsOptionsComparer = new GraphicsOptionsComparer(); [Fact] public void Glow_GlowProcessorWithDefaultValues() @@ -21,7 +21,7 @@ public void Glow_GlowProcessorWithDefaultValues() this.operations.Glow(); GlowProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.GlowColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.Radius); } @@ -32,7 +32,7 @@ public void Glow_Color_GlowProcessorWithDefaultValues() this.operations.Glow(Rgba32.Aquamarine); GlowProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Aquamarine, p.GlowColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.Radius); } @@ -43,7 +43,7 @@ public void Glow_Radux_GlowProcessorWithDefaultValues() this.operations.Glow(3.5f); GlowProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.GlowColor); Assert.Equal(ValueSize.Absolute(3.5f), p.Radius); } @@ -55,7 +55,7 @@ public void Glow_Rect_GlowProcessorWithDefaultValues() this.operations.Glow(rect); GlowProcessor p = this.Verify(rect); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.GlowColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.Radius); } diff --git a/tests/ImageSharp.Tests/Processing/Overlays/VignetteTest.cs b/tests/ImageSharp.Tests/Processing/Overlays/VignetteTest.cs index ebf4fee317..69e03d648b 100644 --- a/tests/ImageSharp.Tests/Processing/Overlays/VignetteTest.cs +++ b/tests/ImageSharp.Tests/Processing/Overlays/VignetteTest.cs @@ -12,7 +12,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Overlays { public class VignetteTest : BaseImageOperationsExtensionTest { - private static readonly GraphicsOptionsComparer graphicsOptionsComparer = new GraphicsOptionsComparer(); + private static readonly GraphicsOptionsComparer GraphicsOptionsComparer = new GraphicsOptionsComparer(); [Fact] public void Vignette_VignetteProcessorWithDefaultValues() @@ -20,7 +20,7 @@ public void Vignette_VignetteProcessorWithDefaultValues() this.operations.Vignette(); VignetteProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.VignetteColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.RadiusX); Assert.Equal(ValueSize.PercentageOfHeight(.5f), p.RadiusY); @@ -32,7 +32,7 @@ public void Vignette_Color_VignetteProcessorWithDefaultValues() this.operations.Vignette(Color.Aquamarine); VignetteProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Aquamarine, p.VignetteColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.RadiusX); Assert.Equal(ValueSize.PercentageOfHeight(.5f), p.RadiusY); @@ -44,7 +44,7 @@ public void Vignette_Radux_VignetteProcessorWithDefaultValues() this.operations.Vignette(3.5f, 12123f); VignetteProcessor p = this.Verify(); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.VignetteColor); Assert.Equal(ValueSize.Absolute(3.5f), p.RadiusX); Assert.Equal(ValueSize.Absolute(12123f), p.RadiusY); @@ -57,7 +57,7 @@ public void Vignette_Rect_VignetteProcessorWithDefaultValues() this.operations.Vignette(rect); VignetteProcessor p = this.Verify(rect); - Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, graphicsOptionsComparer); + Assert.Equal(new GraphicsOptions(), p.GraphicsOptions, GraphicsOptionsComparer); Assert.Equal(Color.Black, p.VignetteColor); Assert.Equal(ValueSize.PercentageOfWidth(.5f), p.RadiusX); Assert.Equal(ValueSize.PercentageOfHeight(.5f), p.RadiusY); diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs index d3507ed4c4..3fe624498a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.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. using SixLabors.ImageSharp.PixelFormats; @@ -8,8 +8,8 @@ using SixLabors.Primitives; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Processing.Processors.Binarization { public class BinaryDitherTests @@ -48,7 +48,7 @@ public class BinaryDitherTests [Theory] [WithFileCollection(nameof(CommonTestImages), nameof(OrderedDitherers), PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(OrderedDitherers), 100, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(OrderedDitherers), 100, 100, PixelTypes.Rgba32)] public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider provider, string name, IOrderedDither ditherer) where TPixel : struct, IPixel { @@ -61,7 +61,7 @@ public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider(TestImageProvider provider, string name, IErrorDiffuser diffuser) where TPixel : struct, IPixel { @@ -130,4 +130,4 @@ public void ApplyDiffusionFilterInBox(TestImageProvider provider } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs index 4ae5d60513..dd999757db 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -19,12 +19,12 @@ public static readonly TheoryData BinaryThresholdValues .25F, .75F }; - + public static readonly string[] CommonTestImages = { TestImages.Png.CalliphoraPartial, TestImages.Png.Bike }; - + public const PixelTypes TestPixelTypes = PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24; [Theory] @@ -44,17 +44,16 @@ public void ImageShouldApplyBinaryThresholdFilter(TestImageProvider(TestImageProvider provider, float value) where TPixel : struct, IPixel { - using (Image source = provider.GetImage()) using (var image = source.Clone()) { var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); image.Mutate(x => x.BinaryThreshold(value, bounds)); - image.DebugSave(provider, value); + image.DebugSave(provider, value); ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/Basic1ParameterConvolutionTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/Basic1ParameterConvolutionTests.cs index 0a10d0755f..5b12f898a5 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/Basic1ParameterConvolutionTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/Basic1ParameterConvolutionTests.cs @@ -1,5 +1,5 @@ -// // Copyright (c) Six Labors and contributors. -// // Licensed under the Apache License, Version 2.0. +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; @@ -14,9 +14,9 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution public abstract class Basic1ParameterConvolutionTests { private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.05F); - + public static readonly TheoryData Values = new TheoryData { 3, 5 }; - + public static readonly string[] InputImages = { TestImages.Bmp.Car, @@ -48,7 +48,7 @@ public void InBox(TestImageProvider provider, int value) } protected abstract void Apply(IImageProcessingContext ctx, int value); - + protected abstract void Apply(IImageProcessingContext ctx, int value, Rectangle bounds); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs index cf97ae4af5..e9baee6bd7 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs @@ -120,9 +120,9 @@ public void Serialize(IXunitSerializationInfo info) [Theory] [WithFileCollection(nameof(TestFiles), nameof(BokehBlurValues), PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BokehBlurValues), 50, 50, "Red", PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BokehBlurValues), 200, 100, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BokehBlurValues), 23, 31, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(BokehBlurValues), 30, 20, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BokehBlurValues), 200, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BokehBlurValues), 23, 31, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BokehBlurValues), 30, 20, PixelTypes.Rgba32)] public void BokehBlurFilterProcessor(TestImageProvider provider, BokehBlurInfo value) where TPixel : struct, IPixel { @@ -133,9 +133,11 @@ public void BokehBlurFilterProcessor(TestImageProvider provider, } [Theory] - // TODO: Re-enable L8 when we update the reference images. - // [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32 | PixelTypes.L8)] - [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32)] + /* + TODO: Re-enable L8 when we update the reference images. + [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32 | PixelTypes.L8)] + */ + [WithTestPatternImage(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32)] public void BokehBlurFilterProcessor_WorksWithAllPixelTypes(TestImageProvider provider) where TPixel : struct, IPixel { @@ -144,7 +146,6 @@ public void BokehBlurFilterProcessor_WorksWithAllPixelTypes(TestImagePro appendSourceFileOrDescription: false); } - [Theory] [WithFileCollection(nameof(TestFiles), nameof(BokehBlurValues), PixelTypes.Rgba32)] public void BokehBlurFilterProcessor_Bounded(TestImageProvider provider, BokehBlurInfo value) diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs index 05524b20b0..2396f6ee25 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -6,8 +6,8 @@ using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using SixLabors.Primitives; using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution { [GroupOutput("Convolution")] @@ -18,7 +18,7 @@ public class DetectEdgesTest private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.0456F); public static readonly string[] TestImages = { Tests.TestImages.Png.Bike }; - + public const PixelTypes CommonNonDefaultPixelTypes = PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.RgbaVector; public static readonly TheoryData DetectEdgesFilters = new TheoryData @@ -52,7 +52,7 @@ public void DetectEdges_WorksOnWrappedMemoryImage(TestImageProvider(TestImageProvider provider, EdgeDetectionOperators detector) where TPixel : struct, IPixel @@ -105,4 +105,4 @@ public void DetectEdges_InBox(TestImageProvider provider) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Dithering/DitherTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Dithering/DitherTests.cs index 5d65a9e61d..78481acd2b 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Dithering/DitherTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Dithering/DitherTests.cs @@ -14,7 +14,7 @@ public class DitherTests { public const PixelTypes CommonNonDefaultPixelTypes = PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24 | PixelTypes.RgbaVector; - + public static readonly string[] CommonTestImages = { TestImages.Png.CalliphoraPartial, TestImages.Png.Bike }; public static readonly TheoryData ErrorDiffusers = new TheoryData @@ -37,8 +37,9 @@ public class DitherTests KnownDitherers.OrderedDither3x3, KnownDitherers.BayerDither2x2 }; + private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.05f); - + private static IOrderedDither DefaultDitherer => KnownDitherers.BayerDither4x4; private static IErrorDiffuser DefaultErrorDiffuser => KnownDiffusers.Atkinson; @@ -59,7 +60,7 @@ public void ApplyDiffusionFilterInBox(TestImageProvider provider { return; } - + provider.RunRectangleConstrainedValidatingProcessorTest( (x, rect) => x.Diffuse(DefaultErrorDiffuser, .5F, rect), comparer: ValidatorComparer); @@ -74,7 +75,7 @@ public void ApplyDitherFilterInBox(TestImageProvider provider) { return; } - + provider.RunRectangleConstrainedValidatingProcessorTest( (x, rect) => x.Dither(DefaultDitherer, rect), comparer: ValidatorComparer); @@ -89,7 +90,7 @@ public void DiffusionFilter_ShouldNotDependOnSinglePixelType(TestImagePr { return; } - + // Increased tolerance because of compatibility issues on .NET 4.6.2: var comparer = ImageComparer.TolerantPercentage(1f); provider.RunValidatingProcessorTest(x => x.Diffuse(DefaultErrorDiffuser, 0.5f), comparer: comparer); @@ -106,7 +107,7 @@ public void DiffusionFilter_WorksWithAllErrorDiffusers( { return; } - + provider.RunValidatingProcessorTest( x => x.Diffuse(diffuser, 0.5f), testOutputDetails: diffuser.GetType().Name, @@ -123,7 +124,7 @@ public void DitherFilter_ShouldNotDependOnSinglePixelType(TestImageProvi { return; } - + provider.RunValidatingProcessorTest( x => x.Dither(DefaultDitherer), comparer: ValidatorComparer); @@ -140,7 +141,7 @@ public void DitherFilter_WorksWithAllDitherers( { return; } - + provider.RunValidatingProcessorTest( x => x.Dither(ditherer), testOutputDetails: ditherer.GetType().Name, diff --git a/tests/ImageSharp.Tests/Processing/Processors/Effects/BackgroundColorTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Effects/BackgroundColorTest.cs index 56ffceb47a..a0ee576821 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Effects/BackgroundColorTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Effects/BackgroundColorTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -16,13 +16,13 @@ public class BackgroundColorTest TestImages.Png.Splash, TestImages.Png.Ducky }; - + [Theory] [WithFileCollection(nameof(InputImages), PixelTypes.Rgba32)] public void FullImage(TestImageProvider provider) where TPixel : struct, IPixel { - provider.RunValidatingProcessorTest(x => x.BackgroundColor(Color.HotPink)); + provider.RunValidatingProcessorTest(x => x.BackgroundColor(Color.HotPink)); } [Theory] @@ -34,4 +34,4 @@ public void InBox(TestImageProvider provider) (x, rect) => x.BackgroundColor(Color.HotPink, rect)); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs index aad48e357a..579663cf44 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs @@ -13,9 +13,10 @@ public class OilPaintTest { public static readonly TheoryData OilPaintValues = new TheoryData { - { 15, 10 }, + { 15, 10 }, { 6, 5 } }; + public static readonly string[] InputImages = { TestImages.Png.CalliphoraPartial, @@ -35,7 +36,7 @@ public void FullImage(TestImageProvider provider, int levels, in [Theory] [WithFileCollection(nameof(InputImages), nameof(OilPaintValues), PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(OilPaintValues), 100, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(OilPaintValues), 100, 100, PixelTypes.Rgba32)] public void InBox(TestImageProvider provider, int levels, int brushSize) where TPixel : struct, IPixel { @@ -44,4 +45,4 @@ public void InBox(TestImageProvider provider, int levels, int br $"{levels}-{brushSize}"); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs index e95452ffb7..d4e4d749b6 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs @@ -22,7 +22,7 @@ public void FullImage(TestImageProvider provider, int value) } [Theory] - [WithTestPatternImages(nameof(PixelateValues), 320, 240, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(PixelateValues), 320, 240, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, nameof(PixelateValues), PixelTypes.Rgba32)] public void InBox(TestImageProvider provider, int value) where TPixel : struct, IPixel diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs index 64aeae0534..4cf4e5144a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs @@ -14,7 +14,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class BlackWhiteTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyBlackWhiteFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs index 54a8dd4b7d..8434ce7d7a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -19,12 +19,12 @@ public static readonly TheoryData BrightnessValues = new TheoryData { .5F, - 1.5F + 1.5F }; [Theory] - [WithTestPatternImages(nameof(BrightnessValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(BrightnessValues), 48, 48, PixelTypes.Rgba32)] public void ApplyBrightnessFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(ctx => ctx.Brightness(value), value, this.imageComparer); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs index 8ac56655ea..b075e73d3c 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs @@ -29,7 +29,7 @@ public static readonly TheoryData ColorBlindnessFilters }; [Theory] - [WithTestPatternImages(nameof(ColorBlindnessFilters), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(ColorBlindnessFilters), 48, 48, PixelTypes.Rgba32)] public void ApplyColorBlindnessFilter(TestImageProvider provider, ColorBlindnessMode colorBlindness) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(x => x.ColorBlindness(colorBlindness), colorBlindness.ToString(), this.imageComparer); } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs index e5e4fa4a90..3c734769de 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -16,15 +16,15 @@ public static readonly TheoryData ContrastValues = new TheoryData { .5F, - 1.5F + 1.5F }; [Theory] - [WithTestPatternImages(nameof(ContrastValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(ContrastValues), 48, 48, PixelTypes.Rgba32)] public void ApplyContrastFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { provider.RunValidatingProcessorTest(x => x.Contrast(value), value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs index 68daa80eac..9ef4d40e9b 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -18,7 +18,7 @@ public class FilterTest // Testing the generic FilterProcessor with more than one pixel type intentionally. // There is no need to do this with the specialized ones. [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void ApplyFilter(TestImageProvider provider) where TPixel : struct, IPixel { @@ -28,7 +28,7 @@ public void ApplyFilter(TestImageProvider provider) } [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { @@ -44,6 +44,5 @@ private static ColorMatrix CreateCombinedTestFilterMatrix() ColorMatrix saturation = KnownFilterMatrices.CreateSaturateFilter(1.5F); return brightness * hue * saturation; } - } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs index c2728e0435..e8535bc836 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -22,12 +22,13 @@ public static readonly TheoryData GrayscaleModeTypes /// /// Use test patterns over loaded images to save decode time. /// + /// The pixel type of the image. [Theory] - [WithTestPatternImages(nameof(GrayscaleModeTypes), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(GrayscaleModeTypes), 48, 48, PixelTypes.Rgba32)] public void ApplyGrayscaleFilter(TestImageProvider provider, GrayscaleMode value) where TPixel : struct, IPixel { provider.RunValidatingProcessorTest(x => x.Grayscale(value), value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs index 4ce700bad0..b99ae38d5d 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -16,15 +16,15 @@ public static readonly TheoryData HueValues = new TheoryData { 180, - -180 + -180 }; [Theory] - [WithTestPatternImages(nameof(HueValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(HueValues), 48, 48, PixelTypes.Rgba32)] public void ApplyHueFilter(TestImageProvider provider, int value) where TPixel : struct, IPixel { provider.RunValidatingProcessorTest(x => x.Hue(value), value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs index 1b4c70646a..4889a1a630 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Effects public class InvertTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyInvertFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs index b7b635c2d2..4d6f163298 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class KodachromeTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyKodachromeFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs index c330ed6d9a..39b1aa1c1f 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs @@ -19,11 +19,11 @@ public static readonly TheoryData LightnessValues = new TheoryData { .5F, - 1.5F + 1.5F }; [Theory] - [WithTestPatternImages(nameof(LightnessValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(LightnessValues), 48, 48, PixelTypes.Rgba32)] public void ApplyLightnessFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(ctx => ctx.Lightness(value), value, this.imageComparer); } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs index 013ec38740..e366a86aad 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class LomographTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyLomographFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs index 35e405f4c9..7e6bf49c58 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -15,16 +15,16 @@ public class OpacityTest public static readonly TheoryData AlphaValues = new TheoryData { - 20/100F, - 80/100F + 20 / 100F, + 80 / 100F }; [Theory] - [WithTestPatternImages(nameof(AlphaValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(AlphaValues), 48, 48, PixelTypes.Rgba32)] public void ApplyAlphaFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { provider.RunValidatingProcessorTest(x => x.Opacity(value), value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs index 3b39542a55..6ac3009ad1 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class PolaroidTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplyPolaroidFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs index 31fab8b65d..943f432a8c 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.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. using SixLabors.ImageSharp.PixelFormats; @@ -16,15 +16,15 @@ public static readonly TheoryData SaturationValues = new TheoryData { .5F, - 1.5F, + 1.5F, }; [Theory] - [WithTestPatternImages(nameof(SaturationValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(SaturationValues), 48, 48, PixelTypes.Rgba32)] public void ApplySaturationFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { provider.RunValidatingProcessorTest(x => x.Saturate(value), value); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs index b7d381f5f2..7c88859138 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class SepiaTest { [Theory] - [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] public void ApplySepiaFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs index ceb6f8363b..68852a939a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs @@ -21,8 +21,8 @@ public static readonly TheoryData InvalidOrientationValues { { ExifDataType.Byte, new byte[] { 1 } }, { ExifDataType.SignedByte, new byte[] { 2 } }, - { ExifDataType.SignedShort, BitConverter.GetBytes((short) 3) }, - { ExifDataType.Long, BitConverter.GetBytes((uint) 4) }, + { ExifDataType.SignedShort, BitConverter.GetBytes((short)3) }, + { ExifDataType.Long, BitConverter.GetBytes(4U) }, { ExifDataType.SignedLong, BitConverter.GetBytes(5) } }; @@ -64,11 +64,14 @@ public void AutoOrient_WorksWithCorruptExifData(TestImageProvider(TestImageProvider provider, int x, int y, int w, int h) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs index 3c932bfaa6..c82ca891fc 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.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. using SixLabors.ImageSharp.PixelFormats; @@ -7,7 +7,6 @@ using Xunit; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms { [GroupOutput("Transforms")] @@ -22,9 +21,9 @@ public class FlipTests }; [Theory] - [WithTestPatternImages(nameof(FlipValues), 20, 37, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(FlipValues), 20, 37, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] public void Flip(TestImageProvider provider, FlipMode flipMode) where TPixel : struct, IPixel { @@ -35,8 +34,8 @@ public void Flip(TestImageProvider provider, FlipMode flipMode) } [Theory] - [WithTestPatternImages(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] public void Flip_WorksOnWrappedMemoryImage(TestImageProvider provider, FlipMode flipMode) where TPixel : struct, IPixel { @@ -47,4 +46,4 @@ public void Flip_WorksOnWrappedMemoryImage(TestImageProvider pro appendPixelTypeToFileName: false); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResamplerTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResamplerTests.cs index b7b4597c79..d3025d9118 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResamplerTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResamplerTests.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms { public class ResamplerTests - { + { [Theory] [InlineData(-2, 0)] [InlineData(-1, 0)] @@ -66,4 +66,4 @@ public static void TriangleWindowOscillatesCorrectly(float x, float expected) Assert.Equal(result, expected); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.ReferenceKernelMap.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.ReferenceKernelMap.cs index 1681c3046a..beb7ebc9c3 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.ReferenceKernelMap.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.ReferenceKernelMap.cs @@ -39,7 +39,7 @@ public static ReferenceKernelMap Calculate(IResampler sampler, int destinationSi TolerantMath tolerantMath = TolerantMath.Default; double radius = tolerantMath.Ceiling(scale * sampler.Radius); - + var result = new List(); for (int i = 0; i < destinationSize; i++) @@ -61,7 +61,7 @@ public static ReferenceKernelMap Calculate(IResampler sampler, int destinationSi double sum = 0; - var values = new double[right - left + 1]; + double[] values = new double[right - left + 1]; for (int j = left; j <= right; j++) { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.cs index 91b011ed6a..08745d5701 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeKernelMapTests.cs @@ -35,9 +35,7 @@ public ResizeKernelMapTests(ITestOutputHelper output) { nameof(KnownResamplers.Bicubic), 500, 200 }, { nameof(KnownResamplers.Bicubic), 200, 500 }, { nameof(KnownResamplers.Bicubic), 3032, 400 }, - { nameof(KnownResamplers.Bicubic), 10, 25 }, - { nameof(KnownResamplers.Lanczos3), 16, 12 }, { nameof(KnownResamplers.Lanczos3), 12, 16 }, { nameof(KnownResamplers.Lanczos3), 12, 9 }, @@ -45,15 +43,12 @@ public ResizeKernelMapTests(ITestOutputHelper output) { nameof(KnownResamplers.Lanczos3), 6, 8 }, { nameof(KnownResamplers.Lanczos3), 8, 6 }, { nameof(KnownResamplers.Lanczos3), 20, 12 }, - { nameof(KnownResamplers.Lanczos3), 5, 25 }, { nameof(KnownResamplers.Lanczos3), 5, 50 }, - { nameof(KnownResamplers.Lanczos3), 25, 5 }, { nameof(KnownResamplers.Lanczos3), 50, 5 }, { nameof(KnownResamplers.Lanczos3), 49, 5 }, { nameof(KnownResamplers.Lanczos3), 31, 5 }, - { nameof(KnownResamplers.Lanczos8), 500, 200 }, { nameof(KnownResamplers.Lanczos8), 100, 10 }, { nameof(KnownResamplers.Lanczos8), 100, 80 }, @@ -70,13 +65,10 @@ public ResizeKernelMapTests(ITestOutputHelper output) { nameof(KnownResamplers.Box), 299, 10 }, { nameof(KnownResamplers.Box), 301, 300 }, { nameof(KnownResamplers.Box), 1180, 480 }, - { nameof(KnownResamplers.Lanczos2), 3264, 3032 }, - { nameof(KnownResamplers.Bicubic), 1280, 2240 }, { nameof(KnownResamplers.Bicubic), 1920, 1680 }, { nameof(KnownResamplers.Bicubic), 3072, 2240 }, - { nameof(KnownResamplers.Welch), 300, 2008 }, // ResizeKernel.Length -related regression tests cherry-picked from GeneratedImageResizeData @@ -91,10 +83,7 @@ public ResizeKernelMapTests(ITestOutputHelper output) public static TheoryData GeneratedImageResizeData = GenerateImageResizeData(); - - [Theory( - Skip = "Only for debugging and development" - )] + [Theory(Skip = "Only for debugging and development")] [MemberData(nameof(KernelMapData))] public void PrintNonNormalizedKernelMap(string resamplerName, int srcSize, int destSize) { @@ -131,8 +120,6 @@ private void VerifyKernelMapContentIsCorrect(string resamplerName, int srcSize, var referenceMap = ReferenceKernelMap.Calculate(resampler, destSize, srcSize); var kernelMap = ResizeKernelMap.Calculate(resampler, destSize, srcSize, Configuration.Default.MemoryAllocator); - - #if DEBUG this.Output.WriteLine(kernelMap.Info); this.Output.WriteLine($"Expected KernelMap:\n{PrintKernelMap(referenceMap)}\n"); @@ -157,8 +144,6 @@ private void VerifyKernelMapContentIsCorrect(string resamplerName, int srcSize, Assert.Equal(expectedValues.Length, actualValues.Length); - - for (int x = 0; x < expectedValues.Length; x++) { Assert.True( @@ -207,7 +192,6 @@ private static string PrintKernelMap( return bld.ToString(); } - private static TheoryData GenerateImageResizeData() { var result = new TheoryData(); diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs index c683a51dc4..6dd2b4293e 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs @@ -17,7 +17,6 @@ using Xunit; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms { public class ResizeTests @@ -39,7 +38,6 @@ public class ResizeTests nameof(KnownResamplers.Lanczos5), }; - private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.07F); [Fact] @@ -47,7 +45,7 @@ public void Resize_PixelAgnostic() { var filePath = TestFile.GetInputFileFullPath(TestImages.Jpeg.Baseline.Calliphora); - using (Image image = Image.Load(filePath)) + using (var image = Image.Load(filePath)) { image.Mutate(x => x.Resize(image.Size() / 2)); string path = System.IO.Path.Combine( @@ -59,9 +57,9 @@ public void Resize_PixelAgnostic() } [Theory(Skip = "Debug only, enable manually")] - [WithTestPatternImages(4000, 4000, PixelTypes.Rgba32, 300, 1024)] - [WithTestPatternImages(3032, 3032, PixelTypes.Rgba32, 400, 1024)] - [WithTestPatternImages(3032, 3032, PixelTypes.Rgba32, 400, 128)] + [WithTestPatternImage(4000, 4000, PixelTypes.Rgba32, 300, 1024)] + [WithTestPatternImage(3032, 3032, PixelTypes.Rgba32, 400, 1024)] + [WithTestPatternImage(3032, 3032, PixelTypes.Rgba32, 400, 128)] public void LargeImage(TestImageProvider provider, int destSize, int workingBufferSizeHintInKilobytes) where TPixel : struct, IPixel { @@ -90,8 +88,6 @@ public void Resize_BasicSmall(TestImageProvider provider, int wN // [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] means: // resizing: (15, 12) -> (10, 6) // kernel dimensions: (3, 4) - - using (Image image = provider.GetImage()) { var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); @@ -105,13 +101,13 @@ public void Resize_BasicSmall(TestImageProvider provider, int wN private static readonly int SizeOfVector4 = Unsafe.SizeOf(); [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 50)] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 60)] - [WithTestPatternImages(100, 400, PixelTypes.Rgba32, 110)] - [WithTestPatternImages(79, 97, PixelTypes.Rgba32, 73)] - [WithTestPatternImages(79, 97, PixelTypes.Rgba32, 5)] - [WithTestPatternImages(47, 193, PixelTypes.Rgba32, 73)] - [WithTestPatternImages(23, 211, PixelTypes.Rgba32, 31)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 50)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 60)] + [WithTestPatternImage(100, 400, PixelTypes.Rgba32, 110)] + [WithTestPatternImage(79, 97, PixelTypes.Rgba32, 73)] + [WithTestPatternImage(79, 97, PixelTypes.Rgba32, 5)] + [WithTestPatternImage(47, 193, PixelTypes.Rgba32, 73)] + [WithTestPatternImage(23, 211, PixelTypes.Rgba32, 31)] public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( TestImageProvider provider, int workingBufferLimitInRows) @@ -161,7 +157,7 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( } [Theory] - [WithTestPatternImages(100, 100, DefaultPixelType)] + [WithTestPatternImage(100, 100, DefaultPixelType)] public void Resize_Compand(TestImageProvider provider) where TPixel : struct, IPixel { @@ -180,7 +176,7 @@ public void Resize_Compand(TestImageProvider provider) public void Resize_DoesNotBleedAlphaPixels(TestImageProvider provider, bool compand) where TPixel : struct, IPixel { - string details = compand ? "Compand" : ""; + string details = compand ? "Compand" : string.Empty; provider.RunValidatingProcessorTest( x => x.Resize(x.GetCurrentSize() / 2, compand), @@ -204,7 +200,7 @@ public void Resize_IsAppliedToAllFrames(TestImageProvider provid } [Theory] - [WithTestPatternImages(50, 50, CommonNonDefaultPixelTypes)] + [WithTestPatternImage(50, 50, CommonNonDefaultPixelTypes)] public void Resize_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { @@ -266,12 +262,12 @@ public void Resize_WorksWithAllParallelismLevels( 1.8f, null, null)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 0.5f, null, null)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 1f, null, null)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 50, 50, DefaultPixelType, 8f, null, null)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 201, 199, DefaultPixelType, null, 100, 99)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 301, 1180, DefaultPixelType, null, 300, 480)] - [WithTestPatternImages(nameof(SmokeTestResamplerNames), 49, 80, DefaultPixelType, null, 301, 100)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 0.5f, null, null)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 1f, null, null)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 50, 50, DefaultPixelType, 8f, null, null)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 201, 199, DefaultPixelType, null, 100, 99)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 301, 1180, DefaultPixelType, null, 300, 480)] + [WithTestPatternImage(nameof(SmokeTestResamplerNames), 49, 80, DefaultPixelType, null, 301, 100)] public void Resize_WorksWithAllResamplers( TestImageProvider provider, string samplerName, @@ -370,7 +366,7 @@ public void ResizeHeightAndKeepAspect(TestImageProvider provider } [Theory] - [WithTestPatternImages(10, 100, DefaultPixelType)] + [WithTestPatternImage(10, 100, DefaultPixelType)] public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { @@ -397,7 +393,7 @@ public void ResizeWidthAndKeepAspect(TestImageProvider provider) } [Theory] - [WithTestPatternImages(100, 10, DefaultPixelType)] + [WithTestPatternImage(100, 10, DefaultPixelType)] public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs index 1e08836c13..1606a7f7bb 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs @@ -24,8 +24,8 @@ public static readonly TheoryData RotateFlipValues }; [Theory] - [WithTestPatternImages(nameof(RotateFlipValues), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(RotateFlipValues), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateFlipValues), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateFlipValues), 50, 100, PixelTypes.Rgba32)] public void RotateFlip(TestImageProvider provider, RotateMode rotateType, FlipMode flipType) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs index 7801c71432..72619f2dc9 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs @@ -26,8 +26,8 @@ public static readonly TheoryData RotateEnumValues }; [Theory] - [WithTestPatternImages(nameof(RotateAngles), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(RotateAngles), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateAngles), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateAngles), 50, 100, PixelTypes.Rgba32)] public void Rotate_WithAngle(TestImageProvider provider, float value) where TPixel : struct, IPixel { @@ -35,8 +35,8 @@ public void Rotate_WithAngle(TestImageProvider provider, float v } [Theory] - [WithTestPatternImages(nameof(RotateEnumValues), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImages(nameof(RotateEnumValues), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateEnumValues), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(RotateEnumValues), 50, 100, PixelTypes.Rgba32)] public void Rotate_WithRotateTypeEnum(TestImageProvider provider, RotateMode value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs index ad77027f0f..631cb84246 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs @@ -43,7 +43,7 @@ public class SkewTests private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.01f); [Theory] - [WithTestPatternImages(nameof(SkewValues), 100, 50, CommonPixelTypes)] + [WithTestPatternImage(nameof(SkewValues), 100, 50, CommonPixelTypes)] public void Skew_IsNotBoundToSinglePixelType(TestImageProvider provider, float x, float y) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs index ed6d3ef2bc..38839e44a1 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Numerics; using System.Reflection; using SixLabors.ImageSharp.Advanced; @@ -15,7 +18,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms { public class AffineTransformTests { - private readonly ITestOutputHelper Output; + private readonly ITestOutputHelper output; // 1 byte difference on one color component. private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.0134F, 3); @@ -66,11 +69,12 @@ public static readonly TheoryData TransformVa nameof(KnownResamplers.Lanczos8), }; - public AffineTransformTests(ITestOutputHelper output) => this.Output = output; + public AffineTransformTests(ITestOutputHelper output) => this.output = output; /// /// The output of an "all white" image should be "all white" or transparent, regardless of the transformation and the resampler. /// + /// The pixel type of the image. [Theory] [WithSolidFilledImages(nameof(Transform_DoesNotCreateEdgeArtifacts_ResamplerNames), 5, 5, 255, 255, 255, 255, PixelTypes.Rgba32)] public void Transform_DoesNotCreateEdgeArtifacts(TestImageProvider provider, string resamplerName) @@ -90,12 +94,14 @@ public void Transform_DoesNotCreateEdgeArtifacts(TestImageProvider( TestImageProvider provider, float angleDeg, - float sx, float sy, - float tx, float ty) + float sx, + float sy, + float tx, + float ty) where TPixel : struct, IPixel { using (Image image = provider.GetImage()) @@ -117,7 +123,7 @@ public void Transform_RotateScaleTranslate( } [Theory] - [WithTestPatternImages(96, 96, PixelTypes.Rgba32, 50, 0.8f)] + [WithTestPatternImage(96, 96, PixelTypes.Rgba32, 50, 0.8f)] public void Transform_RotateScale_ManuallyCentered(TestImageProvider provider, float angleDeg, float s) where TPixel : struct, IPixel { @@ -142,15 +148,16 @@ public void Transform_RotateScale_ManuallyCentered(TestImageProvider /// Testing transforms using custom source rectangles: /// https://github.com/SixLabors/ImageSharp/pull/386#issuecomment-357104963 /// + /// The pixel type of the image. [Theory] - [WithTestPatternImages(96, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(96, 48, PixelTypes.Rgba32)] public void Transform_FromSourceRectangle1(TestImageProvider provider) where TPixel : struct, IPixel { @@ -170,7 +177,7 @@ public void Transform_FromSourceRectangle1(TestImageProvider pro } [Theory] - [WithTestPatternImages(96, 48, PixelTypes.Rgba32)] + [WithTestPatternImage(96, 48, PixelTypes.Rgba32)] public void Transform_FromSourceRectangle2(TestImageProvider provider) where TPixel : struct, IPixel { @@ -189,7 +196,7 @@ public void Transform_FromSourceRectangle2(TestImageProvider pro } [Theory] - [WithTestPatternImages(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] public void Transform_WithSampler(TestImageProvider provider, string resamplerName) where TPixel : struct, IPixel { @@ -240,7 +247,7 @@ private static void VerifyAllPixelsAreWhiteOrTransparent(Image i private void PrintMatrix(Matrix3x2 a) { string s = $"{a.M11:F10},{a.M12:F10},{a.M21:F10},{a.M22:F10},{a.M31:F10},{a.M32:F10}"; - this.Output.WriteLine(s); + this.output.WriteLine(s); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Transforms/FlipTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/FlipTests.cs index 7bb155f3a9..59d226ef5b 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/FlipTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/FlipTests.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. using Xunit; @@ -10,7 +10,6 @@ namespace SixLabors.ImageSharp.Tests.Processing.Transforms public class FlipTests : BaseImageOperationsExtensionTest { - [Theory] [InlineData(FlipMode.None)] [InlineData(FlipMode.Horizontal)] diff --git a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs index 3679180f49..5c68247a7d 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs @@ -10,8 +10,8 @@ using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using Xunit; using Xunit.Abstractions; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.Processing.Transforms { public class ProjectiveTransformTests @@ -45,25 +45,21 @@ public class ProjectiveTransformTests { TaperSide.Bottom, TaperCorner.Both }, { TaperSide.Bottom, TaperCorner.LeftOrTop }, { TaperSide.Bottom, TaperCorner.RightOrBottom }, - { TaperSide.Top, TaperCorner.Both }, { TaperSide.Top, TaperCorner.LeftOrTop }, { TaperSide.Top, TaperCorner.RightOrBottom }, - { TaperSide.Left, TaperCorner.Both }, { TaperSide.Left, TaperCorner.LeftOrTop }, { TaperSide.Left, TaperCorner.RightOrBottom }, - { TaperSide.Right, TaperCorner.Both }, { TaperSide.Right, TaperCorner.LeftOrTop }, { TaperSide.Right, TaperCorner.RightOrBottom }, - }; public ProjectiveTransformTests(ITestOutputHelper output) => this.Output = output; [Theory] - [WithTestPatternImages(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] + [WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] public void Transform_WithSampler(TestImageProvider provider, string resamplerName) where TPixel : struct, IPixel { @@ -132,11 +128,13 @@ public void PerspectiveTransformMatchesCSS(TestImageProvider pro // https://github.com/SixLabors/ImageSharp/issues/787 using (Image image = provider.GetImage()) { +#pragma warning disable SA1117 // Parameters should be on same line or separate lines var matrix = new Matrix4x4( 0.260987f, -0.434909f, 0, -0.0022184f, 0.373196f, 0.949882f, 0, -0.000312129f, 0, 0, 1, 0, 52, 165, 0, 1); +#pragma warning restore SA1117 // Parameters should be on same line or separate lines ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() .AppendMatrix(matrix); diff --git a/tests/ImageSharp.Tests/Processing/Transforms/TransformBuilderTestBase.cs b/tests/ImageSharp.Tests/Processing/Transforms/TransformBuilderTestBase.cs index 71e3b71797..dbbb2500e7 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/TransformBuilderTestBase.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/TransformBuilderTestBase.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. using System; @@ -26,7 +26,9 @@ public abstract class TransformBuilderTestBase [Theory] [MemberData(nameof(ScaleTranslate_Data))] +#pragma warning disable SA1300 // Element should begin with upper-case letter public void _1Scale_2Translate(Vector2 scale, Vector2 translate, Vector2 source, Vector2 expectedDest) +#pragma warning restore SA1300 // Element should begin with upper-case letter { // These operations should be size-agnostic: var size = new Size(123, 321); @@ -50,7 +52,9 @@ public void _1Scale_2Translate(Vector2 scale, Vector2 translate, Vector2 source, [Theory] [MemberData(nameof(TranslateScale_Data))] +#pragma warning disable SA1300 // Element should begin with upper-case letter public void _1Translate_2Scale(Vector2 translate, Vector2 scale, Vector2 source, Vector2 expectedDest) +#pragma warning restore SA1300 // Element should begin with upper-case letter { // Translate ans scale are size-agnostic: var size = new Size(456, 432); @@ -272,4 +276,4 @@ public void ThrowsForInvalidSizes(int width, int height) protected abstract Vector2 Execute(TBuilder builder, Rectangle rectangle, Vector2 sourcePoint); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/JpegProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/JpegProfilingBenchmarks.cs index 95a47fd7cc..d0158e5019 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/JpegProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/JpegProfilingBenchmarks.cs @@ -64,8 +64,10 @@ private void DecodeJpegBenchmarkImpl(string fileName, IImageDecoder decoder) var img = Image.Load(bytes, decoder); img.Dispose(); }, - // ReSharper disable once ExplicitCallerInfoArgument +#pragma warning disable SA1515 // Single-line comment should be preceded by blank line + // ReSharper disable once ExplicitCallerInfoArgument $"Decode {fileName}"); +#pragma warning restore SA1515 // Single-line comment should be preceded by blank line } // Benchmark, enable manually! @@ -101,8 +103,10 @@ public void EncodeJpeg(int executionCount, int quality, JpegSubsample subsample) ms.Seek(0, SeekOrigin.Begin); } }, - // ReSharper disable once ExplicitCallerInfoArgument +#pragma warning disable SA1515 // Single-line comment should be preceded by blank line + // ReSharper disable once ExplicitCallerInfoArgument $@"Encode {testFiles.Length} images"); +#pragma warning restore SA1515 // Single-line comment should be preceded by blank line } foreach (Image image in testImages) @@ -111,4 +115,4 @@ public void EncodeJpeg(int executionCount, int quality, JpegSubsample subsample) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs index 95fe4e48f1..858607a02f 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.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. using System.IO; @@ -28,7 +28,8 @@ public void LoadResizeSave(string imagePath) using (var ms = new MemoryStream()) { - this.Measure(30, + this.Measure( + 30, () => { using (var image = Image.Load(configuration, imageBytes)) @@ -36,9 +37,10 @@ public void LoadResizeSave(string imagePath) image.Mutate(x => x.Resize(image.Size() / 4)); image.SaveAsJpeg(ms); } + ms.Seek(0, SeekOrigin.Begin); }); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/ProfilingSetup.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/ProfilingSetup.cs index f9a68d4e7c..34a1eaa30d 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/ProfilingSetup.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/ProfilingSetup.cs @@ -1,9 +1,8 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. // Uncomment to enable local profiling benchmarks. DO NOT PUSH TO MAIN! // #define PROFILING - namespace SixLabors.ImageSharp.Tests.ProfilingBenchmarks { public static class ProfilingSetup @@ -15,4 +14,4 @@ public static class ProfilingSetup "Profiling benchmark, enable manually!"; #endif } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs index 8b93559381..ba5eb532b2 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs @@ -20,13 +20,14 @@ public ResizeProfilingBenchmarks(ITestOutputHelper output) } public int ExecutionCount { get; set; } = 50; - + [Theory(Skip = ProfilingSetup.SkipProfilingTests)] [InlineData(100, 100)] [InlineData(2000, 2000)] public void ResizeBicubic(int width, int height) { - this.Measure(this.ExecutionCount, + this.Measure( + this.ExecutionCount, () => { using (var image = new Image(this.configuration, width, height)) @@ -35,6 +36,5 @@ public void ResizeBicubic(int width, int height) } }); } - } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs index a1de7fd4b9..1b0253147a 100644 --- a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs +++ b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors.Quantization; @@ -167,4 +170,4 @@ private static void TestScale(Func pixelBuilder) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs index 771e330389..0a039e18e8 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.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. namespace SixLabors.ImageSharp.Tests @@ -20,8 +20,7 @@ internal static class IccTestDataArray public static readonly ushort[] UInt16_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - public static readonly byte[] UInt16_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt16_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_0, IccTestDataPrimitives.UInt16_1, IccTestDataPrimitives.UInt16_2, @@ -31,8 +30,7 @@ internal static class IccTestDataArray IccTestDataPrimitives.UInt16_6, IccTestDataPrimitives.UInt16_7, IccTestDataPrimitives.UInt16_8, - IccTestDataPrimitives.UInt16_9 - ); + IccTestDataPrimitives.UInt16_9); public static readonly object[][] UInt16TestData = { @@ -45,8 +43,7 @@ internal static class IccTestDataArray public static readonly short[] Int16_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - public static readonly byte[] Int16_Arr = ArrayHelper.Concat - ( + public static readonly byte[] Int16_Arr = ArrayHelper.Concat( IccTestDataPrimitives.Int16_0, IccTestDataPrimitives.Int16_1, IccTestDataPrimitives.Int16_2, @@ -56,8 +53,7 @@ internal static class IccTestDataArray IccTestDataPrimitives.Int16_6, IccTestDataPrimitives.Int16_7, IccTestDataPrimitives.Int16_8, - IccTestDataPrimitives.Int16_9 - ); + IccTestDataPrimitives.Int16_9); public static readonly object[][] Int16TestData = { @@ -70,8 +66,7 @@ internal static class IccTestDataArray public static readonly uint[] UInt32_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - public static readonly byte[] UInt32_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt32_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_0, IccTestDataPrimitives.UInt32_1, IccTestDataPrimitives.UInt32_2, @@ -81,8 +76,7 @@ internal static class IccTestDataArray IccTestDataPrimitives.UInt32_6, IccTestDataPrimitives.UInt32_7, IccTestDataPrimitives.UInt32_8, - IccTestDataPrimitives.UInt32_9 - ); + IccTestDataPrimitives.UInt32_9); public static readonly object[][] UInt32TestData = { @@ -95,8 +89,7 @@ internal static class IccTestDataArray public static readonly int[] Int32_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - public static readonly byte[] Int32_Arr = ArrayHelper.Concat - ( + public static readonly byte[] Int32_Arr = ArrayHelper.Concat( IccTestDataPrimitives.Int32_0, IccTestDataPrimitives.Int32_1, IccTestDataPrimitives.Int32_2, @@ -106,8 +99,7 @@ internal static class IccTestDataArray IccTestDataPrimitives.Int32_6, IccTestDataPrimitives.Int32_7, IccTestDataPrimitives.Int32_8, - IccTestDataPrimitives.Int32_9 - ); + IccTestDataPrimitives.Int32_9); public static readonly object[][] Int32TestData = { @@ -120,8 +112,7 @@ internal static class IccTestDataArray public static readonly ulong[] UInt64_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - public static readonly byte[] UInt64_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt64_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt64_0, IccTestDataPrimitives.UInt64_1, IccTestDataPrimitives.UInt64_2, @@ -131,8 +122,7 @@ internal static class IccTestDataArray IccTestDataPrimitives.UInt64_6, IccTestDataPrimitives.UInt64_7, IccTestDataPrimitives.UInt64_8, - IccTestDataPrimitives.UInt64_9 - ); + IccTestDataPrimitives.UInt64_9); public static readonly object[][] UInt64TestData = { @@ -141,4 +131,4 @@ internal static class IccTestDataArray #endregion } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs index 334ee026db..f679d6a324 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.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. using System.Numerics; @@ -10,49 +10,43 @@ internal static class IccTestDataCurves { #region Response +#pragma warning disable SA1118 // Parameter should not span multiple lines /// /// Channels: 3 /// - public static readonly IccResponseCurve Response_ValGrad = new IccResponseCurve - ( + public static readonly IccResponseCurve Response_ValGrad = new IccResponseCurve( IccCurveMeasurementEncodings.StatusA, - new Vector3[] + new[] { IccTestDataNonPrimitives.XyzNumber_ValVar1, IccTestDataNonPrimitives.XyzNumber_ValVar2, - IccTestDataNonPrimitives.XyzNumber_ValVar3, + IccTestDataNonPrimitives.XyzNumber_ValVar3 }, new IccResponseNumber[][] { new IccResponseNumber[] { IccTestDataNonPrimitives.ResponseNumber_Val1, IccTestDataNonPrimitives.ResponseNumber_Val2 }, new IccResponseNumber[] { IccTestDataNonPrimitives.ResponseNumber_Val3, IccTestDataNonPrimitives.ResponseNumber_Val4 }, new IccResponseNumber[] { IccTestDataNonPrimitives.ResponseNumber_Val5, IccTestDataNonPrimitives.ResponseNumber_Val6 }, - } - ); + }); +#pragma warning restore SA1118 // Parameter should not span multiple lines /// /// Channels: 3 /// - public static readonly byte[] Response_Grad = ArrayHelper.Concat - ( + public static readonly byte[] Response_Grad = ArrayHelper.Concat( new byte[] { 0x53, 0x74, 0x61, 0x41 }, IccTestDataPrimitives.UInt32_2, IccTestDataPrimitives.UInt32_2, IccTestDataPrimitives.UInt32_2, - IccTestDataNonPrimitives.XyzNumber_Var1, IccTestDataNonPrimitives.XyzNumber_Var2, IccTestDataNonPrimitives.XyzNumber_Var3, - IccTestDataNonPrimitives.ResponseNumber_1, IccTestDataNonPrimitives.ResponseNumber_2, - IccTestDataNonPrimitives.ResponseNumber_3, IccTestDataNonPrimitives.ResponseNumber_4, - IccTestDataNonPrimitives.ResponseNumber_5, - IccTestDataNonPrimitives.ResponseNumber_6 - ); + IccTestDataNonPrimitives.ResponseNumber_6); public static readonly object[][] ResponseCurveTestData = { @@ -69,18 +63,15 @@ internal static class IccTestDataCurves public static readonly IccParametricCurve Parametric_ValVar4 = new IccParametricCurve(1, 2, 3, 4, 5); public static readonly IccParametricCurve Parametric_ValVar5 = new IccParametricCurve(1, 2, 3, 4, 5, 6, 7); - public static readonly byte[] Parametric_Var1 = ArrayHelper.Concat - ( + public static readonly byte[] Parametric_Var1 = ArrayHelper.Concat( new byte[] { 0x00, 0x00, 0x00, 0x00, }, - IccTestDataPrimitives.Fix16_1 - ); + IccTestDataPrimitives.Fix16_1); - public static readonly byte[] Parametric_Var2 = ArrayHelper.Concat - ( + public static readonly byte[] Parametric_Var2 = ArrayHelper.Concat( new byte[] { 0x00, 0x01, @@ -88,11 +79,9 @@ internal static class IccTestDataCurves }, IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_2, - IccTestDataPrimitives.Fix16_3 - ); + IccTestDataPrimitives.Fix16_3); - public static readonly byte[] Parametric_Var3 = ArrayHelper.Concat - ( + public static readonly byte[] Parametric_Var3 = ArrayHelper.Concat( new byte[] { 0x00, 0x02, @@ -101,11 +90,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_2, IccTestDataPrimitives.Fix16_3, - IccTestDataPrimitives.Fix16_4 - ); + IccTestDataPrimitives.Fix16_4); - public static readonly byte[] Parametric_Var4 = ArrayHelper.Concat - ( + public static readonly byte[] Parametric_Var4 = ArrayHelper.Concat( new byte[] { 0x00, 0x03, @@ -115,11 +102,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Fix16_2, IccTestDataPrimitives.Fix16_3, IccTestDataPrimitives.Fix16_4, - IccTestDataPrimitives.Fix16_5 - ); + IccTestDataPrimitives.Fix16_5); - public static readonly byte[] Parametric_Var5 = ArrayHelper.Concat - ( + public static readonly byte[] Parametric_Var5 = ArrayHelper.Concat( new byte[] { 0x00, 0x04, @@ -131,8 +116,7 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Fix16_4, IccTestDataPrimitives.Fix16_5, IccTestDataPrimitives.Fix16_6, - IccTestDataPrimitives.Fix16_7 - ); + IccTestDataPrimitives.Fix16_7); public static readonly object[][] ParametricCurveTestData = { @@ -151,8 +135,7 @@ internal static class IccTestDataCurves public static readonly IccFormulaCurveElement Formula_ValVar2 = new IccFormulaCurveElement(IccFormulaCurveType.Type2, 1, 2, 3, 4, 5, 0); public static readonly IccFormulaCurveElement Formula_ValVar3 = new IccFormulaCurveElement(IccFormulaCurveType.Type3, 0, 2, 3, 4, 5, 6); - public static readonly byte[] Formula_Var1 = ArrayHelper.Concat - ( + public static readonly byte[] Formula_Var1 = ArrayHelper.Concat( new byte[] { 0x00, 0x00, @@ -161,11 +144,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, - IccTestDataPrimitives.Single_4 - ); + IccTestDataPrimitives.Single_4); - public static readonly byte[] Formula_Var2 = ArrayHelper.Concat - ( + public static readonly byte[] Formula_Var2 = ArrayHelper.Concat( new byte[] { 0x00, 0x01, @@ -175,11 +156,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, IccTestDataPrimitives.Single_4, - IccTestDataPrimitives.Single_5 - ); + IccTestDataPrimitives.Single_5); - public static readonly byte[] Formula_Var3 = ArrayHelper.Concat - ( + public static readonly byte[] Formula_Var3 = ArrayHelper.Concat( new byte[] { 0x00, 0x02, @@ -189,8 +168,7 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_3, IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_5, - IccTestDataPrimitives.Single_6 - ); + IccTestDataPrimitives.Single_6); public static readonly object[][] FormulaCurveSegmentTestData = { @@ -206,10 +184,8 @@ internal static class IccTestDataCurves public static readonly IccSampledCurveElement Sampled_ValGrad1 = new IccSampledCurveElement(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); public static readonly IccSampledCurveElement Sampled_ValGrad2 = new IccSampledCurveElement(new float[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }); - public static readonly byte[] Sampled_Grad1 = ArrayHelper.Concat - ( + public static readonly byte[] Sampled_Grad1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_9, - IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, @@ -218,13 +194,10 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_6, IccTestDataPrimitives.Single_7, IccTestDataPrimitives.Single_8, - IccTestDataPrimitives.Single_9 - ); + IccTestDataPrimitives.Single_9); - public static readonly byte[] Sampled_Grad2 = ArrayHelper.Concat - ( + public static readonly byte[] Sampled_Grad2 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_9, - IccTestDataPrimitives.Single_9, IccTestDataPrimitives.Single_8, IccTestDataPrimitives.Single_7, @@ -233,8 +206,7 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_3, IccTestDataPrimitives.Single_2, - IccTestDataPrimitives.Single_1 - ); + IccTestDataPrimitives.Single_1); public static readonly object[][] SampledCurveSegmentTestData = { @@ -252,55 +224,45 @@ internal static class IccTestDataCurves public static readonly IccCurveSegment Segment_ValSampled1 = Sampled_ValGrad1; public static readonly IccCurveSegment Segment_ValSampled2 = Sampled_ValGrad2; - public static readonly byte[] Segment_Formula1 = ArrayHelper.Concat - ( + public static readonly byte[] Segment_Formula1 = ArrayHelper.Concat( new byte[] { 0x70, 0x61, 0x72, 0x66, 0x00, 0x00, 0x00, 0x00, }, - Formula_Var1 - ); + Formula_Var1); - public static readonly byte[] Segment_Formula2 = ArrayHelper.Concat - ( + public static readonly byte[] Segment_Formula2 = ArrayHelper.Concat( new byte[] { 0x70, 0x61, 0x72, 0x66, 0x00, 0x00, 0x00, 0x00, }, - Formula_Var2 - ); + Formula_Var2); - public static readonly byte[] Segment_Formula3 = ArrayHelper.Concat - ( + public static readonly byte[] Segment_Formula3 = ArrayHelper.Concat( new byte[] { 0x70, 0x61, 0x72, 0x66, 0x00, 0x00, 0x00, 0x00, }, - Formula_Var3 - ); + Formula_Var3); - public static readonly byte[] Segment_Sampled1 = ArrayHelper.Concat - ( + public static readonly byte[] Segment_Sampled1 = ArrayHelper.Concat( new byte[] { 0x73, 0x61, 0x6D, 0x66, 0x00, 0x00, 0x00, 0x00, }, - Sampled_Grad1 - ); + Sampled_Grad1); - public static readonly byte[] Segment_Sampled2 = ArrayHelper.Concat - ( + public static readonly byte[] Segment_Sampled2 = ArrayHelper.Concat( new byte[] { 0x73, 0x61, 0x6D, 0x66, 0x00, 0x00, 0x00, 0x00, }, - Sampled_Grad2 - ); + Sampled_Grad2); public static readonly object[][] CurveSegmentTestData = { @@ -315,24 +277,19 @@ internal static class IccTestDataCurves #region One Dimensional - public static readonly IccOneDimensionalCurve OneDimensional_ValFormula1 = new IccOneDimensionalCurve - ( + public static readonly IccOneDimensionalCurve OneDimensional_ValFormula1 = new IccOneDimensionalCurve( new float[] { 0, 1 }, - new IccCurveSegment[] { Segment_ValFormula1, Segment_ValFormula2, Segment_ValFormula3 } - ); - public static readonly IccOneDimensionalCurve OneDimensional_ValFormula2 = new IccOneDimensionalCurve - ( + new IccCurveSegment[] { Segment_ValFormula1, Segment_ValFormula2, Segment_ValFormula3 }); + + public static readonly IccOneDimensionalCurve OneDimensional_ValFormula2 = new IccOneDimensionalCurve( new float[] { 0, 1 }, - new IccCurveSegment[] { Segment_ValFormula3, Segment_ValFormula2, Segment_ValFormula1 } - ); - public static readonly IccOneDimensionalCurve OneDimensional_ValSampled = new IccOneDimensionalCurve - ( + new IccCurveSegment[] { Segment_ValFormula3, Segment_ValFormula2, Segment_ValFormula1 }); + + public static readonly IccOneDimensionalCurve OneDimensional_ValSampled = new IccOneDimensionalCurve( new float[] { 0, 1 }, - new IccCurveSegment[] { Segment_ValSampled1, Segment_ValSampled2, Segment_ValSampled1 } - ); + new IccCurveSegment[] { Segment_ValSampled1, Segment_ValSampled2, Segment_ValSampled1 }); - public static readonly byte[] OneDimensional_Formula1 = ArrayHelper.Concat - ( + public static readonly byte[] OneDimensional_Formula1 = ArrayHelper.Concat( new byte[] { 0x00, 0x03, @@ -342,11 +299,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_1, Segment_Formula1, Segment_Formula2, - Segment_Formula3 - ); + Segment_Formula3); - public static readonly byte[] OneDimensional_Formula2 = ArrayHelper.Concat - ( + public static readonly byte[] OneDimensional_Formula2 = ArrayHelper.Concat( new byte[] { 0x00, 0x03, @@ -356,11 +311,9 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_1, Segment_Formula3, Segment_Formula2, - Segment_Formula1 - ); + Segment_Formula1); - public static readonly byte[] OneDimensional_Sampled = ArrayHelper.Concat - ( + public static readonly byte[] OneDimensional_Sampled = ArrayHelper.Concat( new byte[] { 0x00, 0x03, @@ -370,8 +323,7 @@ internal static class IccTestDataCurves IccTestDataPrimitives.Single_1, Segment_Sampled1, Segment_Sampled2, - Segment_Sampled1 - ); + Segment_Sampled1); public static readonly object[][] OneDimensionalCurveTestData = { diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs index 5ef2156c71..cc7ab7d71c 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.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. using SixLabors.ImageSharp.Metadata.Profiles.Icc; @@ -15,14 +15,22 @@ internal static class IccTestDataLut private static IccLut CreateLUT8Val() { float[] result = new float[256]; - for (int i = 0; i < 256; i++) { result[i] = i / 255f; } + for (int i = 0; i < 256; i++) + { + result[i] = i / 255f; + } + return new IccLut(result); } private static byte[] CreateLUT8() { byte[] result = new byte[256]; - for (int i = 0; i < 256; i++) { result[i] = (byte)i; } + for (int i = 0; i < 256; i++) + { + result[i] = (byte)i; + } + return result; } @@ -50,8 +58,7 @@ private static byte[] CreateLUT8() 1f }); - public static readonly byte[] LUT16_Grad = ArrayHelper.Concat - ( + public static readonly byte[] LUT16_Grad = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_1, IccTestDataPrimitives.UInt16_2, IccTestDataPrimitives.UInt16_3, @@ -62,8 +69,7 @@ private static byte[] CreateLUT8() IccTestDataPrimitives.UInt16_8, IccTestDataPrimitives.UInt16_9, IccTestDataPrimitives.UInt16_32768, - IccTestDataPrimitives.UInt16_Max - ); + IccTestDataPrimitives.UInt16_Max); public static readonly object[][] Lut16TestData = { @@ -74,8 +80,7 @@ private static byte[] CreateLUT8() #region CLUT8 - public static readonly IccClut CLUT8_ValGrad = new IccClut - ( + public static readonly IccClut CLUT8_ValGrad = new IccClut( new float[][] { new float[] { 1f / byte.MaxValue, 2f / byte.MaxValue, 3f / byte.MaxValue }, @@ -90,8 +95,8 @@ private static byte[] CreateLUT8() new float[] { 22f / byte.MaxValue, 23f / byte.MaxValue, 24f / byte.MaxValue }, new float[] { 25f / byte.MaxValue, 26f / byte.MaxValue, 27f / byte.MaxValue }, }, - new byte[] { 3, 3 }, IccClutDataType.UInt8 - ); + new byte[] { 3, 3 }, + IccClutDataType.UInt8); /// /// Input Channel Count: 2 @@ -122,8 +127,7 @@ private static byte[] CreateLUT8() #region CLUT16 - public static readonly IccClut CLUT16_ValGrad = new IccClut - ( + public static readonly IccClut CLUT16_ValGrad = new IccClut( new float[][] { new float[] { 1f / ushort.MaxValue, 2f / ushort.MaxValue, 3f / ushort.MaxValue }, @@ -138,8 +142,8 @@ private static byte[] CreateLUT8() new float[] { 22f / ushort.MaxValue, 23f / ushort.MaxValue, 24f / ushort.MaxValue }, new float[] { 25f / ushort.MaxValue, 26f / ushort.MaxValue, 27f / ushort.MaxValue }, }, - new byte[] { 3, 3 }, IccClutDataType.UInt16 - ); + new byte[] { 3, 3 }, + IccClutDataType.UInt16); /// /// Input Channel Count: 2 @@ -170,8 +174,7 @@ private static byte[] CreateLUT8() #region CLUTf32 - public static readonly IccClut CLUTf32_ValGrad = new IccClut - ( + public static readonly IccClut CLUTf32_ValGrad = new IccClut( new float[][] { new float[] { 1f, 2f, 3f }, @@ -186,28 +189,42 @@ private static byte[] CreateLUT8() new float[] { 4f, 5f, 6f }, new float[] { 7f, 8f, 9f }, }, - new byte[] { 3, 3 }, IccClutDataType.Float - ); + new byte[] { 3, 3 }, + IccClutDataType.Float); /// /// Input Channel Count: 2 /// Output Channel Count: 3 /// Grid-point Count: { 3, 3 } /// - public static readonly byte[] CLUTf32_Grad = ArrayHelper.Concat - ( - IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, - IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_5, IccTestDataPrimitives.Single_6, - IccTestDataPrimitives.Single_7, IccTestDataPrimitives.Single_8, IccTestDataPrimitives.Single_9, - - IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, - IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_5, IccTestDataPrimitives.Single_6, - IccTestDataPrimitives.Single_7, IccTestDataPrimitives.Single_8, IccTestDataPrimitives.Single_9, - - IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_3, - IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_5, IccTestDataPrimitives.Single_6, - IccTestDataPrimitives.Single_7, IccTestDataPrimitives.Single_8, IccTestDataPrimitives.Single_9 - ); + public static readonly byte[] CLUTf32_Grad = ArrayHelper.Concat( + IccTestDataPrimitives.Single_1, + IccTestDataPrimitives.Single_2, + IccTestDataPrimitives.Single_3, + IccTestDataPrimitives.Single_4, + IccTestDataPrimitives.Single_5, + IccTestDataPrimitives.Single_6, + IccTestDataPrimitives.Single_7, + IccTestDataPrimitives.Single_8, + IccTestDataPrimitives.Single_9, + IccTestDataPrimitives.Single_1, + IccTestDataPrimitives.Single_2, + IccTestDataPrimitives.Single_3, + IccTestDataPrimitives.Single_4, + IccTestDataPrimitives.Single_5, + IccTestDataPrimitives.Single_6, + IccTestDataPrimitives.Single_7, + IccTestDataPrimitives.Single_8, + IccTestDataPrimitives.Single_9, + IccTestDataPrimitives.Single_1, + IccTestDataPrimitives.Single_2, + IccTestDataPrimitives.Single_3, + IccTestDataPrimitives.Single_4, + IccTestDataPrimitives.Single_5, + IccTestDataPrimitives.Single_6, + IccTestDataPrimitives.Single_7, + IccTestDataPrimitives.Single_8, + IccTestDataPrimitives.Single_9); public static readonly object[][] ClutF32TestData = { @@ -222,25 +239,19 @@ private static byte[] CreateLUT8() public static readonly IccClut CLUT_Val16 = CLUT16_ValGrad; public static readonly IccClut CLUT_Valf32 = CLUTf32_ValGrad; - public static readonly byte[] CLUT_8 = ArrayHelper.Concat - ( + public static readonly byte[] CLUT_8 = ArrayHelper.Concat( new byte[16] { 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, new byte[4] { 0x01, 0x00, 0x00, 0x00 }, - CLUT8_Grad - ); + CLUT8_Grad); - public static readonly byte[] CLUT_16 = ArrayHelper.Concat - ( + public static readonly byte[] CLUT_16 = ArrayHelper.Concat( new byte[16] { 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, new byte[4] { 0x02, 0x00, 0x00, 0x00 }, - CLUT16_Grad - ); + CLUT16_Grad); - public static readonly byte[] CLUT_f32 = ArrayHelper.Concat - ( + public static readonly byte[] CLUT_f32 = ArrayHelper.Concat( new byte[16] { 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, - CLUTf32_Grad - ); + CLUTf32_Grad); public static readonly object[][] ClutTestData = { diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs index 799794ca4f..2a2b6338fb 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.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. using System.Numerics; @@ -20,6 +20,7 @@ internal static class IccTestDataMatrix { 4, 5, 6 }, { 7, 8, 9 }, }; + /// /// 3x3 Matrix /// @@ -53,56 +54,44 @@ internal static class IccTestDataMatrix /// /// 3x3 Matrix /// - public static readonly byte[] Fix16_2D_Grad = ArrayHelper.Concat - ( + public static readonly byte[] Fix16_2D_Grad = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_4, IccTestDataPrimitives.Fix16_7, - IccTestDataPrimitives.Fix16_2, IccTestDataPrimitives.Fix16_5, IccTestDataPrimitives.Fix16_8, - IccTestDataPrimitives.Fix16_3, IccTestDataPrimitives.Fix16_6, - IccTestDataPrimitives.Fix16_9 - ); + IccTestDataPrimitives.Fix16_9); /// /// 3x3 Matrix /// - public static readonly byte[] Fix16_2D_Identity = ArrayHelper.Concat - ( + public static readonly byte[] Fix16_2D_Identity = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_0, IccTestDataPrimitives.Fix16_0, - IccTestDataPrimitives.Fix16_0, IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_0, - IccTestDataPrimitives.Fix16_0, IccTestDataPrimitives.Fix16_0, - IccTestDataPrimitives.Fix16_1 - ); + IccTestDataPrimitives.Fix16_1); /// /// 3x3 Matrix /// - public static readonly byte[] Single_2D_Grad = ArrayHelper.Concat - ( + public static readonly byte[] Single_2D_Grad = ArrayHelper.Concat( IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_4, IccTestDataPrimitives.Single_7, - IccTestDataPrimitives.Single_2, IccTestDataPrimitives.Single_5, IccTestDataPrimitives.Single_8, - IccTestDataPrimitives.Single_3, IccTestDataPrimitives.Single_6, - IccTestDataPrimitives.Single_9 - ); + IccTestDataPrimitives.Single_9); public static readonly object[][] Matrix2D_FloatArrayTestData = { @@ -133,6 +122,7 @@ internal static class IccTestDataMatrix /// 3x1 Matrix /// public static readonly float[] Single_1DArray_ValGrad = { 1, 4, 7 }; + /// /// 3x1 Matrix /// @@ -141,22 +131,18 @@ internal static class IccTestDataMatrix /// /// 3x1 Matrix /// - public static readonly byte[] Fix16_1D_Grad = ArrayHelper.Concat - ( + public static readonly byte[] Fix16_1D_Grad = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_4, - IccTestDataPrimitives.Fix16_7 - ); + IccTestDataPrimitives.Fix16_7); /// /// 3x1 Matrix /// - public static readonly byte[] Single_1D_Grad = ArrayHelper.Concat - ( + public static readonly byte[] Single_1D_Grad = ArrayHelper.Concat( IccTestDataPrimitives.Single_1, IccTestDataPrimitives.Single_4, - IccTestDataPrimitives.Single_7 - ); + IccTestDataPrimitives.Single_7); public static readonly object[][] Matrix1D_ArrayTestData = { diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs index 586e846801..32015dfd83 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs @@ -1,11 +1,11 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.Metadata.Profiles.Icc; namespace SixLabors.ImageSharp.Tests { - internal static class IccTestDataMultiProcessElement + internal static class IccTestDataMultiProcessElements { #region CurveSet @@ -19,16 +19,15 @@ internal static class IccTestDataMultiProcessElement IccTestDataCurves.OneDimensional_ValFormula2, IccTestDataCurves.OneDimensional_ValFormula1 }); + /// /// Input Channel Count: 3 /// Output Channel Count: 3 /// - public static readonly byte[] CurvePE_Grad = ArrayHelper.Concat - ( + public static readonly byte[] CurvePE_Grad = ArrayHelper.Concat( IccTestDataCurves.OneDimensional_Formula1, IccTestDataCurves.OneDimensional_Formula2, - IccTestDataCurves.OneDimensional_Formula1 - ); + IccTestDataCurves.OneDimensional_Formula1); public static readonly object[][] CurveSetTestData = { @@ -43,27 +42,23 @@ internal static class IccTestDataMultiProcessElement /// Input Channel Count: 3 /// Output Channel Count: 3 /// - public static readonly IccMatrixProcessElement MatrixPE_ValGrad = new IccMatrixProcessElement - ( + public static readonly IccMatrixProcessElement MatrixPE_ValGrad = new IccMatrixProcessElement( IccTestDataMatrix.Single_2DArray_ValGrad, - IccTestDataMatrix.Single_1DArray_ValGrad - ); + IccTestDataMatrix.Single_1DArray_ValGrad); + /// /// Input Channel Count: 3 /// Output Channel Count: 3 /// - public static readonly byte[] MatrixPE_Grad = ArrayHelper.Concat - ( + public static readonly byte[] MatrixPE_Grad = ArrayHelper.Concat( IccTestDataMatrix.Single_2D_Grad, - IccTestDataMatrix.Single_1D_Grad - ); + IccTestDataMatrix.Single_1D_Grad); public static readonly object[][] MatrixTestData = { new object[] { MatrixPE_Grad, MatrixPE_ValGrad, 3, 3 }, }; - #endregion #region CLUT @@ -73,6 +68,7 @@ internal static class IccTestDataMultiProcessElement /// Output Channel Count: 3 /// public static readonly IccClutProcessElement CLUTPE_ValGrad = new IccClutProcessElement(IccTestDataLut.CLUT_Valf32); + /// /// Input Channel Count: 2 /// Output Channel Count: 3 @@ -94,38 +90,32 @@ internal static class IccTestDataMultiProcessElement public static readonly IccMultiProcessElement MPE_ValbACS = new IccBAcsProcessElement(3, 3); public static readonly IccMultiProcessElement MPE_ValeACS = new IccEAcsProcessElement(3, 3); - public static readonly byte[] MPE_Matrix = ArrayHelper.Concat - ( + public static readonly byte[] MPE_Matrix = ArrayHelper.Concat( new byte[] { 0x6D, 0x61, 0x74, 0x66, 0x00, 0x03, 0x00, 0x03, }, - MatrixPE_Grad - ); + MatrixPE_Grad); - public static readonly byte[] MPE_CLUT = ArrayHelper.Concat - ( + public static readonly byte[] MPE_CLUT = ArrayHelper.Concat( new byte[] { 0x63, 0x6C, 0x75, 0x74, 0x00, 0x02, 0x00, 0x03, }, - CLUTPE_Grad - ); + CLUTPE_Grad); - public static readonly byte[] MPE_Curve = ArrayHelper.Concat - ( + public static readonly byte[] MPE_Curve = ArrayHelper.Concat( new byte[] { 0x6D, 0x66, 0x6C, 0x74, 0x00, 0x03, 0x00, 0x03, }, - CurvePE_Grad - ); + CurvePE_Grad); public static readonly byte[] MPE_bACS = { diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs index 44af423479..a75a04a364 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs @@ -191,39 +191,48 @@ internal static class IccTestDataNonPrimitives #region NamedColor - public static readonly IccNamedColor NamedColor_ValMin = new IccNamedColor - ( + public static readonly IccNamedColor NamedColor_ValMin = new IccNamedColor( ArrayHelper.Fill('A', 31), new ushort[] { 0, 0, 0 }, - new ushort[] { 0, 0, 0 } - ); - public static readonly IccNamedColor NamedColor_ValRand = new IccNamedColor - ( + new ushort[] { 0, 0, 0 }); + + public static readonly IccNamedColor NamedColor_ValRand = new IccNamedColor( ArrayHelper.Fill('5', 31), new ushort[] { 10794, 10794, 10794 }, - new ushort[] { 17219, 17219, 17219, 17219, 17219 } - ); - public static readonly IccNamedColor NamedColor_ValMax = new IccNamedColor - ( + new ushort[] { 17219, 17219, 17219, 17219, 17219 }); + + public static readonly IccNamedColor NamedColor_ValMax = new IccNamedColor( ArrayHelper.Fill('4', 31), new ushort[] { ushort.MaxValue, ushort.MaxValue, ushort.MaxValue }, - new ushort[] { ushort.MaxValue, ushort.MaxValue, ushort.MaxValue, ushort.MaxValue } - ); + new ushort[] { ushort.MaxValue, ushort.MaxValue, ushort.MaxValue, ushort.MaxValue }); public static readonly byte[] NamedColor_Min = CreateNamedColor(3, 0x41, 0x00, 0x00); public static readonly byte[] NamedColor_Rand = CreateNamedColor(5, 0x35, 42, 67); public static readonly byte[] NamedColor_Max = CreateNamedColor(4, 0x34, 0xFF, 0xFF); - private static byte[] CreateNamedColor(int devCoordCount, byte name, byte PCS, byte device) + private static byte[] CreateNamedColor(int devCoordCount, byte name, byte pCS, byte device) { - byte[] data = new byte[32 + 6 + devCoordCount * 2]; + byte[] data = new byte[32 + 6 + (devCoordCount * 2)]; for (int i = 0; i < data.Length; i++) { - if (i < 31) { data[i] = name; } // Name - else if (i == 31) { data[i] = 0x00; } // Name null terminator - else if (i < 32 + 6) { data[i] = PCS; } // PCS Coordinates - else { data[i] = device; } // Device Coordinates + if (i < 31) + { + data[i] = name; // Name + } + else if (i is 31) + { + data[i] = 0x00; // Name null terminator + } + else if (i < 32 + 6) + { + data[i] = pCS; // PCS Coordinates + } + else + { + data[i] = device; // Device Coordinates + } } + return data; } @@ -251,91 +260,76 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte PCS, b }; private static readonly IccMultiLocalizedUnicodeTagDataEntry MultiLocalizedUnicode_Val = new IccMultiLocalizedUnicodeTagDataEntry(LocalizedString_RandArr1); - private static readonly byte[] MultiLocalizedUnicode_Arr = ArrayHelper.Concat - ( + private static readonly byte[] MultiLocalizedUnicode_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 - new byte[] { (byte)'e', (byte)'n', (byte)'U', (byte)'S' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x28 }, // 40 - new byte[] { (byte)'d', (byte)'e', (byte)'A', (byte)'T' }, new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 new byte[] { 0x00, 0x00, 0x00, 0x34 }, // 52 - IccTestDataPrimitives.Unicode_Rand2, - IccTestDataPrimitives.Unicode_Rand3 - ); - - public static readonly IccTextDescriptionTagDataEntry TextDescription_Val1 = new IccTextDescriptionTagDataEntry - ( - IccTestDataPrimitives.Ascii_ValRand, IccTestDataPrimitives.Unicode_ValRand1, ArrayHelper.Fill('A', 66), - 1701729619, 2 - ); - public static readonly byte[] TextDescription_Arr1 = ArrayHelper.Concat - ( + IccTestDataPrimitives.Unicode_Rand3); + + public static readonly IccTextDescriptionTagDataEntry TextDescription_Val1 = new IccTextDescriptionTagDataEntry( + IccTestDataPrimitives.Ascii_ValRand, + IccTestDataPrimitives.Unicode_ValRand1, + ArrayHelper.Fill('A', 66), + 1701729619, + 2); + + public static readonly byte[] TextDescription_Arr1 = ArrayHelper.Concat( new byte[] { 0x00, 0x00, 0x00, 0x0B }, // 11 IccTestDataPrimitives.Ascii_Rand, new byte[] { 0x00 }, // Null terminator - new byte[] { (byte)'e', (byte)'n', (byte)'U', (byte)'S' }, new byte[] { 0x00, 0x00, 0x00, 0x07 }, // 7 IccTestDataPrimitives.Unicode_Rand2, new byte[] { 0x00, 0x00 }, // Null terminator - new byte[] { 0x00, 0x02, 0x43 }, // 2, 67 ArrayHelper.Fill((byte)0x41, 66), - new byte[] { 0x00 } // Null terminator - ); + new byte[] { 0x00 }); // Null terminator - public static readonly IccProfileDescription ProfileDescription_ValRand1 = new IccProfileDescription - ( - 1, 2, + public static readonly IccProfileDescription ProfileDescription_ValRand1 = new IccProfileDescription( + 1, + 2, IccDeviceAttribute.ChromaBlackWhite | IccDeviceAttribute.ReflectivityMatte, IccProfileTag.ProfileDescription, MultiLocalizedUnicode_Val.Texts, - MultiLocalizedUnicode_Val.Texts - ); + MultiLocalizedUnicode_Val.Texts); - public static readonly IccProfileDescription ProfileDescription_ValRand2 = new IccProfileDescription - ( - 1, 2, + public static readonly IccProfileDescription ProfileDescription_ValRand2 = new IccProfileDescription( + 1, + 2, IccDeviceAttribute.ChromaBlackWhite | IccDeviceAttribute.ReflectivityMatte, IccProfileTag.ProfileDescription, new IccLocalizedString[] { LocalizedString_Rand1 }, - new IccLocalizedString[] { LocalizedString_Rand1 } - ); + new IccLocalizedString[] { LocalizedString_Rand1 }); - public static readonly byte[] ProfileDescription_Rand1 = ArrayHelper.Concat - ( + public static readonly byte[] ProfileDescription_Rand1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, IccTestDataPrimitives.UInt32_2, new byte[] { 0, 0, 0, 0, 0, 0, 0, 10 }, new byte[] { 0x64, 0x65, 0x73, 0x63 }, - new byte[] { 0x6D, 0x6C, 0x75, 0x63 }, new byte[] { 0x00, 0x00, 0x00, 0x00 }, MultiLocalizedUnicode_Arr, new byte[] { 0x6D, 0x6C, 0x75, 0x63 }, new byte[] { 0x00, 0x00, 0x00, 0x00 }, - MultiLocalizedUnicode_Arr - ); + MultiLocalizedUnicode_Arr); - public static readonly byte[] ProfileDescription_Rand2 = ArrayHelper.Concat - ( + public static readonly byte[] ProfileDescription_Rand2 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, IccTestDataPrimitives.UInt32_2, new byte[] { 0, 0, 0, 0, 0, 0, 0, 10 }, new byte[] { 0x64, 0x65, 0x73, 0x63 }, - new byte[] { 0x64, 0x65, 0x73, 0x63 }, new byte[] { 0x00, 0x00, 0x00, 0x00 }, TextDescription_Arr1, new byte[] { 0x64, 0x65, 0x73, 0x63 }, new byte[] { 0x00, 0x00, 0x00, 0x00 }, - TextDescription_Arr1 - ); + TextDescription_Arr1); public static readonly object[][] ProfileDescriptionReadTestData = { @@ -355,23 +349,19 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte PCS, b public static readonly IccColorantTableEntry ColorantTableEntry_ValRand1 = new IccColorantTableEntry(ArrayHelper.Fill('A', 31), 1, 2, 3); public static readonly IccColorantTableEntry ColorantTableEntry_ValRand2 = new IccColorantTableEntry(ArrayHelper.Fill('4', 31), 4, 5, 6); - public static readonly byte[] ColorantTableEntry_Rand1 = ArrayHelper.Concat - ( + public static readonly byte[] ColorantTableEntry_Rand1 = ArrayHelper.Concat( ArrayHelper.Fill((byte)0x41, 31), new byte[1], // null terminator IccTestDataPrimitives.UInt16_1, IccTestDataPrimitives.UInt16_2, - IccTestDataPrimitives.UInt16_3 - ); + IccTestDataPrimitives.UInt16_3); - public static readonly byte[] ColorantTableEntry_Rand2 = ArrayHelper.Concat - ( + public static readonly byte[] ColorantTableEntry_Rand2 = ArrayHelper.Concat( ArrayHelper.Fill((byte)0x34, 31), new byte[1], // null terminator IccTestDataPrimitives.UInt16_4, IccTestDataPrimitives.UInt16_5, - IccTestDataPrimitives.UInt16_6 - ); + IccTestDataPrimitives.UInt16_6); public static readonly object[][] ColorantTableEntryTestData = { @@ -386,19 +376,15 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte PCS, b public static readonly IccScreeningChannel ScreeningChannel_ValRand1 = new IccScreeningChannel(4, 6, IccScreeningSpotType.Cross); public static readonly IccScreeningChannel ScreeningChannel_ValRand2 = new IccScreeningChannel(8, 5, IccScreeningSpotType.Diamond); - public static readonly byte[] ScreeningChannel_Rand1 = ArrayHelper.Concat - ( + public static readonly byte[] ScreeningChannel_Rand1 = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_4, IccTestDataPrimitives.Fix16_6, - IccTestDataPrimitives.Int32_7 - ); + IccTestDataPrimitives.Int32_7); - public static readonly byte[] ScreeningChannel_Rand2 = ArrayHelper.Concat - ( + public static readonly byte[] ScreeningChannel_Rand2 = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_8, IccTestDataPrimitives.Fix16_5, - IccTestDataPrimitives.Int32_3 - ); + IccTestDataPrimitives.Int32_3); public static readonly object[][] ScreeningChannelTestData = { diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs index b24e3f24a4..f034313ace 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.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. namespace SixLabors.ImageSharp.Tests @@ -53,7 +53,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] UInt32_9 = { 0x00, 0x00, 0x00, 0x09 }; public static readonly byte[] UInt32_Max = { 0xFF, 0xFF, 0xFF, 0xFF }; - public static readonly uint UInt32_ValRand1 = 1749014123; public static readonly uint UInt32_ValRand2 = 3870560989; public static readonly uint UInt32_ValRand3 = 1050090334; @@ -145,7 +144,7 @@ internal static class IccTestDataPrimitives #region Fix16 public const float Fix16_ValMin = short.MinValue; - public const float Fix16_ValMax = short.MaxValue + 65535f / 65536f; + public const float Fix16_ValMax = short.MaxValue + (65535f / 65536f); public static readonly byte[] Fix16_Min = { 0x80, 0x00, 0x00, 0x00 }; public static readonly byte[] Fix16_0 = { 0x00, 0x00, 0x00, 0x00 }; @@ -173,7 +172,7 @@ internal static class IccTestDataPrimitives #region UFix16 public const float UFix16_ValMin = 0; - public const float UFix16_ValMax = ushort.MaxValue + 65535f / 65536f; + public const float UFix16_ValMax = ushort.MaxValue + (65535f / 65536f); public static readonly byte[] UFix16_0 = { 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] UFix16_1 = { 0x00, 0x01, 0x00, 0x00 }; @@ -199,7 +198,7 @@ internal static class IccTestDataPrimitives #region U1Fix15 public const float U1Fix15_ValMin = 0; - public const float U1Fix15_ValMax = 1f + 32767f / 32768f; + public const float U1Fix15_ValMax = 1f + (32767f / 32768f); public static readonly byte[] U1Fix15_0 = { 0x00, 0x00 }; public static readonly byte[] U1Fix15_1 = { 0x80, 0x00 }; @@ -217,7 +216,7 @@ internal static class IccTestDataPrimitives #region UFix8 public const float UFix8_ValMin = 0; - public const float UFix8_ValMax = byte.MaxValue + 255f / 256f; + public const float UFix8_ValMax = byte.MaxValue + (255f / 256f); public static readonly byte[] UFix8_0 = { 0x00, 0x00 }; public static readonly byte[] UFix8_1 = { 0x01, 0x00 }; diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataProfiles.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataProfiles.cs index 49ff190467..671edcfae0 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataProfiles.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataProfiles.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. using System; @@ -78,41 +78,46 @@ public static byte[] CreateHeaderRandomArray(uint size, uint nrOfEntries, byte[] 0x64, 0x63, 0x62, 0x61, // CreatorSignature }, profileId, +#pragma warning disable SA1118 // Parameter should not span multiple lines new byte[] - { + { // Padding 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Nr of tag table entries - (byte)(nrOfEntries >> 24), (byte)(nrOfEntries >> 16), (byte)(nrOfEntries >> 8), (byte)nrOfEntries + (byte)(nrOfEntries >> 24), + (byte)(nrOfEntries >> 16), + (byte)(nrOfEntries >> 8), + (byte)nrOfEntries }); +#pragma warning restore SA1118 // Parameter should not span multiple lines } - public static readonly byte[] Profile_Random_Array = ArrayHelper.Concat(CreateHeaderRandomArray(168, 2, Profile_Random_Id_Array), + public static readonly byte[] Profile_Random_Array = ArrayHelper.Concat( + CreateHeaderRandomArray(168, 2, Profile_Random_Id_Array), +#pragma warning disable SA1118 // Parameter should not span multiple lines new byte[] { 0x00, 0x00, 0x00, 0x00, // tag signature (Unknown) 0x00, 0x00, 0x00, 0x9C, // tag offset (156) 0x00, 0x00, 0x00, 0x0C, // tag size (12) - 0x00, 0x00, 0x00, 0x00, // tag signature (Unknown) 0x00, 0x00, 0x00, 0x9C, // tag offset (156) 0x00, 0x00, 0x00, 0x0C, // tag size (12) }, +#pragma warning restore SA1118 // Parameter should not span multiple lines IccTestDataTagDataEntry.TagDataEntryHeader_UnknownArr, - IccTestDataTagDataEntry.Unknown_Arr - ); + IccTestDataTagDataEntry.Unknown_Arr); - public static readonly IccProfile Profile_Random_Val = new IccProfile(CreateHeaderRandomValue(168, - Profile_Random_Id_Value, - "acsp"), - new IccTagDataEntry[] - { - IccTestDataTagDataEntry.Unknown_Val, - IccTestDataTagDataEntry.Unknown_Val - }); + public static readonly IccProfile Profile_Random_Val = new IccProfile( + CreateHeaderRandomValue( + 168, + Profile_Random_Id_Value, + "acsp"), + new IccTagDataEntry[] { IccTestDataTagDataEntry.Unknown_Val, IccTestDataTagDataEntry.Unknown_Val }); public static readonly byte[] Header_CorruptDataColorSpace_Array = { @@ -132,8 +137,10 @@ public static byte[] CreateHeaderRandomArray(uint size, uint nrOfEntries, byte[] 0x00, 0x00, 0x00, 0x03, // RenderingIntent 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, // PcsIlluminant 0x64, 0x63, 0x62, 0x61, // CreatorSignature + // Profile ID 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Padding 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -159,8 +166,10 @@ public static byte[] CreateHeaderRandomArray(uint size, uint nrOfEntries, byte[] 0x00, 0x00, 0x00, 0x03, // RenderingIntent 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, // PcsIlluminant 0x64, 0x63, 0x62, 0x61, // CreatorSignature + // Profile ID 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Padding 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -186,8 +195,10 @@ public static byte[] CreateHeaderRandomArray(uint size, uint nrOfEntries, byte[] 0x33, 0x41, 0x30, 0x6B, // RenderingIntent 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, // PcsIlluminant 0x64, 0x63, 0x62, 0x61, // CreatorSignature + // Profile ID 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Padding 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -221,4 +232,4 @@ public static byte[] CreateHeaderRandomArray(uint size, uint nrOfEntries, byte[] new object[] { Header_Random_Array, true }, }; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs index b5da224435..37245a5dda 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.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. using System.Globalization; @@ -56,58 +56,44 @@ internal static class IccTestDataTagDataEntry #region ChromaticityTagDataEntry public static readonly IccChromaticityTagDataEntry Chromaticity_Val1 = new IccChromaticityTagDataEntry(IccColorantEncoding.ItuRBt709_2); - public static readonly byte[] Chromaticity_Arr1 = ArrayHelper.Concat - ( + public static readonly byte[] Chromaticity_Arr1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_3, IccTestDataPrimitives.UInt16_1, - new byte[] { 0x00, 0x00, 0xA3, 0xD7 }, // 0.640 new byte[] { 0x00, 0x00, 0x54, 0x7B }, // 0.330 - new byte[] { 0x00, 0x00, 0x4C, 0xCD }, // 0.300 new byte[] { 0x00, 0x00, 0x99, 0x9A }, // 0.600 - new byte[] { 0x00, 0x00, 0x26, 0x66 }, // 0.150 - new byte[] { 0x00, 0x00, 0x0F, 0x5C } // 0.060 - ); + new byte[] { 0x00, 0x00, 0x0F, 0x5C }); // 0.060 - public static readonly IccChromaticityTagDataEntry Chromaticity_Val2 = new IccChromaticityTagDataEntry - ( + public static readonly IccChromaticityTagDataEntry Chromaticity_Val2 = new IccChromaticityTagDataEntry( new double[][] { new double[] { 1, 2 }, new double[] { 3, 4 }, - } - ); - public static readonly byte[] Chromaticity_Arr2 = ArrayHelper.Concat - ( + }); + + public static readonly byte[] Chromaticity_Arr2 = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_2, IccTestDataPrimitives.UInt16_0, - IccTestDataPrimitives.UFix16_1, IccTestDataPrimitives.UFix16_2, - IccTestDataPrimitives.UFix16_3, - IccTestDataPrimitives.UFix16_4 - ); + IccTestDataPrimitives.UFix16_4); /// /// : channel count must be 3 for any enum other than /// - public static readonly byte[] Chromaticity_ArrInvalid1 = ArrayHelper.Concat - ( + public static readonly byte[] Chromaticity_ArrInvalid1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_5, - IccTestDataPrimitives.UInt16_1 - ); + IccTestDataPrimitives.UInt16_1); /// /// : invalid enum value /// - public static readonly byte[] Chromaticity_ArrInvalid2 = ArrayHelper.Concat - ( + public static readonly byte[] Chromaticity_ArrInvalid2 = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_3, - IccTestDataPrimitives.UInt16_9 - ); + IccTestDataPrimitives.UInt16_9); public static readonly object[][] ChromaticityTagDataEntryTestData = { @@ -131,20 +117,17 @@ internal static class IccTestDataTagDataEntry #region ColorantTableTagDataEntry - public static readonly IccColorantTableTagDataEntry ColorantTable_Val = new IccColorantTableTagDataEntry - ( + public static readonly IccColorantTableTagDataEntry ColorantTable_Val = new IccColorantTableTagDataEntry( new IccColorantTableEntry[] { IccTestDataNonPrimitives.ColorantTableEntry_ValRand1, IccTestDataNonPrimitives.ColorantTableEntry_ValRand2 - } - ); - public static readonly byte[] ColorantTable_Arr = ArrayHelper.Concat - ( + }); + + public static readonly byte[] ColorantTable_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, IccTestDataNonPrimitives.ColorantTableEntry_Rand1, - IccTestDataNonPrimitives.ColorantTableEntry_Rand2 - ); + IccTestDataNonPrimitives.ColorantTableEntry_Rand2); public static readonly object[][] ColorantTableTagDataEntryTestData = { @@ -159,20 +142,16 @@ internal static class IccTestDataTagDataEntry public static readonly byte[] Curve_Arr_0 = IccTestDataPrimitives.UInt32_0; public static readonly IccCurveTagDataEntry Curve_Val_1 = new IccCurveTagDataEntry(1f); - public static readonly byte[] Curve_Arr_1 = ArrayHelper.Concat - ( + public static readonly byte[] Curve_Arr_1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, - IccTestDataPrimitives.UFix8_1 - ); + IccTestDataPrimitives.UFix8_1); public static readonly IccCurveTagDataEntry Curve_Val_2 = new IccCurveTagDataEntry(new float[] { 1 / 65535f, 2 / 65535f, 3 / 65535f }); - public static readonly byte[] Curve_Arr_2 = ArrayHelper.Concat - ( + public static readonly byte[] Curve_Arr_2 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_3, IccTestDataPrimitives.UInt16_1, IccTestDataPrimitives.UInt16_2, - IccTestDataPrimitives.UInt16_3 - ); + IccTestDataPrimitives.UInt16_3); public static readonly object[][] CurveTagDataEntryTestData = { @@ -185,22 +164,20 @@ internal static class IccTestDataTagDataEntry #region DataTagDataEntry - public static readonly IccDataTagDataEntry Data_ValNoASCII = new IccDataTagDataEntry - ( + public static readonly IccDataTagDataEntry Data_ValNoASCII = new IccDataTagDataEntry( new byte[] { 0x01, 0x02, 0x03, 0x04 }, - false - ); + false); + public static readonly byte[] Data_ArrNoASCII = { 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04 }; - public static readonly IccDataTagDataEntry Data_ValASCII = new IccDataTagDataEntry - ( + public static readonly IccDataTagDataEntry Data_ValASCII = new IccDataTagDataEntry( new byte[] { (byte)'A', (byte)'S', (byte)'C', (byte)'I', (byte)'I' }, - true - ); + true); + public static readonly byte[] Data_ArrASCII = { 0x00, 0x00, 0x00, 0x01, @@ -229,27 +206,21 @@ internal static class IccTestDataTagDataEntry #region Lut16TagDataEntry - public static readonly IccLut16TagDataEntry Lut16_Val = new IccLut16TagDataEntry - ( + public static readonly IccLut16TagDataEntry Lut16_Val = new IccLut16TagDataEntry( new IccLut[] { IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad }, IccTestDataLut.CLUT16_ValGrad, - new IccLut[] { IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad } - ); - public static readonly byte[] Lut16_Arr = ArrayHelper.Concat - ( + new IccLut[] { IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad }); + + public static readonly byte[] Lut16_Arr = ArrayHelper.Concat( new byte[] { 0x02, 0x03, 0x03, 0x00 }, IccTestDataMatrix.Fix16_2D_Identity, new byte[] { 0x00, (byte)IccTestDataLut.LUT16_ValGrad.Values.Length, 0x00, (byte)IccTestDataLut.LUT16_ValGrad.Values.Length }, - IccTestDataLut.LUT16_Grad, IccTestDataLut.LUT16_Grad, - IccTestDataLut.CLUT16_Grad, - IccTestDataLut.LUT16_Grad, IccTestDataLut.LUT16_Grad, - IccTestDataLut.LUT16_Grad - ); + IccTestDataLut.LUT16_Grad); public static readonly object[][] Lut16TagDataEntryTestData = { @@ -260,26 +231,20 @@ internal static class IccTestDataTagDataEntry #region Lut8TagDataEntry - public static readonly IccLut8TagDataEntry Lut8_Val = new IccLut8TagDataEntry - ( + public static readonly IccLut8TagDataEntry Lut8_Val = new IccLut8TagDataEntry( new IccLut[] { IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad }, IccTestDataLut.CLUT8_ValGrad, - new IccLut[] { IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad } - ); - public static readonly byte[] Lut8_Arr = ArrayHelper.Concat - ( + new IccLut[] { IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad }); + + public static readonly byte[] Lut8_Arr = ArrayHelper.Concat( new byte[] { 0x02, 0x03, 0x03, 0x00 }, IccTestDataMatrix.Fix16_2D_Identity, - IccTestDataLut.LUT8_Grad, IccTestDataLut.LUT8_Grad, - IccTestDataLut.CLUT8_Grad, - IccTestDataLut.LUT8_Grad, IccTestDataLut.LUT8_Grad, - IccTestDataLut.LUT8_Grad - ); + IccTestDataLut.LUT8_Grad); public static readonly object[][] Lut8TagDataEntryTestData = { @@ -290,24 +255,19 @@ internal static class IccTestDataTagDataEntry #region LutAToBTagDataEntry - private static readonly byte[] CurveFull_0 = ArrayHelper.Concat - ( + private static readonly byte[] CurveFull_0 = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, - Curve_Arr_0 - ); - private static readonly byte[] CurveFull_1 = ArrayHelper.Concat - ( + Curve_Arr_0); + + private static readonly byte[] CurveFull_1 = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, - Curve_Arr_1 - ); - private static readonly byte[] CurveFull_2 = ArrayHelper.Concat - ( + Curve_Arr_1); + + private static readonly byte[] CurveFull_2 = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, - Curve_Arr_2 - ); + Curve_Arr_2); - public static readonly IccLutAToBTagDataEntry LutAToB_Val = new IccLutAToBTagDataEntry - ( + public static readonly IccLutAToBTagDataEntry LutAToB_Val = new IccLutAToBTagDataEntry( new IccCurveTagDataEntry[] { Curve_Val_0, @@ -316,23 +276,13 @@ internal static class IccTestDataTagDataEntry }, IccTestDataMatrix.Single_2DArray_ValGrad, IccTestDataMatrix.Single_1DArray_ValGrad, - new IccCurveTagDataEntry[] - { - Curve_Val_1, - Curve_Val_2, - Curve_Val_0, - }, + new IccCurveTagDataEntry[] { Curve_Val_1, Curve_Val_2, Curve_Val_0 }, IccTestDataLut.CLUT_Val16, - new IccCurveTagDataEntry[] - { - Curve_Val_2, - Curve_Val_1, - } - ); - public static readonly byte[] LutAToB_Arr = ArrayHelper.Concat - ( - new byte[] { 0x02, 0x03, 0x00, 0x00 }, + new IccCurveTagDataEntry[] { Curve_Val_2, Curve_Val_1 }); +#pragma warning disable SA1115 // Parameter should follow comma + public static readonly byte[] LutAToB_Arr = ArrayHelper.Concat( + new byte[] { 0x02, 0x03, 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x20 }, // b: 32 new byte[] { 0x00, 0x00, 0x00, 0x50 }, // matrix: 80 new byte[] { 0x00, 0x00, 0x00, 0x80 }, // m: 128 @@ -365,8 +315,9 @@ internal static class IccTestDataTagDataEntry CurveFull_2, // 18 bytes new byte[] { 0x00, 0x00 }, // Padding CurveFull_1, // 14 bytes - new byte[] { 0x00, 0x00 } // Padding - ); + new byte[] { 0x00, 0x00 }); // Padding + +#pragma warning restore SA1115 // Parameter should follow comma public static readonly object[][] LutAToBTagDataEntryTestData = { @@ -377,9 +328,8 @@ internal static class IccTestDataTagDataEntry #region LutBToATagDataEntry - public static readonly IccLutBToATagDataEntry LutBToA_Val = new IccLutBToATagDataEntry - ( - new IccCurveTagDataEntry[] + public static readonly IccLutBToATagDataEntry LutBToA_Val = new IccLutBToATagDataEntry( + new[] { Curve_Val_0, Curve_Val_1, @@ -388,15 +338,10 @@ internal static class IccTestDataTagDataEntry null, null, IccTestDataLut.CLUT_Val16, - new IccCurveTagDataEntry[] - { - Curve_Val_2, - Curve_Val_1, - Curve_Val_0, - } - ); - public static readonly byte[] LutBToA_Arr = ArrayHelper.Concat - ( + new[] { Curve_Val_2, Curve_Val_1, Curve_Val_0 }); + +#pragma warning disable SA1115 // Parameter should follow comma + public static readonly byte[] LutBToA_Arr = ArrayHelper.Concat( new byte[] { 0x02, 0x03, 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x20 }, // b: 32 @@ -406,8 +351,8 @@ internal static class IccTestDataTagDataEntry new byte[] { 0x00, 0x00, 0x00, 0x88 }, // a: 136 // B - CurveFull_0, //12 bytes - CurveFull_1, //14 bytes + CurveFull_0, // 12 bytes + CurveFull_1, // 14 bytes new byte[] { 0x00, 0x00 }, // Padding // CLUT @@ -419,8 +364,9 @@ internal static class IccTestDataTagDataEntry new byte[] { 0x00, 0x00 }, // Padding CurveFull_1, // 14 bytes new byte[] { 0x00, 0x00 }, // Padding - CurveFull_0 // 12 bytes - ); + CurveFull_0); // 12 bytes + +#pragma warning restore SA1115 // Parameter should follow comma public static readonly object[][] LutBToATagDataEntryTestData = { @@ -431,19 +377,19 @@ internal static class IccTestDataTagDataEntry #region MeasurementTagDataEntry - public static readonly IccMeasurementTagDataEntry Measurement_Val = new IccMeasurementTagDataEntry - ( - IccStandardObserver.Cie1931Observer, IccTestDataNonPrimitives.XyzNumber_ValVar1, - IccMeasurementGeometry.Degree0ToDOrDTo0, 1f, IccStandardIlluminant.D50 - ); - public static readonly byte[] Measurement_Arr = ArrayHelper.Concat - ( + public static readonly IccMeasurementTagDataEntry Measurement_Val = new IccMeasurementTagDataEntry( + IccStandardObserver.Cie1931Observer, + IccTestDataNonPrimitives.XyzNumber_ValVar1, + IccMeasurementGeometry.Degree0ToDOrDTo0, + 1f, + IccStandardIlluminant.D50); + + public static readonly byte[] Measurement_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, IccTestDataNonPrimitives.XyzNumber_Var1, IccTestDataPrimitives.UInt32_2, IccTestDataPrimitives.UFix16_1, - IccTestDataPrimitives.UInt32_1 - ); + IccTestDataPrimitives.UInt32_1); public static readonly object[][] MeasurementTagDataEntryTestData = { @@ -496,11 +442,13 @@ private static IccLocalizedString CreateLocalizedString(string language, string LocalizedString_Rand_enUS, LocalizedString_Rand_deDE, }; + private static readonly IccLocalizedString[] LocalizedString_RandArr_en_Invariant = new IccLocalizedString[] { LocalizedString_Rand_en, LocalizedString_Rand_Invariant, }; + private static readonly IccLocalizedString[] LocalizedString_SameArr_enUS_deDE_esXL_xyXL = new IccLocalizedString[] { LocalizedString_Rand_enUS, @@ -510,82 +458,60 @@ private static IccLocalizedString CreateLocalizedString(string language, string }; public static readonly IccMultiLocalizedUnicodeTagDataEntry MultiLocalizedUnicode_Val = new IccMultiLocalizedUnicodeTagDataEntry(LocalizedString_RandArr_enUS_deDE); - public static readonly byte[] MultiLocalizedUnicode_Arr = ArrayHelper.Concat - ( + public static readonly byte[] MultiLocalizedUnicode_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 - new byte[] { (byte)'e', (byte)'n', (byte)'U', (byte)'S' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x28 }, // 40 - new byte[] { (byte)'d', (byte)'e', (byte)'D', (byte)'E' }, new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 new byte[] { 0x00, 0x00, 0x00, 0x34 }, // 52 - IccTestDataPrimitives.Unicode_Rand2, - IccTestDataPrimitives.Unicode_Rand3 - ); + IccTestDataPrimitives.Unicode_Rand3); public static readonly IccMultiLocalizedUnicodeTagDataEntry MultiLocalizedUnicode_Val2 = new IccMultiLocalizedUnicodeTagDataEntry(LocalizedString_RandArr_en_Invariant); - public static readonly byte[] MultiLocalizedUnicode_Arr2_Read = ArrayHelper.Concat - ( + public static readonly byte[] MultiLocalizedUnicode_Arr2_Read = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 - new byte[] { (byte)'e', (byte)'n', 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x28 }, // 40 - new byte[] { 0x00, 0x00, 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 new byte[] { 0x00, 0x00, 0x00, 0x34 }, // 52 - IccTestDataPrimitives.Unicode_Rand2, - IccTestDataPrimitives.Unicode_Rand3 - ); + IccTestDataPrimitives.Unicode_Rand3); - public static readonly byte[] MultiLocalizedUnicode_Arr2_Write = ArrayHelper.Concat - ( + public static readonly byte[] MultiLocalizedUnicode_Arr2_Write = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 - new byte[] { (byte)'e', (byte)'n', 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x28 }, // 40 - new byte[] { (byte)'x', (byte)'x', 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 new byte[] { 0x00, 0x00, 0x00, 0x34 }, // 52 - IccTestDataPrimitives.Unicode_Rand2, - IccTestDataPrimitives.Unicode_Rand3 - ); + IccTestDataPrimitives.Unicode_Rand3); public static readonly IccMultiLocalizedUnicodeTagDataEntry MultiLocalizedUnicode_Val3 = new IccMultiLocalizedUnicodeTagDataEntry(LocalizedString_SameArr_enUS_deDE_esXL_xyXL); - public static readonly byte[] MultiLocalizedUnicode_Arr3 = ArrayHelper.Concat - ( + public static readonly byte[] MultiLocalizedUnicode_Arr3 = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_4, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 - new byte[] { (byte)'e', (byte)'n', (byte)'U', (byte)'S' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x40 }, // 64 - new byte[] { (byte)'d', (byte)'e', (byte)'D', (byte)'E' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x40 }, // 64 - new byte[] { (byte)'e', (byte)'s', (byte)'X', (byte)'L' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x40 }, // 64 - new byte[] { (byte)'x', (byte)'y', (byte)'X', (byte)'L' }, new byte[] { 0x00, 0x00, 0x00, 0x0C }, // 12 new byte[] { 0x00, 0x00, 0x00, 0x40 }, // 64 - - IccTestDataPrimitives.Unicode_Rand2 - ); + IccTestDataPrimitives.Unicode_Rand2); public static readonly object[][] MultiLocalizedUnicodeTagDataEntryTestData_Read = { @@ -605,29 +531,23 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region MultiProcessElementsTagDataEntry - public static readonly IccMultiProcessElementsTagDataEntry MultiProcessElements_Val = new IccMultiProcessElementsTagDataEntry - ( + public static readonly IccMultiProcessElementsTagDataEntry MultiProcessElements_Val = new IccMultiProcessElementsTagDataEntry( new IccMultiProcessElement[] { - IccTestDataMultiProcessElement.MPE_ValCLUT, - IccTestDataMultiProcessElement.MPE_ValCLUT, - } - ); - public static readonly byte[] MultiProcessElements_Arr = ArrayHelper.Concat - ( + IccTestDataMultiProcessElements.MPE_ValCLUT, + IccTestDataMultiProcessElements.MPE_ValCLUT, + }); + + public static readonly byte[] MultiProcessElements_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_2, IccTestDataPrimitives.UInt16_3, IccTestDataPrimitives.UInt32_2, - new byte[] { 0x00, 0x00, 0x00, 0x20 }, // 32 new byte[] { 0x00, 0x00, 0x00, 0x84 }, // 132 - new byte[] { 0x00, 0x00, 0x00, 0xA4 }, // 164 new byte[] { 0x00, 0x00, 0x00, 0x84 }, // 132 - - IccTestDataMultiProcessElement.MPE_CLUT, - IccTestDataMultiProcessElement.MPE_CLUT - ); + IccTestDataMultiProcessElements.MPE_CLUT, + IccTestDataMultiProcessElements.MPE_CLUT); public static readonly object[][] MultiProcessElementsTagDataEntryTestData = { @@ -638,18 +558,13 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region NamedColor2TagDataEntry - public static readonly IccNamedColor2TagDataEntry NamedColor2_Val = new IccNamedColor2TagDataEntry - ( + public static readonly IccNamedColor2TagDataEntry NamedColor2_Val = new IccNamedColor2TagDataEntry( 16909060, - ArrayHelper.Fill('A', 31), ArrayHelper.Fill('4', 31), - new IccNamedColor[] - { - IccTestDataNonPrimitives.NamedColor_ValMin, - IccTestDataNonPrimitives.NamedColor_ValMin - } - ); - public static readonly byte[] NamedColor2_Arr = ArrayHelper.Concat - ( + ArrayHelper.Fill('A', 31), + ArrayHelper.Fill('4', 31), + new IccNamedColor[] { IccTestDataNonPrimitives.NamedColor_ValMin, IccTestDataNonPrimitives.NamedColor_ValMin }); + + public static readonly byte[] NamedColor2_Arr = ArrayHelper.Concat( new byte[] { 0x01, 0x02, 0x03, 0x04 }, IccTestDataPrimitives.UInt32_2, IccTestDataPrimitives.UInt32_3, @@ -658,8 +573,7 @@ private static IccLocalizedString CreateLocalizedString(string language, string ArrayHelper.Fill((byte)0x34, 31), new byte[] { 0x00 }, IccTestDataNonPrimitives.NamedColor_Min, - IccTestDataNonPrimitives.NamedColor_Min - ); + IccTestDataNonPrimitives.NamedColor_Min); public static readonly object[][] NamedColor2TagDataEntryTestData = { @@ -682,20 +596,17 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region ProfileSequenceDescTagDataEntry - public static readonly IccProfileSequenceDescTagDataEntry ProfileSequenceDesc_Val = new IccProfileSequenceDescTagDataEntry - ( + public static readonly IccProfileSequenceDescTagDataEntry ProfileSequenceDesc_Val = new IccProfileSequenceDescTagDataEntry( new IccProfileDescription[] { IccTestDataNonPrimitives.ProfileDescription_ValRand1, IccTestDataNonPrimitives.ProfileDescription_ValRand1 - } - ); - public static readonly byte[] ProfileSequenceDesc_Arr = ArrayHelper.Concat - ( + }); + + public static readonly byte[] ProfileSequenceDesc_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_2, IccTestDataNonPrimitives.ProfileDescription_Rand1, - IccTestDataNonPrimitives.ProfileDescription_Rand1 - ); + IccTestDataNonPrimitives.ProfileDescription_Rand1); public static readonly object[][] ProfileSequenceDescTagDataEntryTestData = { @@ -706,34 +617,27 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region ProfileSequenceIdentifierTagDataEntry - public static readonly IccProfileSequenceIdentifierTagDataEntry ProfileSequenceIdentifier_Val = new IccProfileSequenceIdentifierTagDataEntry - ( + public static readonly IccProfileSequenceIdentifierTagDataEntry ProfileSequenceIdentifier_Val = new IccProfileSequenceIdentifierTagDataEntry( new IccProfileSequenceIdentifier[] { new IccProfileSequenceIdentifier(IccTestDataNonPrimitives.ProfileId_ValRand, LocalizedString_RandArr_enUS_deDE), new IccProfileSequenceIdentifier(IccTestDataNonPrimitives.ProfileId_ValRand, LocalizedString_RandArr_enUS_deDE), - } - ); - public static readonly byte[] ProfileSequenceIdentifier_Arr = ArrayHelper.Concat - ( - IccTestDataPrimitives.UInt32_2, + }); + public static readonly byte[] ProfileSequenceIdentifier_Arr = ArrayHelper.Concat( + IccTestDataPrimitives.UInt32_2, new byte[] { 0x00, 0x00, 0x00, 0x1C }, // 28 new byte[] { 0x00, 0x00, 0x00, 0x54 }, // 84 - new byte[] { 0x00, 0x00, 0x00, 0x70 }, // 112 new byte[] { 0x00, 0x00, 0x00, 0x54 }, // 84 - IccTestDataNonPrimitives.ProfileId_Rand, // 16 bytes TagDataEntryHeader_MultiLocalizedUnicodeArr, // 8 bytes MultiLocalizedUnicode_Arr, // 58 bytes new byte[] { 0x00, 0x00 }, // 2 bytes (padding) - IccTestDataNonPrimitives.ProfileId_Rand, TagDataEntryHeader_MultiLocalizedUnicodeArr, MultiLocalizedUnicode_Arr, - new byte[] { 0x00, 0x00 } - ); + new byte[] { 0x00, 0x00 }); public static readonly object[][] ProfileSequenceIdentifierTagDataEntryTestData = { @@ -744,25 +648,20 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region ResponseCurveSet16TagDataEntry - public static readonly IccResponseCurveSet16TagDataEntry ResponseCurveSet16_Val = new IccResponseCurveSet16TagDataEntry - ( + public static readonly IccResponseCurveSet16TagDataEntry ResponseCurveSet16_Val = new IccResponseCurveSet16TagDataEntry( new IccResponseCurve[] { IccTestDataCurves.Response_ValGrad, IccTestDataCurves.Response_ValGrad, - } - ); - public static readonly byte[] ResponseCurveSet16_Arr = ArrayHelper.Concat - ( + }); + + public static readonly byte[] ResponseCurveSet16_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_3, IccTestDataPrimitives.UInt16_2, - new byte[] { 0x00, 0x00, 0x00, 0x14 }, // 20 new byte[] { 0x00, 0x00, 0x00, 0x6C }, // 108 - IccTestDataCurves.Response_Grad, // 88 bytes - IccTestDataCurves.Response_Grad // 88 bytes - ); + IccTestDataCurves.Response_Grad); // 88 bytes public static readonly object[][] ResponseCurveSet16TagDataEntryTestData = { @@ -774,12 +673,10 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region Fix16ArrayTagDataEntry public static readonly IccFix16ArrayTagDataEntry Fix16Array_Val = new IccFix16ArrayTagDataEntry(new float[] { 1 / 256f, 2 / 256f, 3 / 256f }); - public static readonly byte[] Fix16Array_Arr = ArrayHelper.Concat - ( + public static readonly byte[] Fix16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_1, IccTestDataPrimitives.Fix16_2, - IccTestDataPrimitives.Fix16_3 - ); + IccTestDataPrimitives.Fix16_3); public static readonly object[][] Fix16ArrayTagDataEntryTestData = { @@ -815,12 +712,10 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region UFix16ArrayTagDataEntry public static readonly IccUFix16ArrayTagDataEntry UFix16Array_Val = new IccUFix16ArrayTagDataEntry(new float[] { 1, 2, 3 }); - public static readonly byte[] UFix16Array_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UFix16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UFix16_1, IccTestDataPrimitives.UFix16_2, - IccTestDataPrimitives.UFix16_3 - ); + IccTestDataPrimitives.UFix16_3); public static readonly object[][] UFix16ArrayTagDataEntryTestData = { @@ -832,12 +727,10 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region UInt16ArrayTagDataEntry public static readonly IccUInt16ArrayTagDataEntry UInt16Array_Val = new IccUInt16ArrayTagDataEntry(new ushort[] { 1, 2, 3 }); - public static readonly byte[] UInt16Array_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_1, IccTestDataPrimitives.UInt16_2, - IccTestDataPrimitives.UInt16_3 - ); + IccTestDataPrimitives.UInt16_3); public static readonly object[][] UInt16ArrayTagDataEntryTestData = { @@ -849,12 +742,10 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region UInt32ArrayTagDataEntry public static readonly IccUInt32ArrayTagDataEntry UInt32Array_Val = new IccUInt32ArrayTagDataEntry(new uint[] { 1, 2, 3 }); - public static readonly byte[] UInt32Array_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt32Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, IccTestDataPrimitives.UInt32_2, - IccTestDataPrimitives.UInt32_3 - ); + IccTestDataPrimitives.UInt32_3); public static readonly object[][] UInt32ArrayTagDataEntryTestData = { @@ -866,12 +757,10 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region UInt64ArrayTagDataEntry public static readonly IccUInt64ArrayTagDataEntry UInt64Array_Val = new IccUInt64ArrayTagDataEntry(new ulong[] { 1, 2, 3 }); - public static readonly byte[] UInt64Array_Arr = ArrayHelper.Concat - ( + public static readonly byte[] UInt64Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt64_1, IccTestDataPrimitives.UInt64_2, - IccTestDataPrimitives.UInt64_3 - ); + IccTestDataPrimitives.UInt64_3); public static readonly object[][] UInt64ArrayTagDataEntryTestData = { @@ -894,18 +783,15 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region ViewingConditionsTagDataEntry - public static readonly IccViewingConditionsTagDataEntry ViewingConditions_Val = new IccViewingConditionsTagDataEntry - ( + public static readonly IccViewingConditionsTagDataEntry ViewingConditions_Val = new IccViewingConditionsTagDataEntry( IccTestDataNonPrimitives.XyzNumber_ValVar1, IccTestDataNonPrimitives.XyzNumber_ValVar2, - IccStandardIlluminant.D50 - ); - public static readonly byte[] ViewingConditions_Arr = ArrayHelper.Concat - ( + IccStandardIlluminant.D50); + + public static readonly byte[] ViewingConditions_Arr = ArrayHelper.Concat( IccTestDataNonPrimitives.XyzNumber_Var1, IccTestDataNonPrimitives.XyzNumber_Var2, - IccTestDataPrimitives.UInt32_1 - ); + IccTestDataPrimitives.UInt32_1); public static readonly object[][] ViewingConditionsTagDataEntryTestData = { @@ -922,12 +808,11 @@ private static IccLocalizedString CreateLocalizedString(string language, string IccTestDataNonPrimitives.XyzNumber_ValVar2, IccTestDataNonPrimitives.XyzNumber_ValVar3, }); - public static readonly byte[] XYZ_Arr = ArrayHelper.Concat - ( + + public static readonly byte[] XYZ_Arr = ArrayHelper.Concat( IccTestDataNonPrimitives.XyzNumber_Var1, IccTestDataNonPrimitives.XyzNumber_Var2, - IccTestDataNonPrimitives.XyzNumber_Var3 - ); + IccTestDataNonPrimitives.XyzNumber_Var3); public static readonly object[][] XYZTagDataEntryTestData = { @@ -938,40 +823,34 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region TextDescriptionTagDataEntry - public static readonly IccTextDescriptionTagDataEntry TextDescription_Val1 = new IccTextDescriptionTagDataEntry - ( - IccTestDataPrimitives.Ascii_ValRand, IccTestDataPrimitives.Unicode_ValRand1, ArrayHelper.Fill('A', 66), - 1701729619, 2 - ); - public static readonly byte[] TextDescription_Arr1 = ArrayHelper.Concat - ( - new byte[] { 0x00, 0x00, 0x00, 0x0B }, // 11 - IccTestDataPrimitives.Ascii_Rand, - new byte[] { 0x00 }, // Null terminator + public static readonly IccTextDescriptionTagDataEntry TextDescription_Val1 = new IccTextDescriptionTagDataEntry( + IccTestDataPrimitives.Ascii_ValRand, + IccTestDataPrimitives.Unicode_ValRand1, + ArrayHelper.Fill('A', 66), + 1701729619, + 2); - new byte[] { 0x65, 0x6E, 0x55, 0x53 }, // enUS - new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 + public static readonly byte[] TextDescription_Arr1 = ArrayHelper.Concat( + new byte[] { 0x00, 0x00, 0x00, 0x0B }, // 11 + IccTestDataPrimitives.Ascii_Rand, + new byte[] { 0x00 }, // Null terminator + new byte[] { 0x65, 0x6E, 0x55, 0x53 }, // enUS + new byte[] { 0x00, 0x00, 0x00, 0x0E }, // 14 IccTestDataPrimitives.Unicode_Rand1, - new byte[] { 0x00, 0x00 }, // Null terminator - - new byte[] { 0x00, 0x02, 0x43 }, // 2, 67 + new byte[] { 0x00, 0x00 }, // Null terminator + new byte[] { 0x00, 0x02, 0x43 }, // 2, 67 ArrayHelper.Fill((byte)0x41, 66), - new byte[] { 0x00 } // Null terminator - ); + new byte[] { 0x00 }); // Null terminator public static readonly IccTextDescriptionTagDataEntry TextDescription_Val2 = new IccTextDescriptionTagDataEntry(IccTestDataPrimitives.Ascii_ValRand, null, null, 0, 0); - public static readonly byte[] TextDescription_Arr2 = ArrayHelper.Concat - ( + public static readonly byte[] TextDescription_Arr2 = ArrayHelper.Concat( new byte[] { 0x00, 0x00, 0x00, 0x0B }, // 11 IccTestDataPrimitives.Ascii_Rand, new byte[] { 0x00 }, // Null terminator - IccTestDataPrimitives.UInt32_0, IccTestDataPrimitives.UInt32_0, - new byte[] { 0x00, 0x00, 0x00 }, // 0, 0 - ArrayHelper.Fill((byte)0x00, 67) - ); + ArrayHelper.Fill((byte)0x00, 67)); public static readonly object[][] TextDescriptionTagDataEntryTestData = { @@ -988,10 +867,9 @@ private static IccLocalizedString CreateLocalizedString(string language, string IccTestDataPrimitives.Ascii_ValRand1, IccTestDataPrimitives.Ascii_ValRand2, IccTestDataPrimitives.Ascii_ValRand3, - IccTestDataPrimitives.Ascii_ValRand4 - ); - public static readonly byte[] CrdInfo_Arr = ArrayHelper.Concat - ( + IccTestDataPrimitives.Ascii_ValRand4); + + public static readonly byte[] CrdInfo_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_6, IccTestDataPrimitives.Ascii_Rand4, new byte[] { 0 }, @@ -1006,8 +884,7 @@ private static IccLocalizedString CreateLocalizedString(string language, string new byte[] { 0 }, IccTestDataPrimitives.UInt32_6, IccTestDataPrimitives.Ascii_Rand4, - new byte[] { 0 } - ); + new byte[] { 0 }); public static readonly object[][] CrdInfoTagDataEntryTestData = { @@ -1020,19 +897,13 @@ private static IccLocalizedString CreateLocalizedString(string language, string public static readonly IccScreeningTagDataEntry Screening_Val = new IccScreeningTagDataEntry( IccScreeningFlag.DefaultScreens | IccScreeningFlag.UnitLinesPerCm, - new IccScreeningChannel[] - { - IccTestDataNonPrimitives.ScreeningChannel_ValRand1, - IccTestDataNonPrimitives.ScreeningChannel_ValRand2, - } - ); - public static readonly byte[] Screening_Arr = ArrayHelper.Concat - ( + new IccScreeningChannel[] { IccTestDataNonPrimitives.ScreeningChannel_ValRand1, IccTestDataNonPrimitives.ScreeningChannel_ValRand2 }); + + public static readonly byte[] Screening_Arr = ArrayHelper.Concat( IccTestDataPrimitives.Int32_1, IccTestDataPrimitives.UInt32_2, IccTestDataNonPrimitives.ScreeningChannel_Rand1, - IccTestDataNonPrimitives.ScreeningChannel_Rand2 - ); + IccTestDataNonPrimitives.ScreeningChannel_Rand2); public static readonly object[][] ScreeningTagDataEntryTestData = { @@ -1046,24 +917,20 @@ private static IccLocalizedString CreateLocalizedString(string language, string public static readonly IccUcrBgTagDataEntry UcrBg_Val = new IccUcrBgTagDataEntry( new ushort[] { 3, 4, 6 }, new ushort[] { 9, 7, 2, 5 }, - IccTestDataPrimitives.Ascii_ValRand - ); - public static readonly byte[] UcrBg_Arr = ArrayHelper.Concat - ( + IccTestDataPrimitives.Ascii_ValRand); + + public static readonly byte[] UcrBg_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_3, IccTestDataPrimitives.UInt16_3, IccTestDataPrimitives.UInt16_4, IccTestDataPrimitives.UInt16_6, - IccTestDataPrimitives.UInt32_4, IccTestDataPrimitives.UInt16_9, IccTestDataPrimitives.UInt16_7, IccTestDataPrimitives.UInt16_2, IccTestDataPrimitives.UInt16_5, - IccTestDataPrimitives.Ascii_Rand, - new byte[] { 0 } - ); + new byte[] { 0 }); public static readonly object[][] UcrBgTagDataEntryTestData = { @@ -1075,32 +942,23 @@ private static IccLocalizedString CreateLocalizedString(string language, string #region TagDataEntry public static readonly IccTagDataEntry TagDataEntry_CurveVal = Curve_Val_2; - public static readonly byte[] TagDataEntry_CurveArr = ArrayHelper.Concat - ( + public static readonly byte[] TagDataEntry_CurveArr = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, Curve_Arr_2, - new byte[] { 0x00, 0x00 } // padding - ); + new byte[] { 0x00, 0x00 }); // padding public static readonly IccTagDataEntry TagDataEntry_MultiLocalizedUnicodeVal = MultiLocalizedUnicode_Val; - public static readonly byte[] TagDataEntry_MultiLocalizedUnicodeArr = ArrayHelper.Concat - ( + public static readonly byte[] TagDataEntry_MultiLocalizedUnicodeArr = ArrayHelper.Concat( TagDataEntryHeader_MultiLocalizedUnicodeArr, MultiLocalizedUnicode_Arr, - new byte[] { 0x00, 0x00 } // padding - ); - - public static readonly IccTagTableEntry TagDataEntry_MultiLocalizedUnicodeTable = new IccTagTableEntry - ( - IccProfileTag.Unknown, 0, - (uint)TagDataEntry_MultiLocalizedUnicodeArr.Length - 2 - ); - - public static readonly IccTagTableEntry TagDataEntry_CurveTable = new IccTagTableEntry - ( - IccProfileTag.Unknown, 0, - (uint)TagDataEntry_CurveArr.Length - 2 - ); + new byte[] { 0x00, 0x00 }); // padding + + public static readonly IccTagTableEntry TagDataEntry_MultiLocalizedUnicodeTable = new IccTagTableEntry( + IccProfileTag.Unknown, + 0, + (uint)TagDataEntry_MultiLocalizedUnicodeArr.Length - 2); + + public static readonly IccTagTableEntry TagDataEntry_CurveTable = new IccTagTableEntry(IccProfileTag.Unknown, 0, (uint)TagDataEntry_CurveArr.Length - 2); public static readonly object[][] TagDataEntryTestData = { diff --git a/tests/ImageSharp.Tests/TestFile.cs b/tests/ImageSharp.Tests/TestFile.cs index 8219920909..bd185fa6b2 100644 --- a/tests/ImageSharp.Tests/TestFile.cs +++ b/tests/ImageSharp.Tests/TestFile.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. using System; @@ -25,7 +25,7 @@ public class TestFile /// The "Formats" directory, as lazy value /// // ReSharper disable once InconsistentNaming - private static readonly Lazy inputImagesDirectory = new Lazy(() => TestEnvironment.InputImagesDirectoryFullPath); + private static readonly Lazy InputImagesDirectoryValue = new Lazy(() => TestEnvironment.InputImagesDirectoryFullPath); /// /// The image (lazy initialized value) @@ -52,17 +52,17 @@ private TestFile(string file) public byte[] Bytes => this.bytes ?? (this.bytes = File.ReadAllBytes(this.FullPath)); /// - /// The full path to file. + /// Gets the full path to file. /// public string FullPath { get; } /// - /// The file name. + /// Gets the file name. /// public string FileName => Path.GetFileName(this.FullPath); /// - /// The file name without extension. + /// Gets the file name without extension. /// public string FileNameWithoutExtension => Path.GetFileNameWithoutExtension(this.FullPath); @@ -74,7 +74,7 @@ private TestFile(string file) /// /// Gets the input image directory. /// - private static string InputImagesDirectory => inputImagesDirectory.Value; + private static string InputImagesDirectory => InputImagesDirectoryValue.Value; /// /// Gets the full qualified path to the input test file. diff --git a/tests/ImageSharp.Tests/TestFont.cs b/tests/ImageSharp.Tests/TestFontUtilities.cs similarity index 91% rename from tests/ImageSharp.Tests/TestFont.cs rename to tests/ImageSharp.Tests/TestFontUtilities.cs index c01f50f203..e087516c68 100644 --- a/tests/ImageSharp.Tests/TestFont.cs +++ b/tests/ImageSharp.Tests/TestFontUtilities.cs @@ -40,11 +40,12 @@ public static string GetPath(string file) /// private static string GetFontsDirectory() { - List directories = new List { + List directories = new List + { "TestFonts/", // Here for code coverage tests. - "tests/ImageSharp.Tests/TestFonts/", // from travis/build script - "../../../../../ImageSharp.Tests/TestFonts/", // from Sandbox46 - "../../../../TestFonts/" + "tests/ImageSharp.Tests/TestFonts/", // from travis/build script + "../../../../../ImageSharp.Tests/TestFonts/", // from Sandbox46 + "../../../../TestFonts/" }; directories = directories.SelectMany(x => new[] diff --git a/tests/ImageSharp.Tests/TestFormat.cs b/tests/ImageSharp.Tests/TestFormat.cs index 0f44b8e1cc..5a791e5a10 100644 --- a/tests/ImageSharp.Tests/TestFormat.cs +++ b/tests/ImageSharp.Tests/TestFormat.cs @@ -47,6 +47,7 @@ public MemoryStream CreateStream(byte[] marker = null) { ms.Write(marker, 0, marker.Length); } + ms.Position = 0; return ms; } @@ -56,7 +57,6 @@ public void VerifySpecificDecodeCall(byte[] marker, Configuration config { DecodeOperation[] discovered = this.DecodeCalls.Where(x => x.IsMatch(marker, config, typeof(TPixel))).ToArray(); - Assert.True(discovered.Any(), "No calls to decode on this format with the provided options happened"); foreach (DecodeOperation d in discovered) @@ -69,7 +69,6 @@ public void VerifyAgnosticDecodeCall(byte[] marker, Configuration config) { DecodeOperation[] discovered = this.DecodeCalls.Where(x => x.IsMatch(marker, config, typeof(TestPixelForAgnosticDecode))).ToArray(); - Assert.True(discovered.Any(), "No calls to decode on this format with the provided options happened"); foreach (DecodeOperation d in discovered) @@ -116,6 +115,7 @@ public bool IsSupportedFileFormat(ReadOnlySpan header) { return false; } + for (int i = 0; i < this.header.Length; i++) { if (header[i] != this.header[i]) @@ -123,6 +123,7 @@ public bool IsSupportedFileFormat(ReadOnlySpan header) return false; } } + return true; } @@ -135,38 +136,37 @@ public void Configure(Configuration host) public struct DecodeOperation { - public byte[] marker; - internal Configuration config; + public byte[] Marker; + internal Configuration Config; - public Type pixelType; + public Type PixelType; public bool IsMatch(byte[] testMarker, Configuration config, Type pixelType) { - - if (this.config != config || this.pixelType != pixelType) + if (this.Config != config || this.PixelType != pixelType) { return false; } - if (testMarker.Length != this.marker.Length) + if (testMarker.Length != this.Marker.Length) { return false; } - for (int i = 0; i < this.marker.Length; i++) + for (int i = 0; i < this.Marker.Length; i++) { - if (testMarker[i] != this.marker[i]) + if (testMarker[i] != this.Marker[i]) { return false; } } + return true; } } public class TestHeader : IImageFormatDetector { - private TestFormat testFormat; public int HeaderSize => this.testFormat.HeaderSize; @@ -174,7 +174,9 @@ public class TestHeader : IImageFormatDetector public IImageFormat DetectFormat(ReadOnlySpan header) { if (this.testFormat.IsSupportedFileFormat(header)) + { return this.testFormat; + } return null; } @@ -184,6 +186,7 @@ public TestHeader(TestFormat testFormat) this.testFormat = testFormat; } } + public class TestDecoder : ImageSharp.Formats.IImageDecoder { private TestFormat testFormat; @@ -193,30 +196,30 @@ public TestDecoder(TestFormat testFormat) this.testFormat = testFormat; } - public IEnumerable MimeTypes => new[] { testFormat.MimeType }; - - public IEnumerable FileExtensions => testFormat.SupportedExtensions; + public IEnumerable MimeTypes => new[] { this.testFormat.MimeType }; - public int HeaderSize => testFormat.HeaderSize; + public IEnumerable FileExtensions => this.testFormat.SupportedExtensions; - public Image Decode(Configuration config, Stream stream) where TPixel : struct, IPixel + public int HeaderSize => this.testFormat.HeaderSize; + public Image Decode(Configuration config, Stream stream) + where TPixel : struct, IPixel { var ms = new MemoryStream(); stream.CopyTo(ms); var marker = ms.ToArray().Skip(this.testFormat.header.Length).ToArray(); this.testFormat.DecodeCalls.Add(new DecodeOperation { - marker = marker, - config = config, - pixelType = typeof(TPixel) + Marker = marker, + Config = config, + PixelType = typeof(TPixel) }); // TODO record this happened so we can verify it. return this.testFormat.Sample(); } - public bool IsSupportedFileFormat(Span header) => testFormat.IsSupportedFileFormat(header); + public bool IsSupportedFileFormat(Span header) => this.testFormat.IsSupportedFileFormat(header); public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); } @@ -230,37 +233,85 @@ public TestEncoder(TestFormat testFormat) this.testFormat = testFormat; } - public IEnumerable MimeTypes => new[] { testFormat.MimeType }; + public IEnumerable MimeTypes => new[] { this.testFormat.MimeType }; - public IEnumerable FileExtensions => testFormat.SupportedExtensions; + public IEnumerable FileExtensions => this.testFormat.SupportedExtensions; - public void Encode(Image image, Stream stream) where TPixel : struct, IPixel + public void Encode(Image image, Stream stream) + where TPixel : struct, IPixel { // TODO record this happened so we can verify it. } } - - struct TestPixelForAgnosticDecode : IPixel + public struct TestPixelForAgnosticDecode : IPixel { public PixelOperations CreatePixelOperations() => new PixelOperations(); - public void FromScaledVector4(Vector4 vector) { } + + public void FromScaledVector4(Vector4 vector) + { + } + public Vector4 ToScaledVector4() => default; - public void FromVector4(Vector4 vector) { } + + public void FromVector4(Vector4 vector) + { + } + public Vector4 ToVector4() => default; - public void FromArgb32(Argb32 source) { } - public void FromBgra5551(Bgra5551 source) { } - public void FromBgr24(Bgr24 source) { } - public void FromBgra32(Bgra32 source) { } - public void FromL8(L8 source) { } - public void FromL16(L16 source) { } - public void FromLa16(La16 source) { } - public void FromLa32(La32 source) { } - public void FromRgb24(Rgb24 source) { } - public void FromRgba32(Rgba32 source) { } - public void ToRgba32(ref Rgba32 dest) { } - public void FromRgb48(Rgb48 source) { } - public void FromRgba64(Rgba64 source) { } + + public void FromArgb32(Argb32 source) + { + } + + public void FromBgra5551(Bgra5551 source) + { + } + + public void FromBgr24(Bgr24 source) + { + } + + public void FromBgra32(Bgra32 source) + { + } + + public void FromL8(L8 source) + { + } + + public void FromL16(L16 source) + { + } + + public void FromLa16(La16 source) + { + } + + public void FromLa32(La32 source) + { + } + + public void FromRgb24(Rgb24 source) + { + } + + public void FromRgba32(Rgba32 source) + { + } + + public void ToRgba32(ref Rgba32 dest) + { + } + + public void FromRgb48(Rgb48 source) + { + } + + public void FromRgba64(Rgba64 source) + { + } + public bool Equals(TestPixelForAgnosticDecode other) => false; } } diff --git a/tests/ImageSharp.Tests/TestImages.cs b/tests/ImageSharp.Tests/TestImages.cs index f5cdb29b63..099d501a90 100644 --- a/tests/ImageSharp.Tests/TestImages.cs +++ b/tests/ImageSharp.Tests/TestImages.cs @@ -2,8 +2,8 @@ // Licensed under the Apache License, Version 2.0. using System.Linq; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming // ReSharper disable MemberHidesStaticFromOuterClass namespace SixLabors.ImageSharp.Tests { @@ -310,8 +310,8 @@ public static class Bmp public const string Rgba321010102 = "Bmp/rgba32-1010102.bmp"; public const string RgbaAlphaBitfields = "Bmp/rgba32abf.bmp"; - public static readonly string[] BitFields - = { + public static readonly string[] BitFields = + { Rgb32bfdef, Rgb32bf, Rgb16565, @@ -320,32 +320,32 @@ public static readonly string[] BitFields Issue735, }; - public static readonly string[] Miscellaneous - = { + public static readonly string[] Miscellaneous = + { Car, F, NegHeight }; - public static readonly string[] Benchmark - = { - Car, - F, - NegHeight, - CoreHeader, - V5Header, - RLE4, - RLE8, - RLE8Inverted, - Bit1, - Bit1Pal1, - Bit4, - Bit8, - Bit8Inverted, - Bit16, - Bit16Inverted, - Bit32Rgb - }; + public static readonly string[] Benchmark = + { + Car, + F, + NegHeight, + CoreHeader, + V5Header, + RLE4, + RLE8, + RLE8Inverted, + Bit1, + Bit1Pal1, + Bit4, + Bit8, + Bit8Inverted, + Bit16, + Bit16Inverted, + Bit32Rgb + }; } public static class Gif diff --git a/tests/ImageSharp.Tests/TestUtilities/ApproximateFloatComparer.cs b/tests/ImageSharp.Tests/TestUtilities/ApproximateFloatComparer.cs index 872a935ffe..0a21fd4d9e 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ApproximateFloatComparer.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ApproximateFloatComparer.cs @@ -16,20 +16,20 @@ namespace SixLabors.ImageSharp.Tests IEqualityComparer, IEqualityComparer { - private readonly float Epsilon; + private readonly float epsilon; /// /// Initializes a new instance of the class. /// /// The comparison error difference epsilon to use. - public ApproximateFloatComparer(float epsilon = 1F) => this.Epsilon = epsilon; + public ApproximateFloatComparer(float epsilon = 1F) => this.epsilon = epsilon; /// public bool Equals(float x, float y) { float d = x - y; - return d >= -this.Epsilon && d <= this.Epsilon; + return d >= -this.epsilon && d <= this.epsilon; } /// @@ -61,4 +61,4 @@ public bool Equals(ColorMatrix x, ColorMatrix y) /// public int GetHashCode(ColorMatrix obj) => obj.GetHashCode(); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ArrayHelper.cs b/tests/ImageSharp.Tests/TestUtilities/ArrayHelper.cs index fdb694dccb..eceecb2c83 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ArrayHelper.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ArrayHelper.cs @@ -22,6 +22,7 @@ public static T[] Concat(params T[][] arrays) arrays[i].CopyTo(result, offset); offset += arrays[i].Length; } + return result; } @@ -39,6 +40,7 @@ public static T[] Fill(T value, int length) { result[i] = value; } + return result; } @@ -50,7 +52,7 @@ public static T[] Fill(T value, int length) /// The filled string public static string Fill(char value, int length) { - return "".PadRight(length, value); + return string.Empty.PadRight(length, value); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/GroupOutputAttribute.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/GroupOutputAttribute.cs index b2967058c0..3287311bf1 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/GroupOutputAttribute.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/GroupOutputAttribute.cs @@ -1,4 +1,7 @@ -namespace SixLabors.ImageSharp.Tests +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Tests { using System; @@ -14,4 +17,4 @@ public GroupOutputAttribute(string subfolder) public string Subfolder { get; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/ImageDataAttributeBase.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/ImageDataAttributeBase.cs index f03d68307b..976bb9a968 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/ImageDataAttributeBase.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/ImageDataAttributeBase.cs @@ -21,9 +21,6 @@ public abstract class ImageDataAttributeBase : DataAttribute /// /// Initializes a new instance of the class. /// - /// - /// - /// protected ImageDataAttributeBase(string memberName, PixelTypes pixelTypes, object[] additionalParameters) { this.PixelTypes = pixelTypes; @@ -32,12 +29,12 @@ protected ImageDataAttributeBase(string memberName, PixelTypes pixelTypes, objec } /// - /// Gets the member name + /// Gets the member name. /// public string MemberName { get; } /// - /// Gets the member type + /// Gets or sets the member type. /// public Type MemberType { get; set; } @@ -84,8 +81,7 @@ public override IEnumerable GetData(MethodInfo testMethod) /// /// Returns a value indicating whether the first parameter of the method is a test provider. /// - /// - /// + /// True, if the first parameter is a test provider. private bool FirstIsProvider(MethodInfo testMethod) { TypeInfo dataType = testMethod.GetParameters().First().ParameterType.GetTypeInfo(); @@ -102,7 +98,7 @@ private IEnumerable InnerGetData(MethodInfo testMethod, IEnumerable InnerGetData(MethodInfo testMethod, IEnumerable /// Gets the field accessor for the given type. /// + /// The field accessor. protected Func GetFieldAccessor(Type type, string memberName) { FieldInfo fieldInfo = null; @@ -160,11 +157,15 @@ protected Func GetFieldAccessor(Type type, string memberName) { fieldInfo = reflectionType.GetRuntimeField(memberName); if (fieldInfo != null) + { break; + } } - if (fieldInfo == null || !fieldInfo.IsStatic) + if (fieldInfo is null || !fieldInfo.IsStatic) + { return null; + } return () => fieldInfo.GetValue(null); } @@ -172,6 +173,7 @@ protected Func GetFieldAccessor(Type type, string memberName) /// /// Gets the property accessor for the given type. /// + /// The property accessor. protected Func GetPropertyAccessor(Type type, string memberName) { PropertyInfo propInfo = null; @@ -184,7 +186,7 @@ protected Func GetPropertyAccessor(Type type, string memberName) } } - if (propInfo?.GetMethod == null || !propInfo.GetMethod.IsStatic) + if (propInfo?.GetMethod is null || !propInfo.GetMethod.IsStatic) { return null; } diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImageAttribute.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImagesAttribute.cs similarity index 99% rename from tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImageAttribute.cs rename to tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImagesAttribute.cs index 796cba8554..051bfecdcf 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImageAttribute.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithBlankImagesAttribute.cs @@ -42,10 +42,11 @@ public WithBlankImagesAttribute(string memberData, int width, int height, PixelT } public int Width { get; } + public int Height { get; } protected override string GetFactoryMethodName(MethodInfo testMethod) => "Blank"; protected override object[] GetFactoryMethodArgs(MethodInfo testMethod, Type factoryType) => new object[] { this.Width, this.Height }; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithSolidFilledImagesAttribute.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithSolidFilledImagesAttribute.cs index 190e80fbad..5c67b5d138 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithSolidFilledImagesAttribute.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithSolidFilledImagesAttribute.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. using System; @@ -141,22 +141,22 @@ public WithSolidFilledImagesAttribute( } /// - /// Red + /// Gets the red component. /// public byte R { get; } /// - /// Green + /// Gets the green component. /// public byte G { get; } /// - /// Blue + /// Gets the blue component. /// public byte B { get; } /// - /// Alpha + /// Gets the alpha component. /// public byte A { get; } @@ -165,4 +165,4 @@ protected override object[] GetFactoryMethodArgs(MethodInfo testMethod, Type fac protected override string GetFactoryMethodName(MethodInfo testMethod) => "Solid"; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs index 7c659c64fc..e4a9b2bdd1 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.Tests /// Triggers passing instances which produce a blank image of size width * height. /// One instance will be passed for each the pixel format defined by the pixelTypes parameter /// - public class WithTestPatternImagesAttribute : ImageDataAttributeBase + public class WithTestPatternImageAttribute : ImageDataAttributeBase { /// /// Triggers passing an that produces a test pattern image of size width * height @@ -19,7 +19,7 @@ public class WithTestPatternImagesAttribute : ImageDataAttributeBase /// The required height /// The requested parameter /// Additional theory parameter values - public WithTestPatternImagesAttribute(int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) + public WithTestPatternImageAttribute(int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) : this(null, width, height, pixelTypes, additionalParameters) { } @@ -32,7 +32,7 @@ public WithTestPatternImagesAttribute(int width, int height, PixelTypes pixelTyp /// The required height /// The requested parameter /// Additional theory parameter values - public WithTestPatternImagesAttribute(string memberData, int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) + public WithTestPatternImageAttribute(string memberData, int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) : base(memberData, pixelTypes, additionalParameters) { this.Width = width; diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ExactImageComparer.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ExactImageComparer.cs index 59167cc888..0edfd8e9bb 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ExactImageComparer.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ExactImageComparer.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Collections.Generic; using SixLabors.ImageSharp.Advanced; @@ -23,7 +26,6 @@ public override ImageSimilarityReport CompareImagesOrFrames report sb.Append(Environment.NewLine); i++; } + return sb.ToString(); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImageDimensionsMismatchException.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImageDimensionsMismatchException.cs index 024c2ee215..b4a94d9b28 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImageDimensionsMismatchException.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImageDimensionsMismatchException.cs @@ -15,6 +15,7 @@ public ImageDimensionsMismatchException(Size expectedSize, Size actualSize) } public Size ExpectedSize { get; } + public Size ActualSize { get; } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImagesSimilarityException.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImagesSimilarityException.cs index bbdb6b5815..d84f1c358a 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImagesSimilarityException.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/Exceptions/ImagesSimilarityException.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + namespace SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison { using System; @@ -9,4 +12,4 @@ public ImagesSimilarityException(string message) { } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageComparer.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageComparer.cs index 38dada063c..3e92d16940 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageComparer.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageComparer.cs @@ -18,6 +18,7 @@ public abstract class ImageComparer /// Returns an instance of . /// Individual manhattan pixel difference is only added to total image difference when the individual difference is over 'perPixelManhattanThreshold'. /// + /// A ImageComparer instance. public static ImageComparer Tolerant( float imageThreshold = TolerantImageComparer.DefaultImageThreshold, int perPixelManhattanThreshold = 0) @@ -28,13 +29,15 @@ public static ImageComparer Tolerant( /// /// Returns Tolerant(imageThresholdInPercents/100) /// + /// A ImageComparer instance. public static ImageComparer TolerantPercentage(float imageThresholdInPercents, int perPixelManhattanThreshold = 0) => Tolerant(imageThresholdInPercents / 100F, perPixelManhattanThreshold); public abstract ImageSimilarityReport CompareImagesOrFrames( ImageFrame expected, ImageFrame actual) - where TPixelA : struct, IPixel where TPixelB : struct, IPixel; + where TPixelA : struct, IPixel + where TPixelB : struct, IPixel; } public static class ImageComparerExtensions @@ -43,7 +46,8 @@ public static ImageSimilarityReport CompareImagesOrFrames expected, Image actual) - where TPixelA : struct, IPixel where TPixelB : struct, IPixel + where TPixelA : struct, IPixel + where TPixelB : struct, IPixel { return comparer.CompareImagesOrFrames(expected.Frames.RootFrame, actual.Frames.RootFrame); } @@ -52,7 +56,8 @@ public static IEnumerable> CompareImages this ImageComparer comparer, Image expected, Image actual) - where TPixelA : struct, IPixel where TPixelB : struct, IPixel + where TPixelA : struct, IPixel + where TPixelB : struct, IPixel { var result = new List>(); @@ -60,6 +65,7 @@ public static IEnumerable> CompareImages { throw new Exception("Frame count does not match!"); } + for (int i = 0; i < expected.Frames.Count; i++) { ImageSimilarityReport report = comparer.CompareImagesOrFrames(expected.Frames[i], actual.Frames[i]); @@ -76,7 +82,8 @@ public static void VerifySimilarity( this ImageComparer comparer, Image expected, Image actual) - where TPixelA : struct, IPixel where TPixelB : struct, IPixel + where TPixelA : struct, IPixel + where TPixelB : struct, IPixel { if (expected.Size() != actual.Size()) { @@ -139,4 +146,4 @@ public static void VerifySimilarityIgnoreRegion( } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageSimilarityReport.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageSimilarityReport.cs index f534079769..f054ce8f9f 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageSimilarityReport.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/ImageSimilarityReport.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -63,6 +66,7 @@ private string PrintDifference() sb.AppendLine(); sb.AppendLine($"Total difference: {this.DifferencePercentageString}"); } + int max = Math.Min(5, this.Differences.Length); for (int i = 0; i < max; i++) @@ -73,10 +77,12 @@ private string PrintDifference() sb.AppendFormat(";{0}", Environment.NewLine); } } + if (this.Differences.Length >= 5) { sb.Append("..."); } + return sb.ToString(); } } @@ -101,4 +107,4 @@ public ImageSimilarityReport( public new ImageFrame ActualImage => (ImageFrame)base.ActualImage; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/PixelDifference.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/PixelDifference.cs index 1ffeb60ad4..d7819c28fb 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/PixelDifference.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/PixelDifference.cs @@ -1,4 +1,7 @@ -using SixLabors.ImageSharp.PixelFormats; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using SixLabors.ImageSharp.PixelFormats; using SixLabors.Primitives; namespace SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison @@ -20,7 +23,8 @@ public PixelDifference( } public PixelDifference(Point position, Rgba64 expected, Rgba64 actual) - : this(position, + : this( + position, actual.R - expected.R, actual.G - expected.G, actual.B - expected.B, @@ -31,11 +35,14 @@ public PixelDifference(Point position, Rgba64 expected, Rgba64 actual) public Point Position { get; } public int RedDifference { get; } + public int GreenDifference { get; } + public int BlueDifference { get; } + public int AlphaDifference { get; } public override string ToString() => $"[Δ({this.RedDifference},{this.GreenDifference},{this.BlueDifference},{this.AlphaDifference}) @ ({this.Position.X},{this.Position.Y})]"; } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/TolerantImageComparer.cs b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/TolerantImageComparer.cs index 8bed3a7155..06421378ab 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageComparison/TolerantImageComparer.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageComparison/TolerantImageComparer.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -67,7 +70,6 @@ public override ImageSimilarityReport CompareImagesOrFrames GetImage() => new Image(this.Configuration, this.Width, this.Height); - public override void Deserialize(IXunitSerializationInfo info) { this.Width = info.GetValue("width"); @@ -51,4 +50,4 @@ public override void Serialize(IXunitSerializationInfo info) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/FileProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/FileProvider.cs index 8c5b88b280..362217efbe 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/FileProvider.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/FileProvider.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. using System; @@ -48,8 +48,10 @@ private static Dictionary GetDecoderParameters(IImageDecoder cus object value = p.GetValue(customDecoder); data[key] = value; } + type = type.GetTypeInfo().BaseType; } + return data; } @@ -81,11 +83,13 @@ public bool Equals(Key other) { return false; } + if (!object.Equals(kv.Value, otherVal)) { return false; } } + return true; } @@ -116,7 +120,7 @@ public override bool Equals(object obj) public static bool operator !=(Key left, Key right) => !Equals(left, right); } - private static readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary> Cache = new ConcurrentDictionary>(); // Needed for deserialization! // ReSharper disable once UnusedMember.Local @@ -150,7 +154,7 @@ public override Image GetImage(IImageDecoder decoder) var key = new Key(this.PixelType, this.FilePath, decoder); - Image cachedImage = cache.GetOrAdd(key, _ => this.LoadImage(decoder)); + Image cachedImage = Cache.GetOrAdd(key, _ => this.LoadImage(decoder)); return cachedImage.Clone(this.Configuration); } @@ -181,4 +185,4 @@ public static string GetFilePathOrNull(ITestImageProvider provider) return fileProvider?.FilePath; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/SolidProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/SolidProvider.cs index e44de307ff..ef0d67adfe 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/SolidProvider.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/SolidProvider.cs @@ -1,15 +1,12 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. - using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; using Xunit.Abstractions; namespace SixLabors.ImageSharp.Tests { - /// /// Provides instances for parametric unit tests. /// diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs index 63de4c96f4..347e809c0a 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs @@ -16,7 +16,9 @@ namespace SixLabors.ImageSharp.Tests public interface ITestImageProvider { PixelTypes PixelType { get; } + ImagingTestCaseUtility Utility { get; } + string SourceFileOrDescription { get; } Configuration Configuration { get; set; } @@ -25,29 +27,32 @@ public interface ITestImageProvider /// /// Provides instances for parametric unit tests. /// - /// The pixel format of the image + /// The pixel format of the image. public abstract partial class TestImageProvider : ITestImageProvider where TPixel : struct, IPixel { public PixelTypes PixelType { get; private set; } = typeof(TPixel).GetPixelType(); - public virtual string SourceFileOrDescription => ""; + public virtual string SourceFileOrDescription => string.Empty; public Configuration Configuration { get; set; } = Configuration.CreateDefaultInstance(); /// - /// Utility instance to provide information about the test image & manage input/output + /// Gets the utility instance to provide information about the test image & manage input/output. /// public ImagingTestCaseUtility Utility { get; private set; } public string TypeName { get; private set; } + public string MethodName { get; private set; } + public string OutputSubfolderName { get; private set; } - public static TestImageProvider BasicTestPattern(int width, - int height, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) + public static TestImageProvider BasicTestPattern( + int width, + int height, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) => new BasicTestPatternProvider(width, height).Init(testMethod, pixelTypeOverride); public static TestImageProvider TestPattern( @@ -94,6 +99,7 @@ public static TestImageProvider Solid( /// /// Returns an instance to the test case with the necessary traits. /// + /// A test image. public abstract Image GetImage(); public virtual Image GetImage(IImageDecoder decoder) @@ -104,6 +110,7 @@ public virtual Image GetImage(IImageDecoder decoder) /// /// Returns an instance to the test case with the necessary traits. /// + /// A test image. public Image GetImage(Action operationsToApply) { Image img = this.GetImage(); @@ -139,6 +146,7 @@ protected TestImageProvider Init( { this.PixelType = pixelTypeOverride; } + this.TypeName = typeName; this.MethodName = methodName; this.OutputSubfolderName = outputSubfolderName; diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestPatternProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestPatternProvider.cs index 8965458cd0..df788641d8 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestPatternProvider.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestPatternProvider.cs @@ -18,17 +18,19 @@ public abstract partial class TestImageProvider /// private class TestPatternProvider : BlankProvider { - static readonly Dictionary> TestImages = new Dictionary>(); + private static readonly Dictionary> TestImages = new Dictionary>(); - private static TPixel[] BlackWhitePixels = new[] { + private static readonly TPixel[] BlackWhitePixels = + { Color.Black.ToPixel(), Color.White.ToPixel() - }; + }; - private static TPixel[] PinkBluePixels = new[] { + private static readonly TPixel[] PinkBluePixels = + { Color.HotPink.ToPixel(), Color.Blue.ToPixel() - }; + }; public TestPatternProvider(int width, int height) : base(width, height) @@ -50,10 +52,11 @@ public override Image GetImage() { if (!TestImages.ContainsKey(this.SourceFileOrDescription)) { - Image image = new Image(this.Width, this.Height); + var image = new Image(this.Width, this.Height); DrawTestPattern(image); TestImages.Add(this.SourceFileOrDescription, image); } + return TestImages[this.SourceFileOrDescription].Clone(this.Configuration); } } @@ -61,7 +64,7 @@ public override Image GetImage() /// /// Draws the test pattern on an image by drawing 4 other patterns in the for quadrants of the image. /// - /// + /// The image to rdaw on. private static void DrawTestPattern(Image image) { // first lets split the image into 4 quadrants @@ -75,7 +78,6 @@ private static void DrawTestPattern(Image image) /// /// Fills the top right quadrant with alternating solid vertical bars. /// - /// private static void VerticalBars(Buffer2D pixels) { // topLeft @@ -99,6 +101,7 @@ private static void VerticalBars(Buffer2D pixels) p++; p = p % PinkBluePixels.Length; } + pixels[x, y] = PinkBluePixels[p]; } } @@ -107,7 +110,6 @@ private static void VerticalBars(Buffer2D pixels) /// /// fills the top left quadrant with a black and white checker board. /// - /// private static void BlackWhiteChecker(Buffer2D pixels) { // topLeft @@ -120,21 +122,24 @@ private static void BlackWhiteChecker(Buffer2D pixels) int p = 0; for (int y = top; y < bottom; y++) { - if (y % stride == 0) + if (y % stride is 0) { p++; p = p % BlackWhitePixels.Length; } + int pstart = p; for (int x = left; x < right; x++) { - if (x % stride == 0) + if (x % stride is 0) { p++; p = p % BlackWhitePixels.Length; } + pixels[x, y] = BlackWhitePixels[p]; } + p = pstart; } } @@ -142,7 +147,6 @@ private static void BlackWhiteChecker(Buffer2D pixels) /// /// Fills the bottom left quadrant with 3 horizontal bars in Red, Green and Blue with a alpha gradient from left (transparent) to right (solid). /// - /// private static void TransparentGradients(Buffer2D pixels) { // topLeft @@ -152,11 +156,11 @@ private static void TransparentGradients(Buffer2D pixels) int bottom = pixels.Height; int height = (int)Math.Ceiling(pixels.Height / 6f); - Vector4 red = Rgba32.Red.ToVector4(); // use real color so we can see har it translates in the test pattern - Vector4 green = Rgba32.Green.ToVector4(); // use real color so we can see har it translates in the test pattern - Vector4 blue = Rgba32.Blue.ToVector4(); // use real color so we can see har it translates in the test pattern + var red = Rgba32.Red.ToVector4(); // use real color so we can see har it translates in the test pattern + var green = Rgba32.Green.ToVector4(); // use real color so we can see har it translates in the test pattern + var blue = Rgba32.Blue.ToVector4(); // use real color so we can see har it translates in the test pattern - TPixel c = default(TPixel); + var c = default(TPixel); for (int x = left; x < right; x++) { @@ -168,12 +172,14 @@ private static void TransparentGradients(Buffer2D pixels) { pixels[x, y] = c; } + topBand = topBand + height; c.FromVector4(green); for (int y = topBand; y < topBand + height; y++) { pixels[x, y] = c; } + topBand = topBand + height; c.FromVector4(blue); for (int y = topBand; y < bottom; y++) @@ -187,7 +193,6 @@ private static void TransparentGradients(Buffer2D pixels) /// Fills the bottom right quadrant with all the colors producible by converting iterating over a uint and unpacking it. /// A better algorithm could be used but it works /// - /// private static void Rainbow(Buffer2D pixels) { int left = pixels.Width / 2; @@ -205,8 +210,9 @@ private static void Rainbow(Buffer2D pixels) for (int y = top; y < bottom; y++) { t.PackedValue += stepsPerPixel; - Vector4 v = t.ToVector4(); - //v.W = (x - left) / (float)left; + var v = t.ToVector4(); + + // v.W = (x - left) / (float)left; c.FromVector4(v); pixels[x, y] = c; } diff --git a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs index 92cc9f6368..cce0c87126 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.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. using System; @@ -19,25 +19,26 @@ namespace SixLabors.ImageSharp.Tests public class ImagingTestCaseUtility { /// - /// Name of the TPixel in the owner + /// Gets or sets the name of the TPixel in the owner /// public string PixelTypeName { get; set; } = string.Empty; /// - /// The name of the file which is provided by + /// Gets or sets the name of the file which is provided by /// Or a short string describing the image in the case of a non-file based image provider. /// public string SourceFileOrDescription { get; set; } = string.Empty; /// - /// By default this is the name of the test class, but it's possible to change it + /// Gets or sets the test group name. + /// By default this is the name of the test class, but it's possible to change it. /// public string TestGroupName { get; set; } = string.Empty; public string OutputSubfolderName { get; set; } = string.Empty; /// - /// The name of the test case (by default) + /// Gets or sets the name of the test case (by default). /// public string TestName { get; set; } = string.Empty; @@ -54,7 +55,7 @@ private string GetTestOutputFileNameImpl( string fn = appendSourceFileOrDescription ? Path.GetFileNameWithoutExtension(this.SourceFileOrDescription) - : ""; + : string.Empty; if (string.IsNullOrWhiteSpace(extension)) { @@ -65,6 +66,7 @@ private string GetTestOutputFileNameImpl( { extension = ".bmp"; } + extension = extension.ToLower(); if (extension[0] != '.') @@ -77,7 +79,7 @@ private string GetTestOutputFileNameImpl( fn = '_' + fn; } - string pixName = ""; + string pixName = string.Empty; if (appendPixelTypeToFileName) { @@ -137,8 +139,7 @@ public string GetTestOutputFileName( detailsString = string.Join( "_", properties.ToDictionary(x => x.Name, x => x.GetValue(testOutputDetails)) - .Select(x => TestUtils.AsInvariantString($"{x.Key}-{x.Value}")) - ); + .Select(x => TestUtils.AsInvariantString($"{x.Key}-{x.Value}"))); } } @@ -152,12 +153,13 @@ public string GetTestOutputFileName( /// /// Encodes image by the format matching the required extension, than saves it to the recommended output file. /// - /// The image instance - /// The requested extension - /// Optional encoder - /// A value indicating whether to append the pixel type to the test output file name + /// The image instance. + /// The requested extension. + /// Optional encoder. + /// Additional information to append to the test output file name. + /// A value indicating whether to append the pixel type to the test output file name. /// A boolean indicating whether to append to the test output file name. - /// Additional information to append to the test output file name + /// The path to the saved image file. public string SaveTestOutputFile( Image image, string extension = null, @@ -189,7 +191,7 @@ public IEnumerable GetTestOutputFileNamesMultiFrame( bool appendPixelTypeToFileName = true, bool appendSourceFileOrDescription = true) { - string baseDir = this.GetTestOutputFileName("", testOutputDetails, appendPixelTypeToFileName, appendSourceFileOrDescription); + string baseDir = this.GetTestOutputFileName(string.Empty, testOutputDetails, appendPixelTypeToFileName, appendSourceFileOrDescription); if (!Directory.Exists(baseDir)) { @@ -241,8 +243,7 @@ internal string GetReferenceOutputFileName( bool appendSourceFileOrDescription) { return TestEnvironment.GetReferenceOutputFileName( - this.GetTestOutputFileName(extension, testOutputDetails, appendPixelTypeToFileName, appendSourceFileOrDescription) - ); + this.GetTestOutputFileName(extension, testOutputDetails, appendPixelTypeToFileName, appendSourceFileOrDescription)); } public string[] GetReferenceOutputFileNamesMultiFrame( @@ -325,4 +326,4 @@ public static void ModifyPixel(ImageFrame img, int x, int y, byt img[x, y] = pixel; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/MeasureFixture.cs b/tests/ImageSharp.Tests/TestUtilities/MeasureFixture.cs index 61bd7cd9fb..b01ece7ba3 100644 --- a/tests/ImageSharp.Tests/TestUtilities/MeasureFixture.cs +++ b/tests/ImageSharp.Tests/TestUtilities/MeasureFixture.cs @@ -16,7 +16,7 @@ public class MeasureFixture /// /// Value indicating whether printing is enabled. /// - protected bool EnablePrinting = true; + protected bool enablePrinting = true; /// /// Measures and prints the execution time of an , executed multiple times. @@ -26,7 +26,7 @@ public class MeasureFixture /// The name of the operation to print to the output public void Measure(int times, Action action, [CallerMemberName] string operationName = null) { - if (this.EnablePrinting) + if (this.enablePrinting) { this.Output?.WriteLine($"{operationName} X {times} ..."); } @@ -39,7 +39,7 @@ public void Measure(int times, Action action, [CallerMemberName] string operatio } sw.Stop(); - if (this.EnablePrinting) + if (this.enablePrinting) { this.Output?.WriteLine($"{operationName} finished in {sw.ElapsedMilliseconds} ms"); } diff --git a/tests/ImageSharp.Tests/TestUtilities/PixelTypes.cs b/tests/ImageSharp.Tests/TestUtilities/PixelTypes.cs index 0c7334d007..9ef95cbf74 100644 --- a/tests/ImageSharp.Tests/TestUtilities/PixelTypes.cs +++ b/tests/ImageSharp.Tests/TestUtilities/PixelTypes.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. using System; @@ -12,6 +12,7 @@ namespace SixLabors.ImageSharp.Tests [Flags] public enum PixelTypes { +#pragma warning disable SA1602 // Enumeration items should be documented Undefined = 0, A8 = 1 << 0, @@ -66,5 +67,7 @@ public enum PixelTypes // "All" is handled as a separate, individual case instead of using bitwise OR All = 30 + +#pragma warning restore SA1602 // Enumeration items should be documented } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs index e81714ddc4..58afd48a7e 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs @@ -57,7 +57,7 @@ public Image Decode(Configuration configuration, Stream stream) return result; } } - + public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs index 79c19f2be7..87ec827af0 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.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. using System; @@ -128,6 +128,7 @@ internal static unsafe Image From24bppRgbSystemDrawingBitmap(Bit { bmp.UnlockBits(data); } + return image; } @@ -171,4 +172,4 @@ internal static unsafe Bitmap To32bppArgbSystemDrawingBitmap(Image this.Decode(configuration, stream); } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.Formats.cs b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.Formats.cs index e09b27c714..d49c34efd9 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.Formats.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.Formats.cs @@ -55,8 +55,7 @@ private static Configuration CreateDefaultConfiguration() var cfg = new Configuration( new JpegConfigurationModule(), new GifConfigurationModule(), - new TgaConfigurationModule() - ); + new TgaConfigurationModule()); // Magick codecs should work on all platforms IImageEncoder pngEncoder = IsWindows ? (IImageEncoder)SystemDrawingReferenceEncoder.Png : new PngEncoder(); diff --git a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs index a5a3e332c7..24d98d22e9 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestEnvironment.cs @@ -38,6 +38,7 @@ public static partial class TestEnvironment internal static string NetCoreVersion => NetCoreVersionLazy.Value; // ReSharper disable once InconsistentNaming + /// /// Gets a value indicating whether test execution runs on CI. /// @@ -75,7 +76,7 @@ private static string GetSolutionDirectoryFullPathImpl() return directory.FullName; } - private static string GetFullPath(string relativePath) => + private static string GetFullPath(string relativePath) => Path.Combine(SolutionDirectoryFullPath, relativePath) .Replace('\\', Path.DirectorySeparatorChar); @@ -83,7 +84,7 @@ private static string GetFullPath(string relativePath) => /// Gets the correct full path to the Input Images directory. /// internal static string InputImagesDirectoryFullPath => GetFullPath(InputImagesRelativePath); - + /// /// Gets the correct full path to the Actual Output directory. (To be written to by the test cases.) /// @@ -100,7 +101,7 @@ internal static string GetReferenceOutputFileName(string actualOutputFileName) = actualOutputFileName.Replace("ActualOutput", @"External\ReferenceOutput").Replace('\\', Path.DirectorySeparatorChar); internal static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - + internal static bool IsMono => Type.GetType("Mono.Runtime") != null; // https://stackoverflow.com/a/721194 internal static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); @@ -142,8 +143,11 @@ private static string GetNetCoreVersion() string[] assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App"); if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2) + { return assemblyPath[netCoreAppIndex + 1]; - return ""; + } + + return string.Empty; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs index f2bb7bdee5..585703a82b 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs @@ -25,7 +25,6 @@ public static class TestImageExtensions /// /// TODO: Consider adding this private processor to the library /// - /// public static void MakeOpaque(this IImageProcessingContext ctx) => ctx.ApplyProcessor(new MakeOpaqueProcessor()); @@ -50,13 +49,14 @@ public static void DebugSave( /// /// Saves the image only when not running in the CI server. /// - /// The image - /// The image provider + /// The image. + /// The image provider. /// Details to be concatenated to the test output file, describing the parameters of the test. - /// The extension + /// The extension. /// A boolean indicating whether to append the pixel type to the output file name. /// A boolean indicating whether to append to the test output file name. /// Custom encoder to use. + /// The input image. public static Image DebugSave( this Image image, ITestImageProvider provider, @@ -165,15 +165,15 @@ public static Image CompareToReferenceOutput( /// Compares the image against the expected Reference output, throws an exception if the images are not similar enough. /// The output file should be named identically to the output produced by . /// - /// The pixel format - /// The image - /// The image provider + /// The pixel format. + /// The image which should be compared to the reference image. + /// The image provider. /// Details to be concatenated to the test output file, describing the parameters of the test. /// The extension /// A boolean indicating whether we should debug save + compare against a grayscale image, smaller in size. /// A boolean indicating whether to append the pixel type to the output file name. /// A boolean indicating whether to append to the test output file name. - /// + /// The image. public static Image CompareToReferenceOutput( this Image image, ITestImageProvider provider, @@ -218,17 +218,17 @@ public static Image CompareToReferenceOutput( /// Compares the image against the expected Reference output, throws an exception if the images are not similar enough. /// The output file should be named identically to the output produced by . /// - /// The pixel format - /// The image - /// The to use - /// The image provider + /// The pixel format. + /// The image which should be compared to the reference output. + /// The to use. + /// The image provider. /// Details to be concatenated to the test output file, describing the parameters of the test. /// The extension /// A boolean indicating whether we should debug save + compare against a grayscale image, smaller in size. /// A boolean indicating whether to append the pixel type to the output file name. /// A boolean indicating whether to append to the test output file name. /// A custom decoder. - /// + /// The image. public static Image CompareToReferenceOutput( this Image image, ImageComparer comparer, @@ -327,12 +327,13 @@ public static Image CompareToReferenceOutputMultiFrame( return image; } - public static Image GetReferenceOutputImage(this ITestImageProvider provider, - object testOutputDetails = null, - string extension = "png", - bool appendPixelTypeToFileName = true, - bool appendSourceFileOrDescription = true, - IImageDecoder decoder = null) + public static Image GetReferenceOutputImage( + this ITestImageProvider provider, + object testOutputDetails = null, + string extension = "png", + bool appendPixelTypeToFileName = true, + bool appendSourceFileOrDescription = true, + IImageDecoder decoder = null) where TPixel : struct, IPixel { string referenceOutputFile = provider.Utility.GetReferenceOutputFileName( @@ -351,11 +352,12 @@ public static Image GetReferenceOutputImage(this ITestImageProvi return Image.Load(referenceOutputFile, decoder); } - public static Image GetReferenceOutputImageMultiFrame(this ITestImageProvider provider, - int frameCount, - object testOutputDetails = null, - string extension = "png", - bool appendPixelTypeToFileName = true) + public static Image GetReferenceOutputImageMultiFrame( + this ITestImageProvider provider, + int frameCount, + object testOutputDetails = null, + string extension = "png", + bool appendPixelTypeToFileName = true) where TPixel : struct, IPixel { string[] frameFiles = provider.Utility.GetReferenceOutputFileNamesMultiFrame( @@ -389,7 +391,7 @@ public static Image GetReferenceOutputImageMultiFrame(this ITest fi.Dispose(); } - // remove the initial empty frame: + // Remove the initial empty frame: result.Frames.RemoveFrame(0); return result; } @@ -441,6 +443,8 @@ public static void CompareBuffers(Span expected, Span actual) /// /// All pixels in all frames should be exactly equal to 'expectedPixel'. /// + /// The pixel type of the image. + /// The image. public static Image ComparePixelBufferTo(this Image image, TPixel expectedPixel) where TPixel : struct, IPixel { @@ -455,6 +459,8 @@ public static Image ComparePixelBufferTo(this Image imag /// /// All pixels in all frames should be exactly equal to 'expectedPixelColor.ToPixel()'. /// + /// The pixel type of the image. + /// The image. public static Image ComparePixelBufferTo(this Image image, Color expectedPixelColor) where TPixel : struct, IPixel { @@ -469,6 +475,8 @@ public static Image ComparePixelBufferTo(this Image imag /// /// All pixels in the frame should be exactly equal to 'expectedPixel'. /// + /// The pixel type of the image. + /// The image. public static ImageFrame ComparePixelBufferTo(this ImageFrame imageFrame, TPixel expectedPixel) where TPixel : struct, IPixel { @@ -558,7 +566,8 @@ internal static void VerifyOperation( appendPixelTypeToFileName: appendPixelTypeToFileName, appendSourceFileOrDescription: appendSourceFileOrDescription); - image.CompareToReferenceOutput(comparer, + image.CompareToReferenceOutput( + comparer, provider, testOutputDetails, appendPixelTypeToFileName: appendPixelTypeToFileName, @@ -689,14 +698,15 @@ private class MakeOpaqueProcessor : ImageProcessor public MakeOpaqueProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) : base(configuration, source, sourceRectangle) { - } protected override void OnFrameApply(ImageFrame source) { Rectangle sourceRectangle = this.SourceRectangle; Configuration configuration = this.Configuration; - ParallelHelper.IterateRowsWithTempBuffer(sourceRectangle, configuration, + ParallelHelper.IterateRowsWithTempBuffer( + sourceRectangle, + configuration, (rows, temp) => { Span tempSpan = temp.Span; @@ -709,6 +719,7 @@ protected override void OnFrameApply(ImageFrame source) ref Vector4 v = ref tempSpan[i]; v.W = 1F; } + PixelOperations.Instance.FromVector4Destructive(configuration, tempSpan, rowSpan, PixelConversionModifiers.Scale); } }); diff --git a/tests/ImageSharp.Tests/TestUtilities/TestMemoryAllocator.cs b/tests/ImageSharp.Tests/TestUtilities/TestMemoryAllocator.cs index e1209a0c6a..edd916cf38 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestMemoryAllocator.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestMemoryAllocator.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using System.Buffers; using System.Collections.Generic; @@ -18,7 +21,7 @@ public TestMemoryAllocator(byte dirtyValue = 42) } /// - /// The value to initialize the result buffer with, with non-clean options () + /// Gets the value to initialize the result buffer with, with non-clean options () /// public byte DirtyValue { get; } @@ -62,7 +65,6 @@ private AllocationRequest(Type elementType, AllocationOptions allocationOptions, if (elementType == typeof(Vector4)) { - } } @@ -74,12 +76,14 @@ public static AllocationRequest Create(AllocationOptions allocationOptions, i } public Type ElementType { get; } + public AllocationOptions AllocationOptions { get; } + public int Length { get; } + public int LengthInBytes { get; } } - /// /// Wraps an array as an instance. /// @@ -152,4 +156,4 @@ public ManagedByteBuffer(byte[] array) } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/TestMemoryManager.cs b/tests/ImageSharp.Tests/TestUtilities/TestMemoryManager.cs index 9274e5727c..3fd5f6e37b 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestMemoryManager.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestMemoryManager.cs @@ -1,9 +1,12 @@ -using System; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; using System.Buffers; namespace SixLabors.ImageSharp.Tests { - class TestMemoryManager : MemoryManager + public class TestMemoryManager : MemoryManager where T : struct { public TestMemoryManager(T[] pixelArray) @@ -43,4 +46,4 @@ protected override void Dispose(bool disposing) this.PixelArray = null; } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/TestPixel.cs b/tests/ImageSharp.Tests/TestUtilities/TestPixel.cs index 1e1a45f074..76627cce10 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestPixel.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestPixel.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. using System; @@ -25,8 +25,11 @@ public TestPixel(float red, float green, float blue, float alpha) } public float Red { get; set; } + public float Green { get; set; } + public float Blue { get; set; } + public float Alpha { get; set; } public static implicit operator TPixel(TestPixel d) @@ -36,14 +39,14 @@ public static implicit operator TPixel(TestPixel d) public TPixel AsPixel() { - TPixel pix = default(TPixel); + var pix = default(TPixel); pix.FromVector4(new System.Numerics.Vector4(this.Red, this.Green, this.Blue, this.Alpha)); return pix; } internal Span AsSpan() { - return new Span(new[] { AsPixel() }); + return new Span(new[] { this.AsPixel() }); } public void Deserialize(IXunitSerializationInfo info) diff --git a/tests/ImageSharp.Tests/TestUtilities/TestUtils.cs b/tests/ImageSharp.Tests/TestUtilities/TestUtils.cs index a6ca008995..a57d7af936 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestUtils.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestUtils.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. using System; @@ -105,8 +105,7 @@ public static bool IsEquivalentTo(this Image a, Image b, /// /// Returns the enumerations for the given type. /// - /// - /// + /// The pixel type. public static PixelTypes GetPixelType(this Type colorStructClrType) => ClrTypes2PixelTypes[colorStructClrType]; public static IEnumerable> ExpandAllTypes(this PixelTypes pixelTypes) @@ -129,6 +128,7 @@ public static IEnumerable> ExpandAllTypes(this Pi result[pt] = pt.GetClrType(); } } + return result; } @@ -161,8 +161,8 @@ internal static TPixel GetPixelOfNamedColor(string colorName) /// The image processing method to test. (As a delegate) /// The value to append to the test output. /// The custom image comparer to use - /// - /// + /// If true, the pixel type will by appended to the output file. + /// A boolean indicating whether to append to the test output file name. internal static void RunValidatingProcessorTest( this TestImageProvider provider, Action process, @@ -216,9 +216,7 @@ internal static void RunValidatingProcessorTest( using (Image image = provider.GetImage()) { FormattableString testOutputDetails = $""; - image.Mutate( - ctx => { testOutputDetails = processAndGetTestOutputDetails(ctx); } - ); + image.Mutate(ctx => { testOutputDetails = processAndGetTestOutputDetails(ctx); }); image.DebugSave( provider, @@ -352,4 +350,4 @@ public static string[] GetAllResamplerNames(bool includeNearestNeighbour = true) .ToArray(); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/TestVector4.cs b/tests/ImageSharp.Tests/TestUtilities/TestVector4.cs index 990258e0c2..8677184e32 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestVector4.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestVector4.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. using System.Numerics; @@ -21,8 +21,11 @@ public TestVector4(float x, float y, float z, float w) } public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float W { get; set; } public static implicit operator Vector4(TestVector4 d) diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/GroupOutputTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/GroupOutputTests.cs index 061d42b0ac..a29f16f577 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/GroupOutputTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/GroupOutputTests.cs @@ -1,4 +1,7 @@ -using System.IO; +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.IO; using SixLabors.ImageSharp.PixelFormats; @@ -26,4 +29,4 @@ public void GetTestOutputDir_ShouldDefineSubfolder(TestImageProvider( TestImageProvider provider, float imageThreshold, @@ -42,7 +45,7 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( } [Theory] - [WithTestPatternImages(110, 110, PixelTypes.Rgba32)] + [WithTestPatternImage(110, 110, PixelTypes.Rgba32)] public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestImageProvider provider) where TPixel : struct, IPixel { @@ -59,7 +62,7 @@ public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestI } [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance(TestImageProvider provider) where TPixel : struct, IPixel { @@ -82,7 +85,7 @@ public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance } [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba64)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba64)] public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvider provider) where TPixel : struct, IPixel { @@ -101,8 +104,8 @@ public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvide } [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 99, 100)] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 100, 99)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 99, 100)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 100, 99)] public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider provider, int w, int h) where TPixel : struct, IPixel { @@ -121,7 +124,6 @@ public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider(TestImageProvider provider) @@ -141,9 +143,8 @@ public void VerifySimilarity_WhenAnImageFrameIsDifferent_Reports(TestIma } } - [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] public void ExactComparer_ApprovesExactEquality(TestImageProvider provider) where TPixel : struct, IPixel { @@ -157,7 +158,7 @@ public void ExactComparer_ApprovesExactEquality(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { @@ -179,4 +180,4 @@ public void ExactComparer_DoesNotTolerateAnyPixelDifference(TestImagePro } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs index 3b4097820a..e9843b2b72 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs @@ -1,9 +1,9 @@ -// Copyright (c) Six Labors and contributors. +// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using Xunit; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.TestUtilities.Tests { using SixLabors.ImageSharp.PixelFormats; @@ -84,4 +84,4 @@ public void MagickDecode_16BitDepthImage_IsApproximatelyEquivalentTo_SystemDrawi } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/ReferenceDecoderBenchmarks.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/ReferenceDecoderBenchmarks.cs index b0d3b8c7e8..90d0835e8d 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/ReferenceDecoderBenchmarks.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/ReferenceDecoderBenchmarks.cs @@ -81,7 +81,8 @@ public void BenchmarkSystemDrawingBmpDecoder(TestImageProvider p private void BenchmarkDecoderImpl(IEnumerable testFiles, IImageDecoder decoder, string info, int times = DefaultExecutionCount) { var measure = new MeasureFixture(this.Output); - measure.Measure(times, + measure.Measure( + times, () => { foreach (string testFile in testFiles) diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs index 4a02d280e5..4ca9cc4bbc 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs @@ -22,7 +22,7 @@ public SystemDrawingReferenceCodecTests(ITestOutputHelper output) } [Theory] - [WithTestPatternImages(20, 20, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void To32bppArgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { @@ -68,7 +68,7 @@ private static string SavePng(TestImageProvider provider, PngCol } [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] public void From32bppArgbSystemDrawingBitmap2(TestImageProvider provider) where TPixel : struct, IPixel { @@ -91,7 +91,7 @@ public void From32bppArgbSystemDrawingBitmap2(TestImageProvider } [Theory] - [WithTestPatternImages(100, 100, PixelTypes.Rgb24)] + [WithTestPatternImage(100, 100, PixelTypes.Rgb24)] public void From24bppRgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { @@ -123,7 +123,7 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv } [Theory] - [WithTestPatternImages(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)] + [WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)] public void SaveWithReferenceEncoder(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs index 07523f6178..160b1fe407 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestEnvironmentTests.cs @@ -4,7 +4,6 @@ using System; using System.IO; -using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Bmp; using SixLabors.ImageSharp.Formats.Gif; @@ -14,8 +13,8 @@ using Xunit; using Xunit.Abstractions; -// ReSharper disable InconsistentNaming +// ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests { public class TestEnvironmentTests @@ -68,7 +67,10 @@ public void GetReferenceOutputFileName() [InlineData("lol/Baz.gif", typeof(GifEncoder))] public void GetReferenceEncoder_ReturnsCorrectEncoders_Windows(string fileName, Type expectedEncoderType) { - if (TestEnvironment.IsLinux) return; + if (TestEnvironment.IsLinux) + { + return; + } IImageEncoder encoder = TestEnvironment.GetReferenceEncoder(fileName); Assert.IsType(expectedEncoderType, encoder); @@ -81,7 +83,10 @@ public void GetReferenceEncoder_ReturnsCorrectEncoders_Windows(string fileName, [InlineData("lol/Baz.gif", typeof(GifDecoder))] public void GetReferenceDecoder_ReturnsCorrectDecoders_Windows(string fileName, Type expectedDecoderType) { - if (TestEnvironment.IsLinux) return; + if (TestEnvironment.IsLinux) + { + return; + } IImageDecoder decoder = TestEnvironment.GetReferenceDecoder(fileName); Assert.IsType(expectedDecoderType, decoder); @@ -94,7 +99,10 @@ public void GetReferenceDecoder_ReturnsCorrectDecoders_Windows(string fileName, [InlineData("lol/Baz.gif", typeof(GifEncoder))] public void GetReferenceEncoder_ReturnsCorrectEncoders_Linux(string fileName, Type expectedEncoderType) { - if (!TestEnvironment.IsLinux) return; + if (!TestEnvironment.IsLinux) + { + return; + } IImageEncoder encoder = TestEnvironment.GetReferenceEncoder(fileName); Assert.IsType(expectedEncoderType, encoder); @@ -107,7 +115,10 @@ public void GetReferenceEncoder_ReturnsCorrectEncoders_Linux(string fileName, Ty [InlineData("lol/Baz.gif", typeof(GifDecoder))] public void GetReferenceDecoder_ReturnsCorrectDecoders_Linux(string fileName, Type expectedDecoderType) { - if (!TestEnvironment.IsLinux) return; + if (!TestEnvironment.IsLinux) + { + return; + } IImageDecoder decoder = TestEnvironment.GetReferenceDecoder(fileName); Assert.IsType(expectedDecoderType, decoder); diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs index 6a1582828a..adb51e723f 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + using System; using Moq; @@ -103,4 +106,4 @@ public void CompareToOriginal_WhenInputIsNotFromFile_Throws(TestImagePro } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs index 416f4034f4..1807738692 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs @@ -14,7 +14,6 @@ using Xunit.Abstractions; // ReSharper disable InconsistentNaming - namespace SixLabors.ImageSharp.Tests { public class TestImageProviderTests @@ -40,9 +39,8 @@ public class TestImageProviderTests /// /// Need to us to create instance of when pixelType is StandardImageClass /// - /// - /// - /// + /// The pixel type of the image. + /// A test image. public static Image CreateTestImage() where TPixel : struct, IPixel => new Image(3, 3); @@ -310,7 +308,7 @@ public void Use_WithSolidFilledImagesAttribute(TestImageProvider } [Theory] - [WithTestPatternImages(49, 20, PixelTypes.Rgba32)] + [WithTestPatternImage(49, 20, PixelTypes.Rgba32)] public void Use_WithTestPatternImages(TestImageProvider provider) where TPixel : struct, IPixel { @@ -321,7 +319,7 @@ public void Use_WithTestPatternImages(TestImageProvider provider } [Theory] - [WithTestPatternImages(20, 20, PixelTypes.Rgba32)] + [WithTestPatternImage(20, 20, PixelTypes.Rgba32)] public void Use_WithTestPatternImages_CustomConfiguration(TestImageProvider provider) where TPixel : struct, IPixel { @@ -348,8 +346,7 @@ private static void EnsureCustomConfigurationIsApplied(TestImageProvider private class TestDecoder : IImageDecoder { // Couldn't make xUnit happy without this hackery: - - private static readonly ConcurrentDictionary invocationCounts = + private static readonly ConcurrentDictionary InvocationCounts = new ConcurrentDictionary(); private static readonly object Monitor = new object(); @@ -367,16 +364,16 @@ public static void DoTestThreadSafe(Action action) public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - invocationCounts[this.callerName]++; + InvocationCounts[this.callerName]++; return new Image(42, 42); } - internal static int GetInvocationCount(string callerName) => invocationCounts[callerName]; + internal static int GetInvocationCount(string callerName) => InvocationCounts[callerName]; internal void InitCaller(string name) { this.callerName = name; - invocationCounts[name] = 0; + InvocationCounts[name] = 0; } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); @@ -384,7 +381,7 @@ internal void InitCaller(string name) private class TestDecoderWithParameters : IImageDecoder { - private static readonly ConcurrentDictionary invocationCounts = + private static readonly ConcurrentDictionary InvocationCounts = new ConcurrentDictionary(); private static readonly object Monitor = new object(); @@ -406,16 +403,16 @@ public static void DoTestThreadSafe(Action action) public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - invocationCounts[this.callerName]++; + InvocationCounts[this.callerName]++; return new Image(42, 42); } - internal static int GetInvocationCount(string callerName) => invocationCounts[callerName]; + internal static int GetInvocationCount(string callerName) => InvocationCounts[callerName]; internal void InitCaller(string name) { this.callerName = name; - invocationCounts[name] = 0; + InvocationCounts[name] = 0; } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestUtilityExtensionsTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestUtilityExtensionsTests.cs index 64b217a028..003e708f41 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestUtilityExtensionsTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestUtilityExtensionsTests.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. using System; @@ -93,7 +93,6 @@ private static void AssertContainsPixelType( IEnumerable> pixelTypesExp) { Assert.Contains(new KeyValuePair(pt, typeof(T)), pixelTypesExp); - } [Fact] diff --git a/tests/ImageSharp.Tests/VectorAssert.cs b/tests/ImageSharp.Tests/VectorAssert.cs index 9612882b3d..a32e168af5 100644 --- a/tests/ImageSharp.Tests/VectorAssert.cs +++ b/tests/ImageSharp.Tests/VectorAssert.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. using System; @@ -48,25 +48,23 @@ public PrecisionEqualityComparer(int precision) public bool Equals(Vector2 x, Vector2 y) { - return Equals(x.X, y.X) && - Equals(x.Y, y.Y); - + return this.Equals(x.X, y.X) && + this.Equals(x.Y, y.Y); } + public bool Equals(Vector3 x, Vector3 y) { - return Equals(x.X, y.X) && - Equals(x.Y, y.Y) && - Equals(x.Z, y.Z); - + return this.Equals(x.X, y.X) && + this.Equals(x.Y, y.Y) && + this.Equals(x.Z, y.Z); } public bool Equals(Vector4 x, Vector4 y) { - return Equals(x.W, y.W) && - Equals(x.X, y.X) && - Equals(x.Y, y.Y) && - Equals(x.Z, y.Z); - + return this.Equals(x.W, y.W) && + this.Equals(x.X, y.X) && + this.Equals(x.Y, y.Y) && + this.Equals(x.Z, y.Z); } public bool Equals(float x, float y) @@ -78,10 +76,12 @@ public int GetHashCode(Vector4 obj) { return obj.GetHashCode(); } + public int GetHashCode(Vector3 obj) { return obj.GetHashCode(); } + public int GetHashCode(Vector2 obj) { return obj.GetHashCode(); From 38454f8fde24ba07dd31eb3e7a6a036d3dbcc5e4 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Wed, 22 Jan 2020 17:19:07 +0100 Subject: [PATCH 02/15] Use using declarations to reduce nesting --- .../Advanced/AdvancedImageExtensionsTests.cs | 137 +++---- .../Common/StreamExtensionsTests.cs | 42 +- .../Drawing/DrawImageTests.cs | 192 +++++---- .../Formats/Bmp/BmpDecoderTests.cs | 346 +++++++---------- .../Formats/Bmp/BmpEncoderTests.cs | 113 +++--- .../Formats/Bmp/BmpMetadataTests.cs | 14 +- .../Formats/GeneralFormatTests.cs | 119 +++--- .../Formats/Gif/GifDecoderTests.cs | 74 ++-- .../Formats/Gif/GifEncoderTests.cs | 162 ++++---- .../Formats/Gif/GifMetadataTests.cs | 88 ++--- .../Formats/ImageFormatManagerTests.cs | 12 +- .../Jpg/Block8x8FTests.CopyToBufferArea.cs | 48 ++- .../Formats/Jpg/GenericBlock8x8Tests.cs | 80 ++-- .../Formats/Jpg/JpegDecoderTests.Baseline.cs | 16 +- .../Formats/Jpg/JpegDecoderTests.Metadata.cs | 88 ++--- .../Jpg/JpegDecoderTests.Progressive.cs | 16 +- .../Formats/Jpg/JpegDecoderTests.cs | 34 +- .../Formats/Jpg/JpegEncoderTests.cs | 107 +++-- .../Jpg/JpegImagePostProcessorTests.cs | 58 ++- .../Formats/Jpg/ParseStreamTests.cs | 60 ++- .../Formats/Jpg/SpectralJpegTests.cs | 20 +- .../Formats/Jpg/Utils/JpegFixture.cs | 10 +- .../Formats/Jpg/Utils/LibJpegTools.cs | 46 ++- .../Formats/Jpg/Utils/VerifyJpeg.cs | 8 +- .../Formats/Png/PngDecoderTests.Chunks.cs | 18 +- .../Formats/Png/PngDecoderTests.cs | 102 ++--- .../Formats/Png/PngEncoderTests.cs | 224 +++++------ .../Formats/Png/PngMetadataTests.cs | 185 ++++----- .../Formats/Png/PngSmokeTests.cs | 44 +-- .../Formats/Tga/TgaDecoderTests.cs | 120 +++--- .../Formats/Tga/TgaEncoderTests.cs | 66 ++-- .../Formats/Tga/TgaTestUtils.cs | 28 +- .../Helpers/ParallelHelperTests.cs | 60 ++- .../Helpers/RowIntervalTests.cs | 18 +- .../IO/DoubleBufferedStreamReaderTests.cs | 190 +++++---- .../ImageSharp.Tests/Image/ImageCloneTests.cs | 116 +++--- .../ImageFrameCollectionTests.Generic.cs | 30 +- .../ImageFrameCollectionTests.NonGeneric.cs | 81 ++-- .../Image/ImageRotationTests.cs | 12 +- .../Image/ImageTests.DetectFormat.cs | 8 +- .../Image/ImageTests.LoadPixelData.cs | 40 +- ..._FileSystemPath_UseDefaultConfiguration.cs | 40 +- ...s.Load_FromBytes_UseGlobalConfiguration.cs | 40 +- ...Load_FromStream_UseDefaultConfiguration.cs | 40 +- .../ImageSharp.Tests/Image/ImageTests.Save.cs | 28 +- .../Image/ImageTests.WrapMemory.cs | 88 ++--- tests/ImageSharp.Tests/Image/ImageTests.cs | 56 ++- .../ImageSharp.Tests/Memory/Buffer2DTests.cs | 106 +++-- .../Memory/BufferAreaTests.cs | 112 +++--- .../Metadata/ImageMetadataTests.cs | 16 +- .../Profiles/Exif/ExifProfileTests.cs | 70 ++-- .../Metadata/Profiles/Exif/ExifValueTests.cs | 6 +- .../PorterDuffCompositorTests.cs | 32 +- ...elOperationsTests.Rgba32OperationsTests.cs | 22 +- .../PixelOperations/PixelOperationsTests.cs | 8 +- .../HistogramEqualizationTests.cs | 114 +++--- .../Binarization/BinaryDitherTests.cs | 60 ++- .../Binarization/BinaryThresholdTest.cs | 22 +- .../Processors/Convolution/BokehBlurTest.cs | 26 +- .../Processors/Convolution/DetectEdgesTest.cs | 40 +- .../Processors/Transforms/AutoOrientTests.cs | 28 +- .../Processors/Transforms/PadTest.cs | 36 +- .../Processors/Transforms/ResizeTests.cs | 365 ++++++++---------- .../Processors/Transforms/RotateFlipTests.cs | 12 +- .../Transforms/AffineTransformTests.cs | 102 +++-- .../Transforms/ProjectiveTransformTests.cs | 68 ++-- .../Transforms/TransformsHelpersTest.cs | 22 +- .../LoadResizeSaveProfilingBenchmarks.cs | 28 +- .../ResizeProfilingBenchmarks.cs | 10 +- .../Quantization/QuantizedImageTests.cs | 40 +- .../Quantization/WuQuantizerTests.cs | 176 ++++----- ...ImageProvider.cs => ITestImageProvider.cs} | 0 .../TestUtilities/ImagingTestCaseUtility.cs | 12 +- .../ReferenceCodecs/MagickReferenceDecoder.cs | 64 ++- .../ReferenceCodecs/SystemDrawingBridge.cs | 60 ++- .../SystemDrawingReferenceDecoder.cs | 48 +-- .../SystemDrawingReferenceEncoder.cs | 8 +- .../TestUtilities/TestImageExtensions.cs | 62 ++- .../TestUtilities/Tests/ImageComparerTests.cs | 104 ++--- .../Tests/MagickReferenceCodecTests.cs | 32 +- .../Tests/SystemDrawingReferenceCodecTests.cs | 78 ++-- .../Tests/TestImageExtensionsTests.cs | 60 ++- .../Tests/TestImageProviderTests.cs | 50 +-- 83 files changed, 2405 insertions(+), 3218 deletions(-) rename tests/ImageSharp.Tests/TestUtilities/ImageProviders/{TestImageProvider.cs => ITestImageProvider.cs} (100%) diff --git a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs index ae2f9a59bd..1dab897f30 100644 --- a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs @@ -20,23 +20,20 @@ public class GetPixelMemory public void WhenMemoryIsOwned(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image0 = provider.GetImage()) - { - var targetBuffer = new TPixel[image0.Width * image0.Height]; - - // Act: - Memory memory = image0.GetPixelMemory(); - - // Assert: - Assert.Equal(image0.Width * image0.Height, memory.Length); - memory.Span.CopyTo(targetBuffer); - - using (Image image1 = provider.GetImage()) - { - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); - } - } + using Image image0 = provider.GetImage(); + var targetBuffer = new TPixel[image0.Width * image0.Height]; + + // Act: + Memory memory = image0.GetPixelMemory(); + + // Assert: + Assert.Equal(image0.Width * image0.Height, memory.Length); + memory.Span.CopyTo(targetBuffer); + + using Image image1 = provider.GetImage(); + + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); } [Theory] @@ -45,27 +42,23 @@ public void WhenMemoryIsOwned(TestImageProvider provider) public void WhenMemoryIsConsumed(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image0 = provider.GetImage()) - { - var targetBuffer = new TPixel[image0.Width * image0.Height]; - image0.GetPixelSpan().CopyTo(targetBuffer); + using Image image0 = provider.GetImage(); + var targetBuffer = new TPixel[image0.Width * image0.Height]; + image0.GetPixelSpan().CopyTo(targetBuffer); - var managerOfExternalMemory = new TestMemoryManager(targetBuffer); + var managerOfExternalMemory = new TestMemoryManager(targetBuffer); - Memory externalMemory = managerOfExternalMemory.Memory; + Memory externalMemory = managerOfExternalMemory.Memory; - using (var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height)) - { - Memory internalMemory = image1.GetPixelMemory(); - Assert.Equal(targetBuffer.Length, internalMemory.Length); - Assert.True(Unsafe.AreSame(ref targetBuffer[0], ref internalMemory.Span[0])); + using var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height); + Memory internalMemory = image1.GetPixelMemory(); + Assert.Equal(targetBuffer.Length, internalMemory.Length); + 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: - image0.ComparePixelBufferTo(externalMemory.Span); - } + // Make sure externalMemory works after destruction: + image0.ComparePixelBufferTo(externalMemory.Span); } } @@ -75,24 +68,21 @@ public void WhenMemoryIsConsumed(TestImageProvider provider) public void GetPixelRowMemory(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var targetBuffer = new TPixel[image.Width * image.Height]; + + // Act: + for (int y = 0; y < image.Height; y++) { - var targetBuffer = new TPixel[image.Width * image.Height]; + Memory rowMemory = image.GetPixelRowMemory(y); + rowMemory.Span.CopyTo(targetBuffer.AsSpan(image.Width * y)); + } - // Act: - for (int y = 0; y < image.Height; y++) - { - Memory rowMemory = image.GetPixelRowMemory(y); - rowMemory.Span.CopyTo(targetBuffer.AsSpan(image.Width * y)); - } + // Assert: + using Image image1 = provider.GetImage(); - // Assert: - using (Image image1 = provider.GetImage()) - { - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); - } - } + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); } [Theory] @@ -101,24 +91,21 @@ public void GetPixelRowMemory(TestImageProvider provider) public void GetPixelRowSpan(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var targetBuffer = new TPixel[image.Width * image.Height]; + + // Act: + for (int y = 0; y < image.Height; y++) { - var targetBuffer = new TPixel[image.Width * image.Height]; + Span rowMemory = image.GetPixelRowSpan(y); + rowMemory.CopyTo(targetBuffer.AsSpan(image.Width * y)); + } - // Act: - for (int y = 0; y < image.Height; y++) - { - Span rowMemory = image.GetPixelRowSpan(y); - rowMemory.CopyTo(targetBuffer.AsSpan(image.Width * y)); - } + // Assert: + using Image image1 = provider.GetImage(); - // Assert: - using (Image image1 = provider.GetImage()) - { - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); - } - } + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); } #pragma warning disable 0618 @@ -128,21 +115,19 @@ public void GetPixelRowSpan(TestImageProvider provider) public unsafe void DangerousGetPinnableReference_CopyToBuffer(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var targetBuffer = new TPixel[image.Width * image.Height]; + + ref byte source = ref Unsafe.As(ref targetBuffer[0]); + ref byte dest = ref Unsafe.As(ref image.DangerousGetPinnableReferenceToPixelBuffer()); + fixed (byte* targetPtr = &source) + fixed (byte* pixelBasePtr = &dest) { - var targetBuffer = new TPixel[image.Width * image.Height]; - - ref byte source = ref Unsafe.As(ref targetBuffer[0]); - ref byte dest = ref Unsafe.As(ref image.DangerousGetPinnableReferenceToPixelBuffer()); - fixed (byte* targetPtr = &source) - fixed (byte* pixelBasePtr = &dest) - { - uint dataSizeInBytes = (uint)(image.Width * image.Height * Unsafe.SizeOf()); - Unsafe.CopyBlock(targetPtr, pixelBasePtr, dataSizeInBytes); - } - - image.ComparePixelBufferTo(targetBuffer); + uint dataSizeInBytes = (uint)(image.Width * image.Height * Unsafe.SizeOf()); + Unsafe.CopyBlock(targetPtr, pixelBasePtr, dataSizeInBytes); } + + image.ComparePixelBufferTo(targetBuffer); } } } diff --git a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs index d47d5da8ef..eb0015c52b 100644 --- a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs @@ -15,51 +15,43 @@ public class StreamExtensionsTests [InlineData(-1)] public void Skip_CountZeroOrLower_PositionNotChanged(int count) { - using (var memStream = new MemoryStream(5)) - { - memStream.Position = 4; - memStream.Skip(count); + using var memStream = new MemoryStream(5); + memStream.Position = 4; + memStream.Skip(count); - Assert.Equal(4, memStream.Position); - } + Assert.Equal(4, memStream.Position); } [Fact] public void Skip_SeekableStream_SeekIsCalled() { - using (var seekableStream = new SeekableStream(4)) - { - seekableStream.Skip(4); + using var seekableStream = new SeekableStream(4); + seekableStream.Skip(4); - Assert.Equal(4, seekableStream.Offset); - Assert.Equal(SeekOrigin.Current, seekableStream.Loc); - } + Assert.Equal(4, seekableStream.Offset); + Assert.Equal(SeekOrigin.Current, seekableStream.Loc); } [Fact] public void Skip_NonSeekableStream_BytesAreRead() { - using (var nonSeekableStream = new NonSeekableStream()) - { - nonSeekableStream.Skip(5); + using var nonSeekableStream = new NonSeekableStream(); + nonSeekableStream.Skip(5); - Assert.Equal(3, nonSeekableStream.Counts.Count); + Assert.Equal(3, nonSeekableStream.Counts.Count); - Assert.Equal(5, nonSeekableStream.Counts[0]); - Assert.Equal(3, nonSeekableStream.Counts[1]); - Assert.Equal(1, nonSeekableStream.Counts[2]); - } + Assert.Equal(5, nonSeekableStream.Counts[0]); + Assert.Equal(3, nonSeekableStream.Counts[1]); + Assert.Equal(1, nonSeekableStream.Counts[2]); } [Fact] public void Skip_EofStream_NoExceptionIsThrown() { - using (var eofStream = new EofStream(7)) - { - eofStream.Skip(7); + using var eofStream = new EofStream(7); + eofStream.Skip(7); - Assert.Equal(0, eofStream.Position); - } + Assert.Equal(0, eofStream.Position); } private class SeekableStream : MemoryStream diff --git a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs index 729ae7b9a4..69eeeaaf93 100644 --- a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs @@ -34,24 +34,22 @@ public class DrawImageTests public void ImageBlendingMatchesSvgSpecExamples(TestImageProvider provider, PixelColorBlendingMode mode) where TPixel : struct, IPixel { - using (Image background = provider.GetImage()) - using (var source = Image.Load(TestFile.Create(TestImages.Png.Ducky).Bytes)) - { - background.Mutate(x => x.DrawImage(source, mode, 1F)); - background.DebugSave( - provider, - new { mode = mode }, - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - - var comparer = ImageComparer.TolerantPercentage(0.01F); - background.CompareToReferenceOutput( - comparer, - provider, - new { mode = mode }, - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - } + using Image background = provider.GetImage(); + using var source = Image.Load(TestFile.Create(TestImages.Png.Ducky).Bytes); + background.Mutate(x => x.DrawImage(source, mode, 1F)); + background.DebugSave( + provider, + new { mode = mode }, + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + + var comparer = ImageComparer.TolerantPercentage(0.01F); + background.CompareToReferenceOutput( + comparer, + provider, + new { mode = mode }, + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); } [Theory] @@ -73,28 +71,26 @@ public void WorksWithDifferentConfigurations( float opacity) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - using (var blend = Image.Load(TestFile.Create(brushImage).Bytes)) + using Image image = provider.GetImage(); + using var blend = Image.Load(TestFile.Create(brushImage).Bytes); + var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4); + var position = new Point(image.Width / 8, image.Height / 8); + blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic)); + image.Mutate(x => x.DrawImage(blend, position, mode, opacity)); + FormattableString testInfo = $"{System.IO.Path.GetFileNameWithoutExtension(brushImage)}-{mode}-{opacity}"; + + var encoder = new PngEncoder(); + + if (provider.PixelType == PixelTypes.Rgba64) { - var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4); - var position = new Point(image.Width / 8, image.Height / 8); - blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic)); - image.Mutate(x => x.DrawImage(blend, position, mode, opacity)); - FormattableString testInfo = $"{System.IO.Path.GetFileNameWithoutExtension(brushImage)}-{mode}-{opacity}"; - - var encoder = new PngEncoder(); - - if (provider.PixelType == PixelTypes.Rgba64) - { - encoder.BitDepth = PngBitDepth.Bit16; - } - - image.DebugSave(provider, testInfo, encoder: encoder); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.01f), - provider, - testInfo); + encoder.BitDepth = PngBitDepth.Bit16; } + + image.DebugSave(provider, testInfo, encoder: encoder); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.01f), + provider, + testInfo); } [Theory] @@ -104,19 +100,17 @@ public void DrawImageOfDifferentPixelType(TestImageProvider prov { byte[] brushData = TestFile.Create(TestImages.Png.Ducky).Bytes; - using (Image image = provider.GetImage()) - using (Image brushImage = provider.PixelType == PixelTypes.Rgba32 - ? (Image)Image.Load(brushData) - : Image.Load(brushData)) - { - image.Mutate(c => c.DrawImage(brushImage, 0.5f)); - - image.DebugSave(provider, appendSourceFileOrDescription: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.01f), - provider, - appendSourceFileOrDescription: false); - } + using Image image = provider.GetImage(); + using Image brushImage = provider.PixelType == PixelTypes.Rgba32 + ? (Image)Image.Load(brushData) + : Image.Load(brushData); + image.Mutate(c => c.DrawImage(brushImage, 0.5f)); + + image.DebugSave(provider, appendSourceFileOrDescription: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.01f), + provider, + appendSourceFileOrDescription: false); } [Theory] @@ -126,25 +120,23 @@ public void DrawImageOfDifferentPixelType(TestImageProvider prov [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, -25, -30)] public void WorksWithDifferentLocations(TestImageProvider provider, int x, int y) { - using (Image background = provider.GetImage()) - using (var overlay = new Image(50, 50)) - { - overlay.GetPixelSpan().Fill(Rgba32.Black); - - background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); - - background.DebugSave( - provider, - testOutputDetails: $"{x}_{y}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - - background.CompareToReferenceOutput( - provider, - testOutputDetails: $"{x}_{y}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - } + using Image background = provider.GetImage(); + using var overlay = new Image(50, 50); + overlay.GetPixelSpan().Fill(Rgba32.Black); + + background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); + + background.DebugSave( + provider, + testOutputDetails: $"{x}_{y}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + + background.CompareToReferenceOutput( + provider, + testOutputDetails: $"{x}_{y}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); } [Theory] @@ -152,29 +144,27 @@ public void WorksWithDifferentLocations(TestImageProvider provider, int public void DrawTransformed(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - using (var blend = Image.Load(TestFile.Create(TestImages.Bmp.Car).Bytes)) - { - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(45F) - .AppendScale(new SizeF(.25F, .25F)) - .AppendTranslation(new PointF(10, 10)); - - // Apply a background color so we can see the translation. - blend.Mutate(x => x.Transform(builder)); - blend.Mutate(x => x.BackgroundColor(Color.HotPink)); - - // Lets center the matrix so we can tell whether any cut-off issues we may have belong to the drawing processor - var position = new Point((image.Width - blend.Width) / 2, (image.Height - blend.Height) / 2); - image.Mutate(x => x.DrawImage(blend, position, .75F)); - - image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.002f), - provider, - appendSourceFileOrDescription: false, - appendPixelTypeToFileName: false); - } + using Image image = provider.GetImage(); + using var blend = Image.Load(TestFile.Create(TestImages.Bmp.Car).Bytes); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(45F) + .AppendScale(new SizeF(.25F, .25F)) + .AppendTranslation(new PointF(10, 10)); + + // Apply a background color so we can see the translation. + blend.Mutate(x => x.Transform(builder)); + blend.Mutate(x => x.BackgroundColor(Color.HotPink)); + + // Lets center the matrix so we can tell whether any cut-off issues we may have belong to the drawing processor + var position = new Point((image.Width - blend.Width) / 2, (image.Height - blend.Height) / 2); + image.Mutate(x => x.DrawImage(blend, position, .75F)); + + image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.002f), + provider, + appendSourceFileOrDescription: false, + appendPixelTypeToFileName: false); } [Theory] @@ -184,17 +174,15 @@ public void DrawTransformed(TestImageProvider provider) [WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, 130)] public void NonOverlappingImageThrows(TestImageProvider provider, int x, int y) { - using (Image background = provider.GetImage()) - using (var overlay = new Image(Configuration.Default, 10, 10, Rgba32.Black)) - { - ImageProcessingException ex = Assert.Throws(Test); + using Image background = provider.GetImage(); + using var overlay = new Image(Configuration.Default, 10, 10, Rgba32.Black); + ImageProcessingException ex = Assert.Throws(Test); - Assert.Contains("does not overlap", ex.ToString()); + Assert.Contains("does not overlap", ex.ToString()); - void Test() - { - background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); - } + void Test() + { + background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs index fb3348be72..9b98eca06e 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs @@ -37,13 +37,11 @@ public class BmpDecoderTests public void BmpDecoder_CanDecode_MiscellaneousBitmaps(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) { - image.DebugSave(provider); - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider); - } + image.CompareToOriginal(provider); } } @@ -52,11 +50,9 @@ public void BmpDecoder_CanDecode_MiscellaneousBitmaps(TestImageProvider< public void BmpDecoder_CanDecodeBitfields(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -65,11 +61,9 @@ public void BmpDecoder_CanDecodeBitfields(TestImageProvider prov public void BmpDecoder_CanDecode_Inverted(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -78,11 +72,9 @@ public void BmpDecoder_CanDecode_Inverted(TestImageProvider prov public void BmpDecoder_CanDecode_1Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); } [Theory] @@ -90,15 +82,13 @@ public void BmpDecoder_CanDecode_1Bit(TestImageProvider provider public void BmpDecoder_CanDecode_4Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider); - } + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); } } @@ -107,11 +97,9 @@ public void BmpDecoder_CanDecode_4Bit(TestImageProvider provider public void BmpDecoder_CanDecode_8Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -119,11 +107,9 @@ public void BmpDecoder_CanDecode_8Bit(TestImageProvider provider public void BmpDecoder_CanDecode_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -131,11 +117,9 @@ public void BmpDecoder_CanDecode_16Bit(TestImageProvider provide public void BmpDecoder_CanDecode_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -143,11 +127,9 @@ public void BmpDecoder_CanDecode_32Bit(TestImageProvider provide public void BmpDecoder_CanDecode_32BitV4Header_Fast(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -157,15 +139,13 @@ public void BmpDecoder_CanDecode_32BitV4Header_Fast(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); + image.DebugSave(provider); - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider); - } + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); } } @@ -174,15 +154,13 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit_WithDelta(TestIma public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); + image.DebugSave(provider); - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider); - } + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); } } @@ -194,13 +172,11 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit(TestImageProvider public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRefDecoder(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) { - image.DebugSave(provider); - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); - } + image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); } } @@ -210,11 +186,9 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRe public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecoder(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette }); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -223,11 +197,9 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecode public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette }); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -237,13 +209,11 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit(TestImageProvider public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); + image.DebugSave(provider); - // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. - // image.CompareToOriginal(provider); - } + // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. + // image.CompareToOriginal(provider); } [Theory] @@ -251,13 +221,11 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvide public void BmpDecoder_CanDecodeAlphaBitfields(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); - // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. - // image.CompareToOriginal(provider); - } + // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. + // image.CompareToOriginal(provider); } [Theory] @@ -265,11 +233,9 @@ public void BmpDecoder_CanDecodeAlphaBitfields(TestImageProvider public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -277,17 +243,15 @@ public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel(TestImageProvide public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - - // Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel - // seems to be wrong. This bitmap has an alpha channel of two bits. In many cases this alpha channel has a value of 3, - // which should be remapped to 255 for RGBA32, but the magick decoder has a value of 191 set. - // The total difference without the alpha channel is still: 0.0204% - // 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()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + + // Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel + // seems to be wrong. This bitmap has an alpha channel of two bits. In many cases this alpha channel has a value of 3, + // which should be remapped to 255 for RGBA32, but the magick decoder has a value of 191 set. + // The total difference without the alpha channel is still: 0.0204% + // 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()); } [Theory] @@ -296,11 +260,9 @@ public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks(TestImageP public void BmpDecoder_CanDecodeBmpv2(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -308,11 +270,9 @@ public void BmpDecoder_CanDecodeBmpv2(TestImageProvider provider public void BmpDecoder_CanDecodeBmpv3(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -320,11 +280,9 @@ public void BmpDecoder_CanDecodeBmpv3(TestImageProvider provider public void BmpDecoder_CanDecodeLessThanFullPalette(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -333,13 +291,11 @@ public void BmpDecoder_CanDecodeLessThanFullPalette(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) { - image.DebugSave(provider); - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider); - } + image.CompareToOriginal(provider); } } @@ -375,11 +331,9 @@ public void BmpDecoder_ThrowsNotSupportedException_OnUnsupportedBitmaps( public void BmpDecoder_CanDecodeAdobeBmpv3(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -387,11 +341,9 @@ public void BmpDecoder_CanDecodeAdobeBmpv3(TestImageProvider pro public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -399,11 +351,9 @@ public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -412,11 +362,9 @@ public void BmpDecoder_CanDecodeBmpv4(TestImageProvider provider public void BmpDecoder_CanDecodeBmpv5(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -424,11 +372,9 @@ public void BmpDecoder_CanDecodeBmpv5(TestImageProvider provider public void BmpDecoder_RespectsFileHeaderOffset(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -436,11 +382,9 @@ public void BmpDecoder_RespectsFileHeaderOffset(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -448,11 +392,9 @@ public void BmpDecoder_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider); - } + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider); } [Theory] @@ -471,12 +413,10 @@ public void BmpDecoder_CanDecode4BytePerEntryPalette(TestImageProvider image = decoder.Decode(Configuration.Default, stream)) - { - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new BmpDecoder(); + using Image image = decoder.Decode(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -523,13 +457,11 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void BmpDecoder_CanDecode_Os2v2XShortHeader(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); - // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. - // image.CompareToOriginal(provider); - } + // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. + // image.CompareToOriginal(provider); } [Theory] @@ -537,15 +469,13 @@ public void BmpDecoder_CanDecode_Os2v2XShortHeader(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); - // TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it, - // but i think incorrectly. I have loaded the image with GIMP and exported as PNG. - // The results are the same as the image sharp implementation. - // image.CompareToOriginal(provider, new MagickReferenceDecoder()); - } + // TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it, + // but i think incorrectly. I have loaded the image with GIMP and exported as PNG. + // The results are the same as the image sharp implementation. + // image.CompareToOriginal(provider, new MagickReferenceDecoder()); } [Theory] @@ -561,13 +491,11 @@ public void BmpDecoder_CanDecode_Os2v2Header(TestImageProvider p public void BmpDecoder_CanDecode_Os2BitmapArray(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new BmpDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new BmpDecoder()); + image.DebugSave(provider); - // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. - // image.CompareToOriginal(provider); - } + // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. + // image.CompareToOriginal(provider); } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs index 6a218abe2b..84009c4b6a 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs @@ -54,22 +54,16 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new BmpEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -79,21 +73,15 @@ public void Encode_PreserveBitsPerPixel(string imagePath, BmpBitsPerPixel bmpBit var options = new BmpEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - BmpMetadata meta = output.Metadata.GetBmpMetadata(); - - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + BmpMetadata meta = output.Metadata.GetBmpMetadata(); + + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); } [Theory] @@ -192,20 +180,16 @@ public void Encode_8BitColor_WithWuQuantizer(TestImageProvider p return; } - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var encoder = new BmpEncoder { - var encoder = new BmpEncoder - { - BitsPerPixel = BmpBitsPerPixel.Pixel8, - Quantizer = new WuQuantizer(256) - }; - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) - { - referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); - } - } + BitsPerPixel = BmpBitsPerPixel.Pixel8, + Quantizer = new WuQuantizer(256) + }; + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); + referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); } [Theory] @@ -218,20 +202,16 @@ public void Encode_8BitColor_WithOctreeQuantizer(TestImageProvider image = provider.GetImage()) + using Image image = provider.GetImage(); + var encoder = new BmpEncoder { - var encoder = new BmpEncoder - { - BitsPerPixel = BmpBitsPerPixel.Pixel8, - Quantizer = new OctreeQuantizer(256) - }; - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) - { - referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); - } - } + BitsPerPixel = BmpBitsPerPixel.Pixel8, + Quantizer = new OctreeQuantizer(256) + }; + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); + referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); } [Theory] @@ -247,19 +227,18 @@ private static void TestBmpEncoderCore( ImageComparer customComparer = null) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + + // 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) { - // 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) - { - image.Mutate(c => c.MakeOpaque()); - } + image.Mutate(c => c.MakeOpaque()); + } - var encoder = new BmpEncoder { BitsPerPixel = bitsPerPixel, SupportTransparency = supportTransparency }; + var encoder = new BmpEncoder { BitsPerPixel = bitsPerPixel, SupportTransparency = supportTransparency }; - // Does DebugSave & load reference CompareToReferenceInput(): - image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer); - } + // Does DebugSave & load reference CompareToReferenceInput(): + image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer); } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs index 9818f9d41f..c0e04a6def 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs @@ -36,14 +36,12 @@ public void CloneIsDeep() public void Identify_DetectsCorrectBitmapInfoHeaderType(string imagePath, BmpInfoHeaderType expectedInfoHeaderType) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - IImageInfo imageInfo = Image.Identify(stream); - Assert.NotNull(imageInfo); - BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata(); - Assert.NotNull(bitmapMetadata); - Assert.Equal(expectedInfoHeaderType, bitmapMetadata.InfoHeaderType); - } + using var stream = new MemoryStream(testFile.Bytes, false); + IImageInfo imageInfo = Image.Identify(stream); + Assert.NotNull(imageInfo); + BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata(); + Assert.NotNull(bitmapMetadata); + Assert.Equal(expectedInfoHeaderType, bitmapMetadata.InfoHeaderType); } } } diff --git a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs index 1e28469101..4a969b3e16 100644 --- a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs +++ b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs @@ -23,12 +23,10 @@ public class GeneralFormatTests : FileTestBase public void ResolutionShouldChange(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Metadata.VerticalResolution = 150; - image.Metadata.HorizontalResolution = 150; - image.DebugSave(provider); - } + using Image image = provider.GetImage(); + image.Metadata.VerticalResolution = 150; + image.Metadata.HorizontalResolution = 150; + image.DebugSave(provider); } [Fact] @@ -38,11 +36,9 @@ public void ImageCanEncodeToString() foreach (TestFile file in Files) { - using (Image image = file.CreateRgba32Image()) - { - string filename = path + "/" + file.FileNameWithoutExtension + ".txt"; - File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance)); - } + using Image image = file.CreateRgba32Image(); + string filename = path + "/" + file.FileNameWithoutExtension + ".txt"; + File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance)); } } @@ -53,10 +49,8 @@ public void DecodeThenEncodeImageFromStreamShouldSucceed() foreach (TestFile file in Files) { - using (Image image = file.CreateRgba32Image()) - { - image.Save($"{path}/{file.FileName}"); - } + using Image image = file.CreateRgba32Image(); + image.Save($"{path}/{file.FileName}"); } } @@ -100,27 +94,25 @@ public void ImageCanConvertFormat() foreach (TestFile file in Files) { - using (Image image = file.CreateRgba32Image()) + using Image image = file.CreateRgba32Image(); + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp")) { - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp")) - { - image.SaveAsBmp(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.jpg")) - { - image.SaveAsJpeg(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.png")) - { - image.SaveAsPng(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.gif")) - { - image.SaveAsGif(output); - } + image.SaveAsBmp(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.jpg")) + { + image.SaveAsJpeg(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.png")) + { + image.SaveAsPng(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.gif")) + { + image.SaveAsGif(output); } } } @@ -132,19 +124,14 @@ public void ImageShouldPreservePixelByteOrderWhenSerialized() foreach (TestFile file in Files) { - byte[] serialized; - using (var image = Image.Load(file.Bytes, out IImageFormat mimeType)) - using (var memoryStream = new MemoryStream()) - { - image.Save(memoryStream, mimeType); - memoryStream.Flush(); - serialized = memoryStream.ToArray(); - } - - using (var image2 = Image.Load(serialized)) - { - image2.Save($"{path}/{file.FileName}"); - } + using var image = Image.Load(file.Bytes, out IImageFormat mimeType); + using var memoryStream = new MemoryStream(); + image.Save(memoryStream, mimeType); + memoryStream.Flush(); + byte[] serialized = memoryStream.ToArray(); + + using var image2 = Image.Load(serialized); + image2.Save($"{path}/{file.FileName}"); } } @@ -170,25 +157,21 @@ public void ImageShouldPreservePixelByteOrderWhenSerialized() [InlineData(10, 100, "tga")] public void CanIdentifyImageLoadedFromBytes(int width, int height, string extension) { - using (var image = Image.LoadPixelData(new Rgba32[width * height], width, height)) - { - using (var memoryStream = new MemoryStream()) - { - IImageFormat format = GetFormat(extension); - image.Save(memoryStream, format); - memoryStream.Position = 0; + using var image = Image.LoadPixelData(new Rgba32[width * height], width, height); + using var memoryStream = new MemoryStream(); + IImageFormat format = GetFormat(extension); + image.Save(memoryStream, format); + memoryStream.Position = 0; - IImageInfo imageInfo = Image.Identify(memoryStream); + IImageInfo imageInfo = Image.Identify(memoryStream); - Assert.Equal(imageInfo.Width, width); - Assert.Equal(imageInfo.Height, height); - memoryStream.Position = 0; + Assert.Equal(imageInfo.Width, width); + Assert.Equal(imageInfo.Height, height); + memoryStream.Position = 0; - imageInfo = Image.Identify(memoryStream, out IImageFormat detectedFormat); + imageInfo = Image.Identify(memoryStream, out IImageFormat detectedFormat); - Assert.Equal(format, detectedFormat); - } - } + Assert.Equal(format, detectedFormat); } [Fact] @@ -196,13 +179,11 @@ public void IdentifyReturnsNullWithInvalidStream() { byte[] invalid = new byte[10]; - using (var memoryStream = new MemoryStream(invalid)) - { - IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format); + using var memoryStream = new MemoryStream(invalid); + IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format); - Assert.Null(imageInfo); - Assert.Null(format); - } + Assert.Null(imageInfo); + Assert.Null(format); } private static IImageFormat GetFormat(string format) diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs index 99dc2d06da..ea6135ab10 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs @@ -54,11 +54,9 @@ public class GifDecoderTests public void Decode_VerifyAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.DebugSaveMultiFrame(provider); - image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(); + image.DebugSaveMultiFrame(provider); + image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact); } [Fact] @@ -70,15 +68,11 @@ public unsafe void Decode_NonTerminatedFinalFrame() fixed (byte* data = testFile.Bytes.AsSpan(0, length)) { - using (var stream = new UnmanagedMemoryStream(data, length)) - { - var decoder = new GifDecoder(); - - using (Image image = decoder.Decode(Configuration.Default, stream)) - { - Assert.Equal((200, 200), (image.Width, image.Height)); - } - } + using var stream = new UnmanagedMemoryStream(data, length); + var decoder = new GifDecoder(); + + using Image image = decoder.Decode(Configuration.Default, stream); + Assert.Equal((200, 200), (image.Width, image.Height)); } } @@ -87,11 +81,9 @@ public unsafe void Decode_NonTerminatedFinalFrame() public void GifDecoder_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.DebugSave(provider); - image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); - } + using Image image = provider.GetImage(); + image.DebugSave(provider); + image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); } [Theory] @@ -104,12 +96,10 @@ public void Decode_VerifyRootFrameAndFrameCount(TestImageProvider image = provider.GetImage()) - { - Assert.Equal(expectedFrameCount, image.Frames.Count); - image.DebugSave(provider); - image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); - } + using Image image = provider.GetImage(); + Assert.Equal(expectedFrameCount, image.Frames.Count); + image.DebugSave(provider); + image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); } [Theory] @@ -117,10 +107,8 @@ public void Decode_VerifyRootFrameAndFrameCount(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First })) - { - Assert.Equal(1, image.Frames.Count); - } + using Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First }); + Assert.Equal(1, image.Frames.Count); } [Theory] @@ -128,10 +116,8 @@ public void CanDecodeJustOneFrame(TestImageProvider provider) public void CanDecodeAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All })) - { - Assert.True(image.Frames.Count > 1); - } + using Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All }); + Assert.True(image.Frames.Count > 1); } [Theory] @@ -142,25 +128,21 @@ public void CanDecodeAllFrames(TestImageProvider provider) public void DetectPixelSize(string imagePath, int expectedPixelSize) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); - } + using var stream = new MemoryStream(testFile.Bytes, false); + Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); } [Fact] public void CanDecodeIntermingledImages() { - using (var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) - using (Image.Load(TestFile.Create(TestImages.Png.Icon).Bytes)) - using (var kumin2 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) + using var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes); + using var load = Image.Load(TestFile.Create(TestImages.Png.Icon).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 first = kumin1.Frames[i]; - ImageFrame second = kumin2.Frames[i]; - first.ComparePixelBufferTo(second.GetPixelSpan()); - } + ImageFrame first = kumin1.Frames[i]; + ImageFrame second = kumin2.Frames[i]; + first.ComparePixelBufferTo(second.GetPixelSpan()); } } } diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs index f9c87e08e5..a4a1506014 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs @@ -30,25 +30,21 @@ public class GifEncoderTests public void EncodeGeneratedPatterns(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var encoder = new GifEncoder { - var encoder = new GifEncoder - { - // Use the palette quantizer without dithering to ensure results - // are consistent - Quantizer = new WebSafePaletteQuantizer(false) - }; - - // Always save as we need to compare the encoded output. - provider.Utility.SaveTestOutputFile(image, "gif", encoder); - } + // Use the palette quantizer without dithering to ensure results + // are consistent + Quantizer = new WebSafePaletteQuantizer(false) + }; + + // Always save as we need to compare the encoded output. + provider.Utility.SaveTestOutputFile(image, "gif", encoder); // Compare encoded result string path = provider.Utility.GetTestOutputFileName("gif", null, true); - using (var encoded = Image.Load(path)) - { - encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif"); - } + using var encoded = Image.Load(path); + encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif"); } [Theory] @@ -58,22 +54,16 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new GifEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Fact] @@ -83,21 +73,15 @@ public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten() var testFile = TestFile.Create(TestImages.Gif.Rings); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - GifMetadata metadata = output.Metadata.GetGifMetadata(); - Assert.Equal(1, metadata.Comments.Count); - Assert.Equal("ImageSharp", metadata.Comments[0]); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + GifMetadata metadata = output.Metadata.GetGifMetadata(); + Assert.Equal(1, metadata.Comments.Count); + Assert.Equal("ImageSharp", metadata.Comments[0]); } [Theory] @@ -105,69 +89,65 @@ public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten() public void EncodeGlobalPaletteReturnsSmallerFile(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var encoder = new GifEncoder { - var encoder = new GifEncoder - { - ColorTableMode = GifColorTableMode.Global, - Quantizer = new OctreeQuantizer(false) - }; + ColorTableMode = GifColorTableMode.Global, + Quantizer = new OctreeQuantizer(false) + }; - // Always save as we need to compare the encoded output. - provider.Utility.SaveTestOutputFile(image, "gif", encoder, "global"); + // Always save as we need to compare the encoded output. + provider.Utility.SaveTestOutputFile(image, "gif", encoder, "global"); - encoder.ColorTableMode = GifColorTableMode.Local; - provider.Utility.SaveTestOutputFile(image, "gif", encoder, "local"); + encoder.ColorTableMode = GifColorTableMode.Local; + provider.Utility.SaveTestOutputFile(image, "gif", encoder, "local"); - var fileInfoGlobal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "global")); - var fileInfoLocal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "local")); + var fileInfoGlobal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "global")); + var fileInfoLocal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "local")); - Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length); - } + Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length); } [Fact] public void NonMutatingEncodePreservesPaletteCount() { - using (var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes)) - using (var outStream = new MemoryStream()) + using var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes); + using var outStream = new MemoryStream(); + inStream.Position = 0; + + var image = Image.Load(inStream); + GifMetadata metaData = image.Metadata.GetGifMetadata(); + GifFrameMetadata frameMetadata = image.Frames.RootFrame.Metadata.GetGifMetadata(); + GifColorTableMode colorMode = metaData.ColorTableMode; + var encoder = new GifEncoder { - inStream.Position = 0; - - var image = Image.Load(inStream); - GifMetadata metaData = image.Metadata.GetGifMetadata(); - GifFrameMetadata frameMetadata = image.Frames.RootFrame.Metadata.GetGifMetadata(); - GifColorTableMode colorMode = metaData.ColorTableMode; - var encoder = new GifEncoder - { - ColorTableMode = colorMode, - Quantizer = new OctreeQuantizer(frameMetadata.ColorTableLength) - }; + ColorTableMode = colorMode, + Quantizer = new OctreeQuantizer(frameMetadata.ColorTableLength) + }; - image.Save(outStream, encoder); - outStream.Position = 0; + image.Save(outStream, encoder); + outStream.Position = 0; - outStream.Position = 0; - var clone = Image.Load(outStream); + outStream.Position = 0; + var clone = Image.Load(outStream); - GifMetadata cloneMetadata = clone.Metadata.GetGifMetadata(); - Assert.Equal(metaData.ColorTableMode, cloneMetadata.ColorTableMode); + GifMetadata cloneMetadata = clone.Metadata.GetGifMetadata(); + Assert.Equal(metaData.ColorTableMode, cloneMetadata.ColorTableMode); - // Gifiddle and Cyotek GifInfo say this image has 64 colors. - Assert.Equal(64, frameMetadata.ColorTableLength); + // Gifiddle and Cyotek GifInfo say this image has 64 colors. + Assert.Equal(64, frameMetadata.ColorTableLength); - for (int i = 0; i < image.Frames.Count; i++) - { - GifFrameMetadata ifm = image.Frames[i].Metadata.GetGifMetadata(); - GifFrameMetadata cifm = clone.Frames[i].Metadata.GetGifMetadata(); - - Assert.Equal(ifm.ColorTableLength, cifm.ColorTableLength); - Assert.Equal(ifm.FrameDelay, cifm.FrameDelay); - } + for (int i = 0; i < image.Frames.Count; i++) + { + GifFrameMetadata ifm = image.Frames[i].Metadata.GetGifMetadata(); + GifFrameMetadata cifm = clone.Frames[i].Metadata.GetGifMetadata(); - image.Dispose(); - clone.Dispose(); + Assert.Equal(ifm.ColorTableLength, cifm.ColorTableLength); + Assert.Equal(ifm.FrameDelay, cifm.FrameDelay); } + + image.Dispose(); + clone.Dispose(); } } } diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs index cb99bc528d..cf8918680a 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs @@ -57,12 +57,10 @@ public void Decode_IgnoreMetadataIsFalse_CommentsAreRead() var testFile = TestFile.Create(TestImages.Gif.Rings); - using (Image image = testFile.CreateRgba32Image(options)) - { - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(1, metadata.Comments.Count); - Assert.Equal("ImageSharp", metadata.Comments[0]); - } + using Image image = testFile.CreateRgba32Image(options); + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(1, metadata.Comments.Count); + Assert.Equal("ImageSharp", metadata.Comments[0]); } [Fact] @@ -75,11 +73,9 @@ public void Decode_IgnoreMetadataIsTrue_CommentsAreIgnored() var testFile = TestFile.Create(TestImages.Gif.Rings); - using (Image image = testFile.CreateRgba32Image(options)) - { - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(0, metadata.Comments.Count); - } + using Image image = testFile.CreateRgba32Image(options); + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(0, metadata.Comments.Count); } [Fact] @@ -88,13 +84,11 @@ public void Decode_CanDecodeLargeTextComment() var options = new GifDecoder(); var testFile = TestFile.Create(TestImages.Gif.LargeComment); - using (Image image = testFile.CreateRgba32Image(options)) - { - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(2, metadata.Comments.Count); - Assert.Equal(new string('c', 349), metadata.Comments[0]); - Assert.Equal("ImageSharp", metadata.Comments[1]); - } + using Image image = testFile.CreateRgba32Image(options); + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(2, metadata.Comments.Count); + Assert.Equal(new string('c', 349), metadata.Comments[0]); + Assert.Equal("ImageSharp", metadata.Comments[1]); } [Fact] @@ -103,20 +97,16 @@ public void Encode_PreservesTextData() var decoder = new GifDecoder(); var testFile = TestFile.Create(TestImages.Gif.LargeComment); - using (Image input = testFile.CreateRgba32Image(decoder)) - using (var memoryStream = new MemoryStream()) - { - input.Save(memoryStream, new GifEncoder()); - memoryStream.Position = 0; - - using (Image image = decoder.Decode(Configuration.Default, memoryStream)) - { - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(2, metadata.Comments.Count); - Assert.Equal(new string('c', 349), metadata.Comments[0]); - Assert.Equal("ImageSharp", metadata.Comments[1]); - } - } + using Image input = testFile.CreateRgba32Image(decoder); + using var memoryStream = new MemoryStream(); + input.Save(memoryStream, new GifEncoder()); + memoryStream.Position = 0; + + using Image image = decoder.Decode(Configuration.Default, memoryStream); + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(2, metadata.Comments.Count); + Assert.Equal(new string('c', 349), metadata.Comments[0]); + Assert.Equal("ImageSharp", metadata.Comments[1]); } [Theory] @@ -124,15 +114,13 @@ public void Encode_PreservesTextData() public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new GifDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new GifDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -140,17 +128,13 @@ public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolut public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new GifDecoder(); - using (Image image = decoder.Decode(Configuration.Default, stream)) - { - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new GifDecoder(); + using Image image = decoder.Decode(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } } } diff --git a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs index d011a63301..54030955ae 100644 --- a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs +++ b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs @@ -128,14 +128,10 @@ public void AddFormatCallsConfig() public void DetectFormatAllocatesCleanBuffer() { byte[] jpegImage; - using (var buffer = new MemoryStream()) - { - using (var image = new Image(100, 100)) - { - image.SaveAsJpeg(buffer); - jpegImage = buffer.ToArray(); - } - } + using var buffer = new MemoryStream(); + using var image = new Image(100, 100); + image.SaveAsJpeg(buffer); + jpegImage = buffer.ToArray(); byte[] invalidImage = { 1, 2, 3 }; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs index 2f0158f4b0..b431ace548 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs @@ -43,19 +43,17 @@ public void Copy1x1Scale() { Block8x8F block = CreateRandomFloatBlock(0, 100); - using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(20, 20, AllocationOptions.Clean)) - { - BufferArea area = buffer.GetArea(5, 10, 8, 8); - block.Copy1x1Scale(area); + using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(20, 20, AllocationOptions.Clean); + BufferArea area = buffer.GetArea(5, 10, 8, 8); + block.Copy1x1Scale(area); - Assert.Equal(block[0, 0], buffer[5, 10]); - Assert.Equal(block[1, 0], buffer[6, 10]); - Assert.Equal(block[0, 1], buffer[5, 11]); - Assert.Equal(block[0, 7], buffer[5, 17]); - Assert.Equal(block[63], buffer[12, 17]); + Assert.Equal(block[0, 0], buffer[5, 10]); + Assert.Equal(block[1, 0], buffer[6, 10]); + Assert.Equal(block[0, 1], buffer[5, 11]); + Assert.Equal(block[0, 7], buffer[5, 17]); + Assert.Equal(block[63], buffer[12, 17]); - VerifyAllZeroOutsideSubArea(buffer, 5, 10); - } + VerifyAllZeroOutsideSubArea(buffer, 5, 10); } [Theory] @@ -71,27 +69,25 @@ public void CopyTo(int horizontalFactor, int verticalFactor) var start = new Point(50, 50); - using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(100, 100, AllocationOptions.Clean)) - { - BufferArea area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor); - block.CopyTo(area, horizontalFactor, verticalFactor); + using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(100, 100, AllocationOptions.Clean); + BufferArea area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor); + block.CopyTo(area, horizontalFactor, verticalFactor); - for (int y = 0; y < 8 * verticalFactor; y++) + for (int y = 0; y < 8 * verticalFactor; y++) + { + for (int x = 0; x < 8 * horizontalFactor; x++) { - for (int x = 0; x < 8 * horizontalFactor; x++) - { - int yy = y / verticalFactor; - int xx = x / horizontalFactor; + int yy = y / verticalFactor; + int xx = x / horizontalFactor; - float expected = block[xx, yy]; - float actual = area[x, y]; + float expected = block[xx, yy]; + float actual = area[x, y]; - Assert.Equal(expected, actual); - } + Assert.Equal(expected, actual); } - - VerifyAllZeroOutsideSubArea(buffer, start.X, start.Y, horizontalFactor, verticalFactor); } + + VerifyAllZeroOutsideSubArea(buffer, start.X, start.Y, horizontalFactor, verticalFactor); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs b/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs index 7c42af5961..4fb7757097 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs @@ -38,23 +38,21 @@ public static Image CreateTestImage() public void LoadAndStretchCorners_FromOrigo(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image s = provider.GetImage()) - { - var d = default(GenericBlock8x8); - d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0); - - TPixel a = s.Frames.RootFrame[0, 0]; - TPixel b = d[0, 0]; - - Assert.Equal(s[0, 0], d[0, 0]); - Assert.Equal(s[1, 0], d[1, 0]); - Assert.Equal(s[7, 0], d[7, 0]); - Assert.Equal(s[0, 1], d[0, 1]); - Assert.Equal(s[1, 1], d[1, 1]); - Assert.Equal(s[7, 0], d[7, 0]); - Assert.Equal(s[0, 7], d[0, 7]); - Assert.Equal(s[7, 7], d[7, 7]); - } + using Image s = provider.GetImage(); + var d = default(GenericBlock8x8); + d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0); + + TPixel a = s.Frames.RootFrame[0, 0]; + TPixel b = d[0, 0]; + + Assert.Equal(s[0, 0], d[0, 0]); + Assert.Equal(s[1, 0], d[1, 0]); + Assert.Equal(s[7, 0], d[7, 0]); + Assert.Equal(s[0, 1], d[0, 1]); + Assert.Equal(s[1, 1], d[1, 1]); + Assert.Equal(s[7, 0], d[7, 0]); + Assert.Equal(s[0, 7], d[0, 7]); + Assert.Equal(s[7, 7], d[7, 7]); } [Theory] @@ -62,38 +60,36 @@ public void LoadAndStretchCorners_FromOrigo(TestImageProvider pr public void LoadAndStretchCorners_WithOffset(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image s = provider.GetImage()) - { - var d = default(GenericBlock8x8); - d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7); + using Image s = provider.GetImage(); + var d = default(GenericBlock8x8); + d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7); - Assert.Equal(s[6, 7], d[0, 0]); - Assert.Equal(s[6, 8], d[0, 1]); - Assert.Equal(s[7, 8], d[1, 1]); + Assert.Equal(s[6, 7], d[0, 0]); + Assert.Equal(s[6, 8], d[0, 1]); + Assert.Equal(s[7, 8], d[1, 1]); - Assert.Equal(s[6, 9], d[0, 2]); - Assert.Equal(s[6, 9], d[0, 3]); - Assert.Equal(s[6, 9], d[0, 7]); + Assert.Equal(s[6, 9], d[0, 2]); + Assert.Equal(s[6, 9], d[0, 3]); + Assert.Equal(s[6, 9], d[0, 7]); - Assert.Equal(s[7, 9], d[1, 2]); - Assert.Equal(s[7, 9], d[1, 3]); - Assert.Equal(s[7, 9], d[1, 7]); + Assert.Equal(s[7, 9], d[1, 2]); + Assert.Equal(s[7, 9], d[1, 3]); + Assert.Equal(s[7, 9], d[1, 7]); - Assert.Equal(s[9, 9], d[3, 2]); - Assert.Equal(s[9, 9], d[3, 3]); - Assert.Equal(s[9, 9], d[3, 7]); + Assert.Equal(s[9, 9], d[3, 2]); + Assert.Equal(s[9, 9], d[3, 3]); + Assert.Equal(s[9, 9], d[3, 7]); - Assert.Equal(s[9, 7], d[3, 0]); - Assert.Equal(s[9, 7], d[4, 0]); - Assert.Equal(s[9, 7], d[7, 0]); + Assert.Equal(s[9, 7], d[3, 0]); + Assert.Equal(s[9, 7], d[4, 0]); + Assert.Equal(s[9, 7], d[7, 0]); - Assert.Equal(s[9, 9], d[3, 2]); - Assert.Equal(s[9, 9], d[4, 2]); - Assert.Equal(s[9, 9], d[7, 2]); + Assert.Equal(s[9, 9], d[3, 2]); + Assert.Equal(s[9, 9], d[4, 2]); + Assert.Equal(s[9, 9], d[7, 2]); - Assert.Equal(s[9, 9], d[4, 3]); - Assert.Equal(s[9, 9], d[7, 7]); - } + Assert.Equal(s[9, 9], d[4, 3]); + Assert.Equal(s[9, 9], d[7, 7]); } [Fact] diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs index adf4629580..31a3f7d3a7 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Baseline.cs @@ -20,16 +20,14 @@ public void DecodeBaselineJpeg(TestImageProvider provider) return; } - using (Image image = provider.GetImage(JpegDecoder)) - { - image.DebugSave(provider); + using Image image = provider.GetImage(JpegDecoder); + image.DebugSave(provider); - provider.Utility.TestName = DecodeBaselineJpegOutputName; - image.CompareToReferenceOutput( - this.GetImageComparer(provider), - provider, - appendPixelTypeToFileName: false); - } + provider.Utility.TestName = DecodeBaselineJpegOutputName; + image.CompareToReferenceOutput( + this.GetImageComparer(provider), + provider, + appendPixelTypeToFileName: false); } [Theory] diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs index c2fc320aff..8bebd73043 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs @@ -79,17 +79,13 @@ public void MetadataIsParsedCorrectly( public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new JpegDecoder(); - using (Image image = decoder.Decode(Configuration.Default, stream)) - { - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new JpegDecoder(); + using Image image = decoder.Decode(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -97,15 +93,13 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new JpegDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new JpegDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -113,13 +107,11 @@ public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolut public void Identify_VerifyQuality(string imagePath, int quality) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new JpegDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - JpegMetadata meta = image.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new JpegDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + JpegMetadata meta = image.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); } [Theory] @@ -127,28 +119,22 @@ public void Identify_VerifyQuality(string imagePath, int quality) public void Decode_VerifyQuality(string imagePath, int quality) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new JpegDecoder(); - using (Image image = decoder.Decode(Configuration.Default, stream)) - { - JpegMetadata meta = image.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); - } - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new JpegDecoder(); + using Image image = decoder.Decode(Configuration.Default, stream); + JpegMetadata meta = image.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); } private static void TestImageInfo(string imagePath, IImageDecoder decoder, bool useIdentify, Action test) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - IImageInfo imageInfo = useIdentify + using var stream = new MemoryStream(testFile.Bytes, false); + IImageInfo imageInfo = useIdentify ? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream) : decoder.Decode(Configuration.Default, stream); - test(imageInfo); - } + test(imageInfo); } private static void TestMetadataImpl( @@ -215,18 +201,16 @@ public void IgnoreMetadata_ControlsWhetherMetadataIsParsed(bool ignoreMetadata) // Snake.jpg has both Exif and ICC profiles defined: var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Snake); - using (Image image = testFile.CreateRgba32Image(decoder)) + using Image image = testFile.CreateRgba32Image(decoder); + if (ignoreMetadata) { - if (ignoreMetadata) - { - Assert.Null(image.Metadata.ExifProfile); - Assert.Null(image.Metadata.IccProfile); - } - else - { - Assert.NotNull(image.Metadata.ExifProfile); - Assert.NotNull(image.Metadata.IccProfile); - } + Assert.Null(image.Metadata.ExifProfile); + Assert.Null(image.Metadata.IccProfile); + } + else + { + Assert.NotNull(image.Metadata.ExifProfile); + Assert.NotNull(image.Metadata.IccProfile); } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs index d3da6e0392..f7ac4eae28 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Progressive.cs @@ -22,16 +22,14 @@ public void DecodeProgressiveJpeg(TestImageProvider provider) return; } - using (Image image = provider.GetImage(JpegDecoder)) - { - image.DebugSave(provider); + using Image image = provider.GetImage(JpegDecoder); + image.DebugSave(provider); - provider.Utility.TestName = DecodeProgressiveJpegOutputName; - image.CompareToReferenceOutput( - this.GetImageComparer(provider), - provider, - appendPixelTypeToFileName: false); - } + provider.Utility.TestName = DecodeProgressiveJpegOutputName; + image.CompareToReferenceOutput( + this.GetImageComparer(provider), + provider, + appendPixelTypeToFileName: false); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs index 2060132296..f72660d42c 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs @@ -69,16 +69,14 @@ public JpegDecoderTests(ITestOutputHelper output) public void ParseStream_BasicPropertiesAreCorrect() { byte[] bytes = TestFile.Create(TestImages.Jpeg.Progressive.Progress).Bytes; - using (var ms = new MemoryStream(bytes)) - { - var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); - decoder.ParseStream(ms); - - // I don't know why these numbers are different. All I know is that the decoder works - // and spectral data is exactly correct also. - // VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31); - VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31); - } + using var ms = new MemoryStream(bytes); + var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); + decoder.ParseStream(ms); + + // I don't know why these numbers are different. All I know is that the decoder works + // and spectral data is exactly correct also. + // VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31); + VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31); } public const string DecodeBaselineJpegOutputName = "DecodeBaselineJpeg"; @@ -128,16 +126,14 @@ public void ValidateProgressivePdfJsOutput( var comparer = ImageComparer.Tolerant(0, 0); - using (Image expectedImage = provider.GetReferenceOutputImage(appendPixelTypeToFileName: false)) - using (var pdfJsOriginalResult = Image.Load(pdfJsOriginalResultPath)) - using (var pdfJsPortResult = Image.Load(sourceBytes, JpegDecoder)) - { - ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult); - ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult); + using Image expectedImage = provider.GetReferenceOutputImage(appendPixelTypeToFileName: false); + using var pdfJsOriginalResult = Image.Load(pdfJsOriginalResultPath); + using var pdfJsPortResult = Image.Load(sourceBytes, JpegDecoder); + ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult); + ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult); - this.Output.WriteLine($"Difference for PDF.js ORIGINAL: {originalReport.DifferencePercentageString}"); - this.Output.WriteLine($"Difference for PORT: {portReport.DifferencePercentageString}"); - } + this.Output.WriteLine($"Difference for PDF.js ORIGINAL: {originalReport.DifferencePercentageString}"); + this.Output.WriteLine($"Difference for PORT: {portReport.DifferencePercentageString}"); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs index 4146050f03..e54414c496 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs @@ -47,20 +47,14 @@ public void Encode_PreserveQuality(string imagePath, int quality) var options = new JpegEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - JpegMetadata meta = output.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + JpegMetadata meta = output.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); } [Theory] @@ -108,22 +102,21 @@ private static void TestJpegEncoderCore( int quality = 100) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + + // There is no alpha in Jpeg! + image.Mutate(c => c.MakeOpaque()); + + var encoder = new JpegEncoder { - // There is no alpha in Jpeg! - image.Mutate(c => c.MakeOpaque()); + Subsample = subsample, + Quality = quality + }; + string info = $"{subsample}-Q{quality}"; + ImageComparer comparer = GetComparer(quality, subsample); - var encoder = new JpegEncoder - { - Subsample = subsample, - Quality = quality - }; - string info = $"{subsample}-Q{quality}"; - ImageComparer comparer = GetComparer(quality, subsample); - - // Does DebugSave & load reference CompareToReferenceInput(): - image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png"); - } + // Does DebugSave & load reference CompareToReferenceInput(): + image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png"); } [Fact] @@ -136,17 +129,15 @@ public void Quality_0_And_1_Are_Identical() var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); - using (Image input = testFile.CreateRgba32Image()) - using (var memStream0 = new MemoryStream()) - using (var memStream1 = new MemoryStream()) - { - input.SaveAsJpeg(memStream0, options); + using Image input = testFile.CreateRgba32Image(); + using var memStream0 = new MemoryStream(); + using var memStream1 = new MemoryStream(); + input.SaveAsJpeg(memStream0, options); - options.Quality = 1; - input.SaveAsJpeg(memStream1, options); + options.Quality = 1; + input.SaveAsJpeg(memStream1, options); - Assert.Equal(memStream0.ToArray(), memStream1.ToArray()); - } + Assert.Equal(memStream0.ToArray(), memStream1.ToArray()); } [Fact] @@ -159,17 +150,15 @@ public void Quality_0_And_100_Are_Not_Identical() var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); - using (Image input = testFile.CreateRgba32Image()) - using (var memStream0 = new MemoryStream()) - using (var memStream1 = new MemoryStream()) - { - input.SaveAsJpeg(memStream0, options); + using Image input = testFile.CreateRgba32Image(); + using var memStream0 = new MemoryStream(); + using var memStream1 = new MemoryStream(); + input.SaveAsJpeg(memStream0, options); - options.Quality = 100; - input.SaveAsJpeg(memStream1, options); + options.Quality = 100; + input.SaveAsJpeg(memStream1, options); - Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray()); - } + Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray()); } [Theory] @@ -179,22 +168,16 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new JpegEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs index 86128e0020..e478621580 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs @@ -34,10 +34,8 @@ public JpegImagePostProcessorTests(ITestOutputHelper output) private static void SaveBuffer(JpegComponentPostProcessor cp, TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f)) - { - image.DebugSave(provider, $"-C{cp.Component.Index}-"); - } + using Image image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f); + image.DebugSave(provider, $"-C{cp.Component.Index}-"); } [Theory] @@ -47,18 +45,16 @@ public void DoProcessorStep(TestImageProvider provider) where TPixel : struct, IPixel { string imageFile = provider.SourceFileOrDescription; - using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) - using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) - using (var imageFrame = new ImageFrame(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight)) - { - pp.DoPostProcessorStep(imageFrame); + using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); + using var pp = new JpegImagePostProcessor(Configuration.Default, decoder); + using var imageFrame = new ImageFrame(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight); + pp.DoPostProcessorStep(imageFrame); - JpegComponentPostProcessor[] cp = pp.ComponentProcessors; + JpegComponentPostProcessor[] cp = pp.ComponentProcessors; - SaveBuffer(cp[0], provider); - SaveBuffer(cp[1], provider); - SaveBuffer(cp[2], provider); - } + SaveBuffer(cp[0], provider); + SaveBuffer(cp[1], provider); + SaveBuffer(cp[2], provider); } [Theory] @@ -67,30 +63,26 @@ public void PostProcess(TestImageProvider provider) where TPixel : struct, IPixel { string imageFile = provider.SourceFileOrDescription; - using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) - using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) - using (var image = new Image(decoder.ImageWidth, decoder.ImageHeight)) - { - pp.PostProcess(image.Frames.RootFrame); + using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); + using var pp = new JpegImagePostProcessor(Configuration.Default, decoder); + using var image = new Image(decoder.ImageWidth, decoder.ImageHeight); + pp.PostProcess(image.Frames.RootFrame); - image.DebugSave(provider); + image.DebugSave(provider); - ImagingTestCaseUtility testUtil = provider.Utility; - testUtil.TestGroupName = nameof(JpegDecoderTests); - testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName; + ImagingTestCaseUtility testUtil = provider.Utility; + testUtil.TestGroupName = nameof(JpegDecoderTests); + testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName; - using (Image referenceImage = - provider.GetReferenceOutputImage(appendPixelTypeToFileName: false)) - { - ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image); + using Image referenceImage = + provider.GetReferenceOutputImage(appendPixelTypeToFileName: false); + ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image); - this.Output.WriteLine($"*** {imageFile} ***"); - this.Output.WriteLine($"Difference: {report.DifferencePercentageString}"); + this.Output.WriteLine($"*** {imageFile} ***"); + this.Output.WriteLine($"Difference: {report.DifferencePercentageString}"); - // ReSharper disable once PossibleInvalidOperationException - Assert.True(report.TotalNormalizedDifference.Value < 0.005f); - } - } + // ReSharper disable once PossibleInvalidOperationException + Assert.True(report.TotalNormalizedDifference.Value < 0.005f); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs index ccc2930e37..8ef36a86b5 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs @@ -32,28 +32,24 @@ public void ColorSpace_IsDeducedCorrectly(string imageFile, object expectedColor { var expectedColorSpace = (JpegColorSpace)expectedColorSpaceValue; - using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) - { - Assert.Equal(expectedColorSpace, decoder.ColorSpace); - } + using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); + Assert.Equal(expectedColorSpace, decoder.ColorSpace); } [Fact] public void ComponentScalingIsCorrect_1ChannelJpeg() { - using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400)) - { - Assert.Equal(1, decoder.ComponentCount); - Assert.Equal(1, decoder.Components.Length); + using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400); + Assert.Equal(1, decoder.ComponentCount); + Assert.Equal(1, decoder.Components.Length); - Size expectedSizeInBlocks = decoder.ImageSizeInPixels.DivideRoundUp(8); + Size expectedSizeInBlocks = decoder.ImageSizeInPixels.DivideRoundUp(8); - Assert.Equal(expectedSizeInBlocks, decoder.ImageSizeInMCU); + Assert.Equal(expectedSizeInBlocks, decoder.ImageSizeInMCU); - var uniform1 = new Size(1, 1); - JpegComponent c0 = decoder.Components[0]; - VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1); - } + var uniform1 = new Size(1, 1); + JpegComponent c0 = decoder.Components[0]; + VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1); } [Theory] @@ -104,32 +100,30 @@ public void ComponentScalingIsCorrect_MultiChannelJpeg( var fLuma = (Size)expectedLumaFactors; var fChroma = (Size)expectedChromaFactors; - using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) - { - Assert.Equal(componentCount, decoder.ComponentCount); - Assert.Equal(componentCount, decoder.Components.Length); + using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); + Assert.Equal(componentCount, decoder.ComponentCount); + Assert.Equal(componentCount, decoder.Components.Length); - JpegComponent c0 = decoder.Components[0]; - JpegComponent c1 = decoder.Components[1]; - JpegComponent c2 = decoder.Components[2]; + JpegComponent c0 = decoder.Components[0]; + JpegComponent c1 = decoder.Components[1]; + JpegComponent c2 = decoder.Components[2]; - var uniform1 = new Size(1, 1); + var uniform1 = new Size(1, 1); - Size expectedLumaSizeInBlocks = decoder.ImageSizeInMCU.MultiplyBy(fLuma); + Size expectedLumaSizeInBlocks = decoder.ImageSizeInMCU.MultiplyBy(fLuma); - Size divisor = fLuma.DivideBy(fChroma); + Size divisor = fLuma.DivideBy(fChroma); - Size expectedChromaSizeInBlocks = expectedLumaSizeInBlocks.DivideRoundUp(divisor); + Size expectedChromaSizeInBlocks = expectedLumaSizeInBlocks.DivideRoundUp(divisor); - VerifyJpeg.VerifyComponent(c0, expectedLumaSizeInBlocks, fLuma, uniform1); - VerifyJpeg.VerifyComponent(c1, expectedChromaSizeInBlocks, fChroma, divisor); - VerifyJpeg.VerifyComponent(c2, expectedChromaSizeInBlocks, fChroma, divisor); + VerifyJpeg.VerifyComponent(c0, expectedLumaSizeInBlocks, fLuma, uniform1); + VerifyJpeg.VerifyComponent(c1, expectedChromaSizeInBlocks, fChroma, divisor); + VerifyJpeg.VerifyComponent(c2, expectedChromaSizeInBlocks, fChroma, divisor); - if (componentCount == 4) - { - JpegComponent c3 = decoder.Components[2]; - VerifyJpeg.VerifyComponent(c3, expectedLumaSizeInBlocks, fLuma, uniform1); - } + if (componentCount == 4) + { + JpegComponent c3 = decoder.Components[2]; + VerifyJpeg.VerifyComponent(c3, expectedLumaSizeInBlocks, fLuma, uniform1); } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs index 8d7dda2fed..d6e69925b2 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs @@ -50,13 +50,11 @@ public void Decoder_ParseStream_SaveSpectralResult(TestImageProvider(TestImageProvider provider byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes; - using (var ms = new MemoryStream(sourceBytes)) - { - decoder.ParseStream(ms); - var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); + using var ms = new MemoryStream(sourceBytes); + decoder.ParseStream(ms); + var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); - this.VerifySpectralCorrectnessImpl(provider, imageSharpData); - } + this.VerifySpectralCorrectnessImpl(provider, imageSharpData); } private void VerifySpectralCorrectnessImpl( diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs index b7cf6a8406..9be449f122 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs @@ -192,12 +192,10 @@ internal void CompareBlocks(Span a, Span b, float tolerance) internal static JpegDecoderCore ParseJpegStream(string testFileName, bool metaDataOnly = false) { byte[] bytes = TestFile.Create(testFileName).Bytes; - using (var ms = new MemoryStream(bytes)) - { - var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); - decoder.ParseStream(ms, metaDataOnly); - return decoder; - } + using var ms = new MemoryStream(bytes); + var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); + decoder.ParseStream(ms, metaDataOnly); + return decoder; } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs index 826335b652..e1d1e7f5d5 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs @@ -98,40 +98,38 @@ public static SpectralData ExtractSpectralData(string inputFile) { RunDumpJpegCoeffsTool(testFile.FullPath, coeffFileFullPath); - using (var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open)) - using (var rdr = new BinaryReader(dumpStream)) + using var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open); + using var rdr = new BinaryReader(dumpStream); + int componentCount = rdr.ReadInt16(); + var result = new ComponentData[componentCount]; + + for (int i = 0; i < componentCount; i++) { - int componentCount = rdr.ReadInt16(); - var result = new ComponentData[componentCount]; + int widthInBlocks = rdr.ReadInt16(); + int heightInBlocks = rdr.ReadInt16(); + var resultComponent = new ComponentData(widthInBlocks, heightInBlocks, i); + result[i] = resultComponent; + } - for (int i = 0; i < componentCount; i++) - { - int widthInBlocks = rdr.ReadInt16(); - int heightInBlocks = rdr.ReadInt16(); - var resultComponent = new ComponentData(widthInBlocks, heightInBlocks, i); - result[i] = resultComponent; - } + var buffer = new byte[64 * sizeof(short)]; - var buffer = new byte[64 * sizeof(short)]; + for (int i = 0; i < result.Length; i++) + { + ComponentData c = result[i]; - for (int i = 0; i < result.Length; i++) + for (int y = 0; y < c.HeightInBlocks; y++) { - ComponentData c = result[i]; - - for (int y = 0; y < c.HeightInBlocks; y++) + for (int x = 0; x < c.WidthInBlocks; x++) { - for (int x = 0; x < c.WidthInBlocks; x++) - { - rdr.Read(buffer, 0, buffer.Length); + rdr.Read(buffer, 0, buffer.Length); - short[] block = MemoryMarshal.Cast(buffer.AsSpan()).ToArray(); - c.MakeBlock(block, y, x); - } + short[] block = MemoryMarshal.Cast(buffer.AsSpan()).ToArray(); + c.MakeBlock(block, y, x); } } - - return new SpectralData(result); } + + return new SpectralData(result); } finally { diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs index 973181ed57..8ac6944c23 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs @@ -59,11 +59,9 @@ internal static void SaveSpectralImage( output?.WriteLine("Min: " + comp.MinVal); output?.WriteLine("Max: " + comp.MaxVal); - using (Image image = comp.CreateGrayScaleImage()) - { - string details = $"C{comp.Index}"; - image.DebugSave(provider, details, appendPixelTypeToFileName: false); - } + using Image image = comp.CreateGrayScaleImage(); + string details = $"C{comp.Index}"; + image.DebugSave(provider, details, appendPixelTypeToFileName: false); } Image fullImage = data.TryCreateRGBSpectralImage(); diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs index ee4001c203..ba93d6a7e0 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs @@ -63,19 +63,17 @@ public void Decode_IncorrectCRCForCriticalChunk_ExceptionIsThrown(uint chunkType { string chunkName = GetChunkTypeName(chunkType); - using (var memStream = new MemoryStream()) - { - WriteHeaderChunk(memStream); - WriteChunk(memStream, chunkName); - WriteDataChunk(memStream); + using var memStream = new MemoryStream(); + WriteHeaderChunk(memStream); + WriteChunk(memStream, chunkName); + WriteDataChunk(memStream); - var decoder = new PngDecoder(); + var decoder = new PngDecoder(); - ImageFormatException exception = - Assert.Throws(() => decoder.Decode(null, memStream)); + ImageFormatException exception = + Assert.Throws(() => decoder.Decode(null, memStream)); - 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) diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs index a88962e5f8..a749b8af9d 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs @@ -87,23 +87,21 @@ public partial class PngDecoderTests public void Decode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); - // We don't have another x-plat reference decoder that can be compared for this image. - if (provider.Utility.SourceFileOrDescription == TestImages.Png.Bad.Issue1047_BadEndChunk) - { - if (TestEnvironment.IsWindows) - { - image.CompareToOriginal(provider, ImageComparer.Exact, (IImageDecoder)SystemDrawingReferenceDecoder.Instance); - } - } - else + // We don't have another x-plat reference decoder that can be compared for this image. + if (provider.Utility.SourceFileOrDescription == TestImages.Png.Bad.Issue1047_BadEndChunk) + { + if (TestEnvironment.IsWindows) { - image.CompareToOriginal(provider, ImageComparer.Exact); + image.CompareToOriginal(provider, ImageComparer.Exact, (IImageDecoder)SystemDrawingReferenceDecoder.Instance); } } + else + { + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -111,11 +109,9 @@ public void Decode(TestImageProvider provider) public void Decode_Interlaced_ImageIsCorrect(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -123,11 +119,9 @@ public void Decode_Interlaced_ImageIsCorrect(TestImageProvider p public void Decode_48Bpp(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -135,11 +129,9 @@ public void Decode_48Bpp(TestImageProvider provider) public void Decode_64Bpp(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -147,11 +139,9 @@ public void Decode_64Bpp(TestImageProvider provider) public void Decoder_L8bitInterlaced(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -159,11 +149,9 @@ public void Decoder_L8bitInterlaced(TestImageProvider provider) public void Decode_L16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -171,11 +159,9 @@ public void Decode_L16Bit(TestImageProvider provider) public void Decode_GrayAlpha16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -183,11 +169,9 @@ public void Decode_GrayAlpha16Bit(TestImageProvider provider) public void Decoder_CanDecodeGrey8bitWithAlpha(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -195,11 +179,9 @@ public void Decoder_CanDecodeGrey8bitWithAlpha(TestImageProvider public void Decoder_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -213,10 +195,8 @@ public void Decoder_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) System.Exception ex = Record.Exception( () => { - using (Image image = provider.GetImage(new PngDecoder())) - { - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); - } + using Image image = provider.GetImage(new PngDecoder()); + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); }); Assert.Null(ex); } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs index 03fdf70bc6..cd884def1c 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs @@ -230,26 +230,24 @@ public void PaletteColorType_WuQuantizer(TestImageProvider provi public void WritesFileMarker(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - using (var ms = new MemoryStream()) + using Image image = provider.GetImage(); + using var ms = new MemoryStream(); + image.Save(ms, new PngEncoder()); + + byte[] data = ms.ToArray().Take(8).ToArray(); + byte[] expected = { - image.Save(ms, new PngEncoder()); - - byte[] data = ms.ToArray().Take(8).ToArray(); - byte[] expected = - { - 0x89, // Set the high bit. - 0x50, // P - 0x4E, // N - 0x47, // G - 0x0D, // Line ending CRLF - 0x0A, // Line ending CRLF - 0x1A, // EOF - 0x0A // LF - }; - - Assert.Equal(expected, data); - } + 0x89, // Set the high bit. + 0x50, // P + 0x4E, // N + 0x47, // G + 0x0D, // Line ending CRLF + 0x0A, // Line ending CRLF + 0x1A, // EOF + 0x0A // LF + }; + + Assert.Equal(expected, data); } [Theory] @@ -259,22 +257,16 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } - } + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + + memStream.Position = 0; + using var output = Image.Load(memStream); + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -284,21 +276,15 @@ public void Encode_PreserveBits(string imagePath, PngBitDepth pngBitDepth) var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - PngMetadata meta = output.Metadata.GetPngMetadata(); + memStream.Position = 0; + using var output = Image.Load(memStream); + PngMetadata meta = output.Metadata.GetPngMetadata(); - Assert.Equal(pngBitDepth, meta.BitDepth); - } - } - } + Assert.Equal(pngBitDepth, meta.BitDepth); } [Theory] @@ -308,51 +294,45 @@ public void Encode_PreserveTrns(string imagePath, PngBitDepth pngBitDepth, PngCo var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) + using Image input = testFile.CreateRgba32Image(); + PngMetadata inMeta = input.Metadata.GetPngMetadata(); + Assert.True(inMeta.HasTransparency); + + using var memStream = new MemoryStream(); + input.Save(memStream, options); + memStream.Position = 0; + using var output = Image.Load(memStream); + PngMetadata outMeta = output.Metadata.GetPngMetadata(); + Assert.True(outMeta.HasTransparency); + + switch (pngColorType) { - PngMetadata inMeta = input.Metadata.GetPngMetadata(); - Assert.True(inMeta.HasTransparency); - - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - memStream.Position = 0; - using (var output = Image.Load(memStream)) + case PngColorType.Grayscale: + if (pngBitDepth.Equals(PngBitDepth.Bit16)) + { + Assert.True(outMeta.TransparentL16.HasValue); + Assert.Equal(inMeta.TransparentL16, outMeta.TransparentL16); + } + else + { + Assert.True(outMeta.TransparentL8.HasValue); + Assert.Equal(inMeta.TransparentL8, outMeta.TransparentL8); + } + + break; + case PngColorType.Rgb: + if (pngBitDepth.Equals(PngBitDepth.Bit16)) + { + Assert.True(outMeta.TransparentRgb48.HasValue); + Assert.Equal(inMeta.TransparentRgb48, outMeta.TransparentRgb48); + } + else { - PngMetadata outMeta = output.Metadata.GetPngMetadata(); - Assert.True(outMeta.HasTransparency); - - switch (pngColorType) - { - case PngColorType.Grayscale: - if (pngBitDepth.Equals(PngBitDepth.Bit16)) - { - Assert.True(outMeta.TransparentL16.HasValue); - Assert.Equal(inMeta.TransparentL16, outMeta.TransparentL16); - } - else - { - Assert.True(outMeta.TransparentL8.HasValue); - Assert.Equal(inMeta.TransparentL8, outMeta.TransparentL8); - } - - break; - case PngColorType.Rgb: - if (pngBitDepth.Equals(PngBitDepth.Bit16)) - { - Assert.True(outMeta.TransparentRgb48.HasValue); - Assert.Equal(inMeta.TransparentRgb48, outMeta.TransparentRgb48); - } - else - { - Assert.True(outMeta.TransparentRgb24.HasValue); - Assert.Equal(inMeta.TransparentRgb24, outMeta.TransparentRgb24); - } - - break; - } + Assert.True(outMeta.TransparentRgb24.HasValue); + Assert.Equal(inMeta.TransparentRgb24, outMeta.TransparentRgb24); } - } + + break; } } @@ -372,41 +352,37 @@ private static void TestPngEncoderCore( bool appendPngBitDepth = false) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var encoder = new PngEncoder { - var encoder = new PngEncoder - { - ColorType = pngColorType, - FilterMethod = pngFilterMethod, - CompressionLevel = compressionLevel, - BitDepth = bitDepth, - Quantizer = new WuQuantizer(paletteSize), - InterlaceMethod = interlaceMode - }; - - string pngColorTypeInfo = appendPngColorType ? pngColorType.ToString() : string.Empty; - string pngFilterMethodInfo = appendPngFilterMethod ? pngFilterMethod.ToString() : string.Empty; - string compressionLevelInfo = appendCompressionLevel ? $"_C{compressionLevel}" : string.Empty; - string paletteSizeInfo = appendPaletteSize ? $"_PaletteSize-{paletteSize}" : string.Empty; - string pngBitDepthInfo = appendPngBitDepth ? bitDepth.ToString() : string.Empty; - string pngInterlaceModeInfo = interlaceMode != PngInterlaceMode.None ? $"_{interlaceMode}" : string.Empty; - - string debugInfo = $"{pngColorTypeInfo}{pngFilterMethodInfo}{compressionLevelInfo}{paletteSizeInfo}{pngBitDepthInfo}{pngInterlaceModeInfo}"; - - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "png", encoder, debugInfo, appendPixelType); - - // Compare to the Magick reference decoder. - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - - // We compare using both our decoder and the reference decoder as pixel transformation - // occurs within the encoder itself leaving the input image unaffected. - // This means we are benefiting from testing our decoder also. - using (var imageSharpImage = Image.Load(actualOutputFile, new PngDecoder())) - using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) - { - ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage); - } - } + ColorType = pngColorType, + FilterMethod = pngFilterMethod, + CompressionLevel = compressionLevel, + BitDepth = bitDepth, + Quantizer = new WuQuantizer(paletteSize), + InterlaceMethod = interlaceMode + }; + + string pngColorTypeInfo = appendPngColorType ? pngColorType.ToString() : string.Empty; + string pngFilterMethodInfo = appendPngFilterMethod ? pngFilterMethod.ToString() : string.Empty; + string compressionLevelInfo = appendCompressionLevel ? $"_C{compressionLevel}" : string.Empty; + string paletteSizeInfo = appendPaletteSize ? $"_PaletteSize-{paletteSize}" : string.Empty; + string pngBitDepthInfo = appendPngBitDepth ? bitDepth.ToString() : string.Empty; + string pngInterlaceModeInfo = interlaceMode != PngInterlaceMode.None ? $"_{interlaceMode}" : string.Empty; + + string debugInfo = $"{pngColorTypeInfo}{pngFilterMethodInfo}{compressionLevelInfo}{paletteSizeInfo}{pngBitDepthInfo}{pngInterlaceModeInfo}"; + + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "png", encoder, debugInfo, appendPixelType); + + // Compare to the Magick reference decoder. + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + + // We compare using both our decoder and the reference decoder as pixel transformation + // occurs within the encoder itself leaving the input image unaffected. + // This means we are benefiting from testing our decoder also. + using var imageSharpImage = Image.Load(actualOutputFile, new PngDecoder()); + using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); + ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage); } } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs index fe25497247..7ebd4c1aab 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs @@ -53,21 +53,19 @@ public void CloneIsDeep() public void Decoder_CanReadTextData(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - 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("Author") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); - 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")); - } + using Image image = provider.GetImage(new PngDecoder()); + 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("Author") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); + 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")); } [Theory] @@ -76,28 +74,24 @@ public void Encoder_PreservesTextData(TestImageProvider provider where TPixel : struct, IPixel { var decoder = new PngDecoder(); - using (Image input = provider.GetImage(decoder)) - using (var memoryStream = new MemoryStream()) - { - input.Save(memoryStream, new PngEncoder()); - - memoryStream.Position = 0; - using (Image image = decoder.Decode(Configuration.Default, memoryStream)) - { - 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("Author") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); - 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")); - } - } + using Image input = provider.GetImage(decoder); + using var memoryStream = new MemoryStream(); + input.Save(memoryStream, new PngEncoder()); + + memoryStream.Position = 0; + using Image image = decoder.Decode(Configuration.Default, memoryStream); + 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("Author") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); + 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")); } [Theory] @@ -105,16 +99,14 @@ public void Encoder_PreservesTextData(TestImageProvider provider public void Decoder_IgnoresInvalidTextData(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new PngDecoder())) - { - 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("trailing space")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("space")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("empty")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large")); - } + using Image image = provider.GetImage(new PngDecoder()); + 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("trailing space")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("space")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("empty")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large")); } [Theory] @@ -123,30 +115,27 @@ public void Encode_UseCompression_WhenTextIsGreaterThenThreshold_Works(T where TPixel : struct, IPixel { var decoder = new PngDecoder(); - using (Image input = provider.GetImage(decoder)) - using (var memoryStream = new MemoryStream()) + using Image input = provider.GetImage(decoder); + using var memoryStream = new MemoryStream(); + + // This will be a zTXt chunk. + var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty); + + // This will be a iTXt chunk. + var expectedTextNoneLatin = new PngTextData("large-text-non-latin", new string('Ф', 100), "language-tag", "translated-keyword"); + PngMetadata inputMetadata = input.Metadata.GetFormatMetadata(PngFormat.Instance); + inputMetadata.TextData.Add(expectedText); + inputMetadata.TextData.Add(expectedTextNoneLatin); + input.Save(memoryStream, new PngEncoder { - // This will be a zTXt chunk. - var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty); - - // This will be a iTXt chunk. - var expectedTextNoneLatin = new PngTextData("large-text-non-latin", new string('Ф', 100), "language-tag", "translated-keyword"); - PngMetadata inputMetadata = input.Metadata.GetFormatMetadata(PngFormat.Instance); - inputMetadata.TextData.Add(expectedText); - inputMetadata.TextData.Add(expectedTextNoneLatin); - input.Save(memoryStream, new PngEncoder - { - TextCompressionThreshold = 50 - }); - - memoryStream.Position = 0; - using (Image image = decoder.Decode(Configuration.Default, memoryStream)) - { - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Contains(meta.TextData, m => m.Equals(expectedText)); - Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin)); - } - } + TextCompressionThreshold = 50 + }); + + memoryStream.Position = 0; + using Image image = decoder.Decode(Configuration.Default, memoryStream); + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + Assert.Contains(meta.TextData, m => m.Equals(expectedText)); + Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin)); } [Fact] @@ -159,15 +148,13 @@ public void Decode_IgnoreMetadataIsFalse_TextChunkIsRead() var testFile = TestFile.Create(TestImages.Png.Blur); - using (Image image = testFile.CreateRgba32Image(options)) - { - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + using Image image = testFile.CreateRgba32Image(options); + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Equal(1, meta.TextData.Count); - Assert.Equal("Software", meta.TextData[0].Keyword); - Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value); - Assert.Equal(0.4545d, meta.Gamma, precision: 4); - } + Assert.Equal(1, meta.TextData.Count); + Assert.Equal("Software", meta.TextData[0].Keyword); + Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value); + Assert.Equal(0.4545d, meta.Gamma, precision: 4); } [Fact] @@ -180,11 +167,9 @@ public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored() var testFile = TestFile.Create(TestImages.Png.Blur); - using (Image image = testFile.CreateRgba32Image(options)) - { - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Equal(0, meta.TextData.Count); - } + using Image image = testFile.CreateRgba32Image(options); + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + Assert.Equal(0, meta.TextData.Count); } [Theory] @@ -192,17 +177,13 @@ public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored() public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new PngDecoder(); - using (Image image = decoder.Decode(Configuration.Default, stream)) - { - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new PngDecoder(); + using Image image = decoder.Decode(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } [Theory] @@ -210,15 +191,13 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using (var stream = new MemoryStream(testFile.Bytes, false)) - { - var decoder = new PngDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); - } + using var stream = new MemoryStream(testFile.Bytes, false); + var decoder = new PngDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); } } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs index 1fe69eee1e..a2842964de 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs @@ -18,19 +18,16 @@ public void GeneralTest(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? - using (Image image = provider.GetImage()) - using (var ms = new MemoryStream()) - { - // image.Save(provider.Utility.GetTestOutputFileName("bmp")); - image.Save(ms, new PngEncoder()); - ms.Position = 0; - using (var img2 = Image.Load(ms, new PngDecoder())) - { - ImageComparer.Tolerant().VerifySimilarity(image, img2); + using Image image = provider.GetImage(); + using var ms = new MemoryStream(); - // img2.Save(provider.Utility.GetTestOutputFileName("bmp", "_loaded"), new BmpEncoder()); - } - } + // image.Save(provider.Utility.GetTestOutputFileName("bmp")); + image.Save(ms, new PngEncoder()); + ms.Position = 0; + using var img2 = Image.Load(ms, new PngDecoder()); + ImageComparer.Tolerant().VerifySimilarity(image, img2); + + // 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 @@ -103,20 +100,17 @@ public void Resize(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? - using (Image image = provider.GetImage()) - using (var ms = new MemoryStream()) - { - // image.Save(provider.Utility.GetTestOutputFileName("png")); - image.Mutate(x => x.Resize(100, 100)); + using Image image = provider.GetImage(); + using var ms = new MemoryStream(); - // image.Save(provider.Utility.GetTestOutputFileName("png", "resize")); - image.Save(ms, new PngEncoder()); - ms.Position = 0; - using (var img2 = Image.Load(ms, new PngDecoder())) - { - ImageComparer.Tolerant().VerifySimilarity(image, img2); - } - } + // image.Save(provider.Utility.GetTestOutputFileName("png")); + image.Mutate(x => x.Resize(100, 100)); + + // image.Save(provider.Utility.GetTestOutputFileName("png", "resize")); + image.Save(ms, new PngEncoder()); + ms.Position = 0; + using var img2 = Image.Load(ms, new PngDecoder()); + ImageComparer.Tolerant().VerifySimilarity(image, img2); } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs index 1f8cbd6a9b..df3ddc216c 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs @@ -18,11 +18,9 @@ public class TgaDecoderTests public void TgaDecoder_CanDecode_Uncompressed_MonoChrome(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -30,11 +28,9 @@ public void TgaDecoder_CanDecode_Uncompressed_MonoChrome(TestImageProvid public void TgaDecoder_CanDecode_Uncompressed_15Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -42,11 +38,9 @@ public void TgaDecoder_CanDecode_Uncompressed_15Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -54,11 +48,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_15Bit(TestImageProvide public void TgaDecoder_CanDecode_Uncompressed_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -66,11 +58,9 @@ public void TgaDecoder_CanDecode_Uncompressed_16Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -78,11 +68,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_WithPalette_16Bit(Test public void TgaDecoder_CanDecode_Uncompressed_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -90,11 +78,9 @@ public void TgaDecoder_CanDecode_Uncompressed_24Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -102,11 +88,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_WithTopLeftOrigin_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -114,11 +98,9 @@ public void TgaDecoder_CanDecode_Palette_WithTopLeftOrigin_24Bit(TestIma public void TgaDecoder_CanDecode_Uncompressed_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -126,11 +108,9 @@ public void TgaDecoder_CanDecode_Uncompressed_32Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -138,11 +118,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_MonoChrome(TestImagePr public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -150,11 +128,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit(TestImageProvide public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -162,11 +138,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvide public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -174,11 +148,9 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit(TestImageProvide public void TgaDecoder_CanDecode_WithPalette_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } [Theory] @@ -186,11 +158,9 @@ public void TgaDecoder_CanDecode_WithPalette_16Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage(new TgaDecoder())) - { - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); - } + using Image image = provider.GetImage(new TgaDecoder()); + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs index 26fe7cbdad..562088620a 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs @@ -37,20 +37,14 @@ public void Encode_PreserveBitsPerPixel(string imagePath, TgaBitsPerPixel bmpBit { var options = new TgaEncoder(); - TestFile testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - memStream.Position = 0; - using (Image output = Image.Load(memStream)) - { - TgaMetadata meta = output.Metadata.GetTgaMetadata(); - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); - } - } - } + var testFile = TestFile.Create(imagePath); + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + memStream.Position = 0; + using var output = Image.Load(memStream); + TgaMetadata meta = output.Metadata.GetTgaMetadata(); + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); } [Theory] @@ -62,20 +56,14 @@ public void Encode_WithCompression_PreserveBitsPerPixel(string imagePath, TgaBit Compression = TgaCompression.RunLength }; - TestFile testFile = TestFile.Create(imagePath); - using (Image input = testFile.CreateRgba32Image()) - { - using (var memStream = new MemoryStream()) - { - input.Save(memStream, options); - memStream.Position = 0; - using (var output = Image.Load(memStream)) - { - TgaMetadata meta = output.Metadata.GetTgaMetadata(); - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); - } - } - } + var testFile = TestFile.Create(imagePath); + using Image input = testFile.CreateRgba32Image(); + using var memStream = new MemoryStream(); + input.Save(memStream, options); + memStream.Position = 0; + using var output = Image.Load(memStream); + TgaMetadata meta = output.Metadata.GetTgaMetadata(); + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); } [Theory] @@ -130,20 +118,14 @@ private static void TestTgaEncoderCore( float compareTolerance = 0.01f) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; - - using (var memStream = new MemoryStream()) - { - image.Save(memStream, encoder); - memStream.Position = 0; - using (var encodedImage = (Image)Image.Load(memStream)) - { - TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance); - } - } - } + using Image image = provider.GetImage(); + var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; + + using var memStream = new MemoryStream(); + image.Save(memStream, encoder); + memStream.Position = 0; + using var encodedImage = (Image)Image.Load(memStream); + TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance); } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs index 090aecb797..500de56066 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs @@ -42,24 +42,22 @@ public static void CompareWithReferenceDecoder( public static Image DecodeWithMagick(Configuration configuration, FileInfo fileInfo) where TPixel : struct, IPixel { - using (var magickImage = new MagickImage(fileInfo)) - { - var result = new Image(configuration, magickImage.Width, magickImage.Height); - Span resultPixels = result.GetPixelSpan(); - - using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) - { - byte[] data = pixels.ToByteArray(PixelMapping.RGBA); + using var magickImage = new MagickImage(fileInfo); + var result = new Image(configuration, magickImage.Width, magickImage.Height); + Span resultPixels = result.GetPixelSpan(); - PixelOperations.Instance.FromRgba32Bytes( - configuration, - data, - resultPixels, - resultPixels.Length); - } + using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) + { + byte[] data = pixels.ToByteArray(PixelMapping.RGBA); - return result; + PixelOperations.Instance.FromRgba32Bytes( + configuration, + data, + resultPixels, + resultPixels.Length); } + + return result; } } } diff --git a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs index 41921144c2..4ac72ac6f9 100644 --- a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs +++ b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs @@ -297,43 +297,41 @@ public void IterateRectangularBuffer( { MemoryAllocator memoryAllocator = Configuration.Default.MemoryAllocator; - using (Buffer2D expected = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean)) - using (Buffer2D actual = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean)) - { - var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight); + using Buffer2D expected = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean); + using Buffer2D actual = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean); + var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight); - void FillRow(int y, Buffer2D buffer) + void FillRow(int y, Buffer2D buffer) + { + for (int x = rect.Left; x < rect.Right; x++) { - for (int x = rect.Left; x < rect.Right; x++) - { - buffer[x, y] = new Point(x, y); - } + buffer[x, y] = new Point(x, y); } + } - // Fill Expected data: - for (int y = rectY; y < rect.Bottom; y++) - { - FillRow(y, expected); - } + // Fill Expected data: + for (int y = rectY; y < rect.Bottom; y++) + { + FillRow(y, expected); + } - // Fill actual data using IterateRows: - var settings = new ParallelExecutionSettings(maxDegreeOfParallelism, memoryAllocator); + // Fill actual data using IterateRows: + var settings = new ParallelExecutionSettings(maxDegreeOfParallelism, memoryAllocator); - ParallelHelper.IterateRows( - rect, - settings, - rows => - { - this.output.WriteLine(rows.ToString()); - for (int y = rows.Min; y < rows.Max; y++) - { - FillRow(y, actual); - } - }); - - // Assert: - TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan()); - } + ParallelHelper.IterateRows( + rect, + settings, + rows => + { + this.output.WriteLine(rows.ToString()); + for (int y = rows.Min; y < rows.Max; y++) + { + FillRow(y, actual); + } + }); + + // Assert: + TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan()); } [Theory] diff --git a/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs b/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs index 0bb3f49d64..ff1010927c 100644 --- a/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs +++ b/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs @@ -19,20 +19,18 @@ public class RowIntervalTests [InlineData(10, 20, 0, 1)] public void GetMultiRowSpan(int width, int height, int min, int max) { - using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(width, height)) - { - var rows = new RowInterval(min, max); + using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(width, height); + var rows = new RowInterval(min, max); - Span span = buffer.GetMultiRowSpan(rows); + Span span = buffer.GetMultiRowSpan(rows); - ref int expected0 = ref buffer.GetSpan()[min * width]; - int expectedLength = (max - min) * width; + ref int expected0 = ref buffer.GetSpan()[min * width]; + int expectedLength = (max - min) * width; - ref int actual0 = ref span[0]; + ref int actual0 = ref span[0]; - Assert.Equal(span.Length, expectedLength); - Assert.True(Unsafe.AreSame(ref expected0, ref actual0)); - } + Assert.Equal(span.Length, expectedLength); + Assert.True(Unsafe.AreSame(ref expected0, ref actual0)); } [Fact] diff --git a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs index 9703aea9b6..ff42ad59b4 100644 --- a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs +++ b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs @@ -16,64 +16,58 @@ public class DoubleBufferedStreamReaderTests [Fact] public void DoubleBufferedStreamReaderCanReadSingleByteFromOrigin() { - using (MemoryStream stream = this.CreateTestStream()) - { - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + using MemoryStream stream = this.CreateTestStream(); + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - Assert.Equal(expected[0], reader.ReadByte()); + Assert.Equal(expected[0], reader.ReadByte()); - // We've read a whole chunk but increment by 1 in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - Assert.Equal(1, reader.Position); - } + // We've read a whole chunk but increment by 1 in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + Assert.Equal(1, reader.Position); } [Fact] public void DoubleBufferedStreamReaderCanReadSingleByteFromOffset() { - using (MemoryStream stream = this.CreateTestStream()) - { - byte[] expected = stream.ToArray(); - const int offset = 5; - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - reader.Position = offset; + using MemoryStream stream = this.CreateTestStream(); + byte[] expected = stream.ToArray(); + const int offset = 5; + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + reader.Position = offset; - Assert.Equal(expected[offset], reader.ReadByte()); + Assert.Equal(expected[offset], reader.ReadByte()); - // We've read a whole chunk but increment by 1 in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset); - Assert.Equal(offset + 1, reader.Position); - } + // We've read a whole chunk but increment by 1 in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset); + Assert.Equal(offset + 1, reader.Position); } [Fact] public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly() { - using (MemoryStream stream = this.CreateTestStream()) + using MemoryStream stream = this.CreateTestStream(); + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + + for (int i = 0; i < expected.Length; i++) { - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + Assert.Equal(expected[i], reader.ReadByte()); + Assert.Equal(i + 1, reader.Position); - for (int i = 0; i < expected.Length; i++) + if (i < DoubleBufferedStreamReader.ChunkLength) { - Assert.Equal(expected[i], reader.ReadByte()); - Assert.Equal(i + 1, reader.Position); - - if (i < DoubleBufferedStreamReader.ChunkLength) - { - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - } - else if (i >= DoubleBufferedStreamReader.ChunkLength && i < DoubleBufferedStreamReader.ChunkLength * 2) - { - // We should have advanced to the second chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); - } - else - { - // We should have advanced to the third chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); - } + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + } + else if (i >= DoubleBufferedStreamReader.ChunkLength && i < DoubleBufferedStreamReader.ChunkLength * 2) + { + // We should have advanced to the second chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); + } + else + { + // We should have advanced to the third chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); } } } @@ -81,53 +75,49 @@ public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly() [Fact] public void DoubleBufferedStreamReaderCanReadMultipleBytesFromOrigin() { - using (MemoryStream stream = this.CreateTestStream()) - { - var buffer = new byte[2]; - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - - Assert.Equal(2, reader.Read(buffer, 0, 2)); - Assert.Equal(expected[0], buffer[0]); - Assert.Equal(expected[1], buffer[1]); - - // We've read a whole chunk but increment by the buffer length in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - Assert.Equal(buffer.Length, reader.Position); - } + using MemoryStream stream = this.CreateTestStream(); + var buffer = new byte[2]; + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + + Assert.Equal(2, reader.Read(buffer, 0, 2)); + Assert.Equal(expected[0], buffer[0]); + Assert.Equal(expected[1], buffer[1]); + + // We've read a whole chunk but increment by the buffer length in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + Assert.Equal(buffer.Length, reader.Position); } [Fact] public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() { - using (MemoryStream stream = this.CreateTestStream()) + using MemoryStream stream = this.CreateTestStream(); + var buffer = new byte[2]; + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + + for (int i = 0, o = 0; i < expected.Length / 2; i++, o += 2) { - var buffer = new byte[2]; - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + Assert.Equal(2, reader.Read(buffer, 0, 2)); + Assert.Equal(expected[o], buffer[0]); + Assert.Equal(expected[o + 1], buffer[1]); + Assert.Equal(o + 2, reader.Position); - for (int i = 0, o = 0; i < expected.Length / 2; i++, o += 2) + int offset = i * 2; + if (offset < DoubleBufferedStreamReader.ChunkLength) { - Assert.Equal(2, reader.Read(buffer, 0, 2)); - Assert.Equal(expected[o], buffer[0]); - Assert.Equal(expected[o + 1], buffer[1]); - Assert.Equal(o + 2, reader.Position); - - int offset = i * 2; - if (offset < DoubleBufferedStreamReader.ChunkLength) - { - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - } - else if (offset >= DoubleBufferedStreamReader.ChunkLength && offset < DoubleBufferedStreamReader.ChunkLength * 2) - { - // We should have advanced to the second chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); - } - else - { - // We should have advanced to the third chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); - } + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + } + else if (offset >= DoubleBufferedStreamReader.ChunkLength && offset < DoubleBufferedStreamReader.ChunkLength * 2) + { + // We should have advanced to the second chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); + } + else + { + // We should have advanced to the third chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); } } } @@ -135,33 +125,31 @@ public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() [Fact] public void DoubleBufferedStreamReaderCanSkip() { - using (MemoryStream stream = this.CreateTestStream()) - { - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + using MemoryStream stream = this.CreateTestStream(); + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - int skip = 50; - int plusOne = 1; - int skip2 = DoubleBufferedStreamReader.ChunkLength; + int skip = 50; + int plusOne = 1; + int skip2 = DoubleBufferedStreamReader.ChunkLength; - // Skip - reader.Skip(skip); - Assert.Equal(skip, reader.Position); - Assert.Equal(stream.Position, reader.Position); + // Skip + reader.Skip(skip); + Assert.Equal(skip, reader.Position); + Assert.Equal(stream.Position, reader.Position); - // Read - Assert.Equal(expected[skip], reader.ReadByte()); + // Read + Assert.Equal(expected[skip], reader.ReadByte()); - // Skip Again - reader.Skip(skip2); + // Skip Again + reader.Skip(skip2); - // First Skip + First Read + Second Skip - int position = skip + plusOne + skip2; + // First Skip + First Read + Second Skip + int position = skip + plusOne + skip2; - Assert.Equal(position, reader.Position); - Assert.Equal(stream.Position, reader.Position); - Assert.Equal(expected[position], reader.ReadByte()); - } + Assert.Equal(position, reader.Position); + Assert.Equal(stream.Position, reader.Position); + Assert.Equal(expected[position], reader.ReadByte()); } private MemoryStream CreateTestStream() diff --git a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs index 343b1ae77e..ccaee3d108 100644 --- a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs @@ -32,24 +32,22 @@ public void Clone_WhenDisposed_Throws() [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgra32(TestImageProvider provider) { - using (Image image = provider.GetImage()) - using (Image clone = image.CloneAs()) + using Image image = provider.GetImage(); + using Image clone = image.CloneAs(); + for (int y = 0; y < image.Height; y++) { - for (int y = 0; y < image.Height; y++) + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) - { - Rgba32 expected = row[x]; - Bgra32 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - Assert.Equal(expected.A, actual.A); - } + Rgba32 expected = row[x]; + Bgra32 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + Assert.Equal(expected.A, actual.A); } } } @@ -58,23 +56,21 @@ public void CloneAs_ToBgra32(TestImageProvider provider) [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgr24(TestImageProvider provider) { - using (Image image = provider.GetImage()) - using (Image clone = image.CloneAs()) + using Image image = provider.GetImage(); + using Image clone = image.CloneAs(); + for (int y = 0; y < image.Height; y++) { - for (int y = 0; y < image.Height; y++) + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) - { - Rgba32 expected = row[x]; - Bgr24 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - } + Rgba32 expected = row[x]; + Bgr24 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); } } } @@ -83,24 +79,22 @@ public void CloneAs_ToBgr24(TestImageProvider provider) [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToArgb32(TestImageProvider provider) { - using (Image image = provider.GetImage()) - using (Image clone = image.CloneAs()) + using Image image = provider.GetImage(); + using Image clone = image.CloneAs(); + for (int y = 0; y < image.Height; y++) { - for (int y = 0; y < image.Height; y++) + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) - { - Rgba32 expected = row[x]; - Argb32 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - Assert.Equal(expected.A, actual.A); - } + Rgba32 expected = row[x]; + Argb32 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + Assert.Equal(expected.A, actual.A); } } } @@ -109,23 +103,21 @@ public void CloneAs_ToArgb32(TestImageProvider provider) [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToRgb24(TestImageProvider provider) { - using (Image image = provider.GetImage()) - using (Image clone = image.CloneAs()) + using Image image = provider.GetImage(); + using Image clone = image.CloneAs(); + for (int y = 0; y < image.Height; y++) { - for (int y = 0; y < image.Height; y++) + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) - { - Rgba32 expected = row[x]; - Rgb24 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - } + Rgba32 expected = row[x]; + Rgb24 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); } } } diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs index 6997300d59..644fa40649 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs @@ -192,15 +192,11 @@ public void Dispose_DisposesAllInnerFrames() public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image img = provider.GetImage()) - { - img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway - using (Image cloned = img.Frames.CloneFrame(0)) - { - Assert.Equal(2, img.Frames.Count); - cloned.ComparePixelBufferTo(img.GetPixelSpan()); - } - } + using Image img = provider.GetImage(); + img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway + using Image cloned = img.Frames.CloneFrame(0); + Assert.Equal(2, img.Frames.Count); + cloned.ComparePixelBufferTo(img.GetPixelSpan()); } [Theory] @@ -208,17 +204,13 @@ public void CloneFrame(TestImageProvider provider) public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image img = provider.GetImage()) - { - var sourcePixelData = img.GetPixelSpan().ToArray(); + using Image img = provider.GetImage(); + var sourcePixelData = img.GetPixelSpan().ToArray(); - img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); - using (Image cloned = img.Frames.ExportFrame(0)) - { - Assert.Equal(1, img.Frames.Count); - cloned.ComparePixelBufferTo(sourcePixelData); - } - } + img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); + using Image cloned = img.Frames.ExportFrame(0); + Assert.Equal(1, img.Frames.Count); + cloned.ComparePixelBufferTo(sourcePixelData); } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs index 10d9a44890..754804cf2a 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs @@ -148,20 +148,16 @@ public void RootFrameIsFrameAtIndexZero() public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image img = provider.GetImage()) - { - ImageFrameCollection nonGenericFrameCollection = img.Frames; + using Image img = provider.GetImage(); + ImageFrameCollection nonGenericFrameCollection = img.Frames; - nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway - using (Image cloned = nonGenericFrameCollection.CloneFrame(0)) - { - Assert.Equal(2, img.Frames.Count); + nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway + using Image cloned = nonGenericFrameCollection.CloneFrame(0); + Assert.Equal(2, img.Frames.Count); - var expectedClone = (Image)cloned; + var expectedClone = (Image)cloned; - expectedClone.ComparePixelBufferTo(img.GetPixelSpan()); - } - } + expectedClone.ComparePixelBufferTo(img.GetPixelSpan()); } [Theory] @@ -169,21 +165,17 @@ public void CloneFrame(TestImageProvider provider) public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image img = provider.GetImage()) - { - var sourcePixelData = img.GetPixelSpan().ToArray(); + using Image img = provider.GetImage(); + var sourcePixelData = img.GetPixelSpan().ToArray(); - ImageFrameCollection nonGenericFrameCollection = img.Frames; + ImageFrameCollection nonGenericFrameCollection = img.Frames; - nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); - using (Image cloned = nonGenericFrameCollection.ExportFrame(0)) - { - Assert.Equal(1, img.Frames.Count); + nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); + using Image cloned = nonGenericFrameCollection.ExportFrame(0); + Assert.Equal(1, img.Frames.Count); - var expectedClone = (Image)cloned; - expectedClone.ComparePixelBufferTo(sourcePixelData); - } - } + var expectedClone = (Image)cloned; + expectedClone.ComparePixelBufferTo(sourcePixelData); } [Fact] @@ -270,39 +262,34 @@ public void Contains_FalseIfNonMember() public void ConstructGif_FromDifferentPixelTypes(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image source = provider.GetImage()) - using (var dest = new Image(source.GetConfiguration(), source.Width, source.Height)) - { - // Giphy.gif has 5 frames - ImportFrameAs(source.Frames, dest.Frames, 0); - ImportFrameAs(source.Frames, dest.Frames, 1); - ImportFrameAs(source.Frames, dest.Frames, 2); - ImportFrameAs(source.Frames, dest.Frames, 3); - ImportFrameAs(source.Frames, dest.Frames, 4); + using Image source = provider.GetImage(); + using var dest = new Image(source.GetConfiguration(), source.Width, source.Height); - // Drop the original empty root frame: - dest.Frames.RemoveFrame(0); + // Giphy.gif has 5 frames + ImportFrameAs(source.Frames, dest.Frames, 0); + ImportFrameAs(source.Frames, dest.Frames, 1); + ImportFrameAs(source.Frames, dest.Frames, 2); + ImportFrameAs(source.Frames, dest.Frames, 3); + ImportFrameAs(source.Frames, dest.Frames, 4); - dest.DebugSave(provider, appendSourceFileOrDescription: false, extension: "gif"); - dest.CompareToOriginal(provider); + // Drop the original empty root frame: + dest.Frames.RemoveFrame(0); - for (int i = 0; i < 5; i++) - { - CompareGifMetadata(source.Frames[i], dest.Frames[i]); - } + dest.DebugSave(provider, appendSourceFileOrDescription: false, extension: "gif"); + dest.CompareToOriginal(provider); + + for (int i = 0; i < 5; i++) + { + CompareGifMetadata(source.Frames[i], dest.Frames[i]); } } private static void ImportFrameAs(ImageFrameCollection source, ImageFrameCollection destination, int index) where TPixel : struct, IPixel { - using (Image temp = source.CloneFrame(index)) - { - using (Image temp2 = temp.CloneAs()) - { - destination.AddFrame(temp2.Frames.RootFrame); - } - } + using Image temp = source.CloneFrame(index); + using Image temp2 = temp.CloneAs(); + destination.AddFrame(temp2.Frames.RootFrame); } private static void CompareGifMetadata(ImageFrame a, ImageFrame b) diff --git a/tests/ImageSharp.Tests/Image/ImageRotationTests.cs b/tests/ImageSharp.Tests/Image/ImageRotationTests.cs index e1c4a419e1..2884a0047c 100644 --- a/tests/ImageSharp.Tests/Image/ImageRotationTests.cs +++ b/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. using SixLabors.ImageSharp.PixelFormats; @@ -48,12 +48,10 @@ public void RotateImageBy360Degrees() private static (Size original, Size rotated) Rotate(int angle) { var file = TestFile.Create(TestImages.Bmp.Car); - using (var image = Image.Load(file.FullPath)) - { - Size original = image.Size(); - image.Mutate(x => x.Rotate(angle)); - return (original, image.Size()); - } + using var image = Image.Load(file.FullPath); + Size original = image.Size(); + image.Mutate(x => x.Rotate(angle)); + return (original, image.Size()); } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs index dcf4dcfe84..c639f37cd2 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs @@ -71,11 +71,9 @@ public void FromFileSystemPath_CustomConfiguration() [Fact] public void FromStream_GlobalConfiguration() { - using (var stream = new MemoryStream(this.ActualImageBytes)) - { - IImageFormat type = Image.DetectFormat(stream); - Assert.Equal(ExpectedGlobalFormat, type); - } + using var stream = new MemoryStream(this.ActualImageBytes); + IImageFormat type = Image.DetectFormat(stream); + Assert.Equal(ExpectedGlobalFormat, type); } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs b/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs index 7a5fa87290..7d75bd0b02 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs +++ b/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. using System; @@ -18,17 +18,15 @@ public void FromPixels(bool useSpan) { Rgba32[] data = { Rgba32.Black, Rgba32.White, Rgba32.White, Rgba32.Black, }; - using (Image img = useSpan - ? Image.LoadPixelData(data.AsSpan(), 2, 2) - : Image.LoadPixelData(data, 2, 2)) - { - Assert.NotNull(img); - Assert.Equal(Rgba32.Black, img[0, 0]); - Assert.Equal(Rgba32.White, img[0, 1]); + using Image img = useSpan + ? Image.LoadPixelData(data.AsSpan(), 2, 2) + : Image.LoadPixelData(data, 2, 2); + Assert.NotNull(img); + Assert.Equal(Rgba32.Black, img[0, 0]); + Assert.Equal(Rgba32.White, img[0, 1]); - Assert.Equal(Rgba32.White, img[1, 0]); - Assert.Equal(Rgba32.Black, img[1, 1]); - } + Assert.Equal(Rgba32.White, img[1, 0]); + Assert.Equal(Rgba32.Black, img[1, 1]); } [Theory] @@ -43,18 +41,16 @@ public void FromBytes(bool useSpan) 255, 255, 255, 255, // 1,0 0, 0, 0, 255, // 1,1 }; - using (Image img = useSpan - ? Image.LoadPixelData(data.AsSpan(), 2, 2) - : Image.LoadPixelData(data, 2, 2)) - { - Assert.NotNull(img); - Assert.Equal(Rgba32.Black, img[0, 0]); - Assert.Equal(Rgba32.White, img[0, 1]); + using Image img = useSpan + ? Image.LoadPixelData(data.AsSpan(), 2, 2) + : Image.LoadPixelData(data, 2, 2); + Assert.NotNull(img); + Assert.Equal(Rgba32.Black, img[0, 0]); + Assert.Equal(Rgba32.White, img[0, 1]); - Assert.Equal(Rgba32.White, img[1, 0]); - Assert.Equal(Rgba32.Black, img[1, 1]); - } + Assert.Equal(Rgba32.White, img[1, 0]); + Assert.Equal(Rgba32.Black, img[1, 1]); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs index 58a67f9df6..7c0018959c 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs @@ -26,57 +26,45 @@ private static void VerifyDecodedImage(Image img) [Fact] public void Path_Specific() { - using (var img = Image.Load(this.Path)) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Path); + VerifyDecodedImage(img); } [Fact] public void Path_Agnostic() { - using (var img = Image.Load(this.Path)) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Path); + VerifyDecodedImage(img); } [Fact] public void Path_Decoder_Specific() { - using (var img = Image.Load(this.Path, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Path, new BmpDecoder()); + VerifyDecodedImage(img); } [Fact] public void Path_Decoder_Agnostic() { - using (var img = Image.Load(this.Path, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Path, new BmpDecoder()); + VerifyDecodedImage(img); } [Fact] public void Path_OutFormat_Specific() { - using (var img = Image.Load(this.Path, out IImageFormat format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = Image.Load(this.Path, out IImageFormat format); + VerifyDecodedImage(img); + Assert.IsType(format); } [Fact] public void Path_OutFormat_Agnostic() { - using (var img = Image.Load(this.Path, out IImageFormat format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = Image.Load(this.Path, out IImageFormat format); + VerifyDecodedImage(img); + Assert.IsType(format); } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs index f65dccc7e9..9c5ac4f84d 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs @@ -30,10 +30,8 @@ private static void VerifyDecodedImage(Image img) [InlineData(true)] public void Bytes_Specific(bool useSpan) { - using (var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray)) - { - VerifyDecodedImage(img); - } + using var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray); + VerifyDecodedImage(img); } [Theory] @@ -41,10 +39,8 @@ public void Bytes_Specific(bool useSpan) [InlineData(true)] public void Bytes_Agnostic(bool useSpan) { - using (var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray)) - { - VerifyDecodedImage(img); - } + using var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray); + VerifyDecodedImage(img); } [Theory] @@ -52,10 +48,8 @@ public void Bytes_Agnostic(bool useSpan) [InlineData(true)] public void Bytes_Decoder_Specific(bool useSpan) { - using (var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder()); + VerifyDecodedImage(img); } [Theory] @@ -63,10 +57,8 @@ public void Bytes_Decoder_Specific(bool useSpan) [InlineData(true)] public void Bytes_Decoder_Agnostic(bool useSpan) { - using (var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder()); + VerifyDecodedImage(img); } [Theory] @@ -75,11 +67,9 @@ public void Bytes_Decoder_Agnostic(bool useSpan) public void Bytes_OutFormat_Specific(bool useSpan) { IImageFormat format; - using (var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format); + VerifyDecodedImage(img); + Assert.IsType(format); } [Theory] @@ -88,11 +78,9 @@ public void Bytes_OutFormat_Specific(bool useSpan) public void Bytes_OutFormat_Agnostic(bool useSpan) { IImageFormat format; - using (var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format); + VerifyDecodedImage(img); + Assert.IsType(format); } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs index a35557c83e..f09d989611 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs @@ -29,57 +29,45 @@ private static void VerifyDecodedImage(Image img) [Fact] public void Stream_Specific() { - using (var img = Image.Load(this.Stream)) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Stream); + VerifyDecodedImage(img); } [Fact] public void Stream_Agnostic() { - using (var img = Image.Load(this.Stream)) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Stream); + VerifyDecodedImage(img); } [Fact] public void Stream_OutFormat_Specific() { - using (var img = Image.Load(this.Stream, out IImageFormat format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = Image.Load(this.Stream, out IImageFormat format); + VerifyDecodedImage(img); + Assert.IsType(format); } [Fact] public void Stream_Decoder_Specific() { - using (var img = Image.Load(this.Stream, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Stream, new BmpDecoder()); + VerifyDecodedImage(img); } [Fact] public void Stream_Decoder_Agnostic() { - using (var img = Image.Load(this.Stream, new BmpDecoder())) - { - VerifyDecodedImage(img); - } + using var img = Image.Load(this.Stream, new BmpDecoder()); + VerifyDecodedImage(img); } [Fact] public void Stream_OutFormat_Agnostic() { - using (var img = Image.Load(this.Stream, out IImageFormat format)) - { - VerifyDecodedImage(img); - Assert.IsType(format); - } + using var img = Image.Load(this.Stream, out IImageFormat format); + VerifyDecodedImage(img); + Assert.IsType(format); } public void Dispose() diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs index dc65ecfef9..597f32b666 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs @@ -44,12 +44,10 @@ public void WhenExtensionIsUnknown_Throws() Assert.Throws( () => - { - using (var image = new Image(10, 10)) - { - image.Save(file); - } - }); + { + using var image = new Image(10, 10); + image.Save(file); + }); } [Fact] @@ -58,15 +56,11 @@ public void SetEncoding() string dir = TestEnvironment.CreateOutputDirectory(nameof(ImageTests)); string file = System.IO.Path.Combine(dir, "SetEncoding.dat"); - using (var image = new Image(10, 10)) - { - image.Save(file, new PngEncoder()); - } + using var image = new Image(10, 10); + image.Save(file, new PngEncoder()); - using (Image.Load(file, out var mime)) - { - Assert.Equal("image/png", mime.DefaultMimeType); - } + using var load = Image.Load(file, out var mime); + Assert.Equal("image/png", mime.DefaultMimeType); } [Fact] @@ -75,10 +69,8 @@ public void ThrowsWhenDisposed() var image = new Image(5, 5); image.Dispose(); IImageEncoder encoder = Mock.Of(); - using (var stream = new MemoryStream()) - { - Assert.Throws(() => image.Save(stream, encoder)); - } + using var stream = new MemoryStream(); + Assert.Throws(() => image.Save(stream, encoder)); } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs index ea5df2694f..9063e839d5 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs @@ -88,14 +88,12 @@ public void WrapMemory_CreatedImageIsCorrect() var array = new Rgba32[25]; var memory = new Memory(array); - using (var image = Image.WrapMemory(cfg, memory, 5, 5, metaData)) - { - ref Rgba32 pixel0 = ref image.GetPixelSpan()[0]; - Assert.True(Unsafe.AreSame(ref array[0], ref pixel0)); + using var image = Image.WrapMemory(cfg, memory, 5, 5, metaData); + ref Rgba32 pixel0 = ref image.GetPixelSpan()[0]; + Assert.True(Unsafe.AreSame(ref array[0], ref pixel0)); - Assert.Equal(cfg, image.GetConfiguration()); - Assert.Equal(metaData, image.Metadata); - } + Assert.Equal(cfg, image.GetConfiguration()); + Assert.Equal(metaData, image.Metadata); } [Fact] @@ -106,33 +104,27 @@ public void WrapSystemDrawingBitmap_WhenObserved() return; } - using (var bmp = new Bitmap(51, 23)) + using var bmp = new Bitmap(51, 23); + using var memoryManager = new BitmapMemoryManager(bmp); + Memory memory = memoryManager.Memory; + Bgra32 bg = Color.Red; + Bgra32 fg = Color.Green; + + using var image = Image.WrapMemory(memory, bmp.Width, bmp.Height); + Assert.Equal(memory, image.GetPixelMemory()); + image.GetPixelSpan().Fill(bg); + for (var i = 10; i < 20; i++) { - using (var memoryManager = new BitmapMemoryManager(bmp)) - { - Memory memory = memoryManager.Memory; - Bgra32 bg = Color.Red; - Bgra32 fg = Color.Green; - - using (var image = Image.WrapMemory(memory, bmp.Width, bmp.Height)) - { - Assert.Equal(memory, image.GetPixelMemory()); - image.GetPixelSpan().Fill(bg); - for (var i = 10; i < 20; i++) - { - image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); - } - } - - Assert.False(memoryManager.IsDisposed); - } + image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); + } - string fn = System.IO.Path.Combine( - TestEnvironment.ActualOutputDirectoryFullPath, - $"{nameof(this.WrapSystemDrawingBitmap_WhenObserved)}.bmp"); + Assert.False(memoryManager.IsDisposed); - bmp.Save(fn, ImageFormat.Bmp); - } + string fn = System.IO.Path.Combine( + TestEnvironment.ActualOutputDirectoryFullPath, + $"{nameof(this.WrapSystemDrawingBitmap_WhenObserved)}.bmp"); + + bmp.Save(fn, ImageFormat.Bmp); } [Fact] @@ -143,31 +135,29 @@ public void WrapSystemDrawingBitmap_WhenOwned() return; } - using (var bmp = new Bitmap(51, 23)) + using var bmp = new Bitmap(51, 23); + var memoryManager = new BitmapMemoryManager(bmp); + Bgra32 bg = Color.Red; + Bgra32 fg = Color.Green; + + using (var image = Image.WrapMemory(memoryManager, bmp.Width, bmp.Height)) { - var memoryManager = new BitmapMemoryManager(bmp); - Bgra32 bg = Color.Red; - Bgra32 fg = Color.Green; + Assert.Equal(memoryManager.Memory, image.GetPixelMemory()); - using (var image = Image.WrapMemory(memoryManager, bmp.Width, bmp.Height)) + image.GetPixelSpan().Fill(bg); + for (var i = 10; i < 20; i++) { - Assert.Equal(memoryManager.Memory, image.GetPixelMemory()); - - image.GetPixelSpan().Fill(bg); - for (var i = 10; i < 20; i++) - { - image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); - } + image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); } + } - Assert.True(memoryManager.IsDisposed); + Assert.True(memoryManager.IsDisposed); - string fn = System.IO.Path.Combine( - TestEnvironment.ActualOutputDirectoryFullPath, - $"{nameof(this.WrapSystemDrawingBitmap_WhenOwned)}.bmp"); + string fn = System.IO.Path.Combine( + TestEnvironment.ActualOutputDirectoryFullPath, + $"{nameof(this.WrapSystemDrawingBitmap_WhenOwned)}.bmp"); - bmp.Save(fn, ImageFormat.Bmp); - } + bmp.Save(fn, ImageFormat.Bmp); } private static bool ShouldSkipBitmapTest => diff --git a/tests/ImageSharp.Tests/Image/ImageTests.cs b/tests/ImageSharp.Tests/Image/ImageTests.cs index 99bdfceccb..d1f6dae114 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.cs @@ -21,15 +21,13 @@ public class Constructor [Fact] public void Width_Height() { - using (var image = new Image(11, 23)) - { - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(default(Rgba32)); + using var image = new Image(11, 23); + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(default(Rgba32)); - Assert.Equal(Configuration.Default, image.GetConfiguration()); - } + Assert.Equal(Configuration.Default, image.GetConfiguration()); } [Fact] @@ -37,15 +35,13 @@ public void Configuration_Width_Height() { Configuration configuration = Configuration.Default.Clone(); - using (var image = new Image(configuration, 11, 23)) - { - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(default(Rgba32)); + using var image = new Image(configuration, 11, 23); + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(default(Rgba32)); - Assert.Equal(configuration, image.GetConfiguration()); - } + Assert.Equal(configuration, image.GetConfiguration()); } [Fact] @@ -54,15 +50,13 @@ public void Configuration_Width_Height_BackgroundColor() Configuration configuration = Configuration.Default.Clone(); Rgba32 color = Rgba32.Aquamarine; - using (var image = new Image(configuration, 11, 23, color)) - { - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(color); + using var image = new Image(configuration, 11, 23, color); + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(color); - Assert.Equal(configuration, image.GetConfiguration()); - } + Assert.Equal(configuration, image.GetConfiguration()); } [Fact] @@ -74,15 +68,13 @@ public void CreateUninitialized() configuration.MemoryAllocator = new TestMemoryAllocator(dirtyValue); var metadata = new ImageMetadata(); - using (var image = Image.CreateUninitialized(configuration, 21, 22, metadata)) - { - Assert.Equal(21, image.Width); - Assert.Equal(22, image.Height); - Assert.Same(configuration, image.GetConfiguration()); - Assert.Same(metadata, image.Metadata); + using var image = Image.CreateUninitialized(configuration, 21, 22, metadata); + Assert.Equal(21, image.Width); + Assert.Equal(22, image.Height); + Assert.Same(configuration, image.GetConfiguration()); + Assert.Same(metadata, image.Metadata); - Assert.Equal(dirtyValue, image[5, 5].PackedValue); - } + Assert.Equal(dirtyValue, image[5, 5].PackedValue); } } } diff --git a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs index 9eea5518f4..ccbc7ee2f5 100644 --- a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs +++ b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs @@ -37,24 +37,20 @@ public static void SpanPointsTo(Span span, IMemoryOwner buffer, int buf [InlineData(1025, 17)] public void Construct(int width, int height) { - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) - { - Assert.Equal(width, buffer.Width); - Assert.Equal(height, buffer.Height); - Assert.Equal(width * height, buffer.GetMemory().Length); - } + using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); + Assert.Equal(width, buffer.Width); + Assert.Equal(height, buffer.Height); + Assert.Equal(width * height, buffer.GetMemory().Length); } [Fact] public void CreateClean() { - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean)) + using Buffer2D buffer = this.MemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean); + Span span = buffer.GetSpan(); + for (int j = 0; j < span.Length; j++) { - Span span = buffer.GetSpan(); - for (int j = 0; j < span.Length; j++) - { - Assert.Equal(0, span[j]); - } + Assert.Equal(0, span[j]); } } @@ -64,14 +60,12 @@ public void CreateClean() [InlineData(17, 42, 41)] public void GetRowSpanY(int width, int height, int y) { - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) - { - Span span = buffer.GetRowSpan(y); + using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); + Span span = buffer.GetRowSpan(y); - // Assert.Equal(width * y, span.Start); - Assert.Equal(width, span.Length); - Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y); - } + // Assert.Equal(width * y, span.Start); + Assert.Equal(width, span.Length); + Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y); } [Theory] @@ -80,35 +74,31 @@ public void GetRowSpanY(int width, int height, int y) [InlineData(99, 88, 98, 87)] public void Indexer(int width, int height, int x, int y) { - using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) - { - Span span = buffer.MemorySource.GetSpan(); + using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); + Span span = buffer.MemorySource.GetSpan(); - ref TestStructs.Foo actual = ref buffer[x, y]; + ref TestStructs.Foo actual = ref buffer[x, y]; - ref TestStructs.Foo expected = ref span[(y * width) + x]; + ref TestStructs.Foo expected = ref span[(y * width) + x]; - Assert.True(Unsafe.AreSame(ref expected, ref actual)); - } + Assert.True(Unsafe.AreSame(ref expected, ref actual)); } [Fact] public void SwapOrCopyContent() { - using (Buffer2D a = this.MemoryAllocator.Allocate2D(10, 5)) - using (Buffer2D b = this.MemoryAllocator.Allocate2D(3, 7)) - { - IMemoryOwner aa = a.MemorySource.MemoryOwner; - IMemoryOwner bb = b.MemorySource.MemoryOwner; + using Buffer2D a = this.MemoryAllocator.Allocate2D(10, 5); + using Buffer2D b = this.MemoryAllocator.Allocate2D(3, 7); + IMemoryOwner aa = a.MemorySource.MemoryOwner; + IMemoryOwner bb = b.MemorySource.MemoryOwner; - Buffer2D.SwapOrCopyContent(a, b); + Buffer2D.SwapOrCopyContent(a, b); - Assert.Equal(bb, a.MemorySource.MemoryOwner); - Assert.Equal(aa, b.MemorySource.MemoryOwner); + Assert.Equal(bb, a.MemorySource.MemoryOwner); + Assert.Equal(aa, b.MemorySource.MemoryOwner); - Assert.Equal(new Size(3, 7), a.Size()); - Assert.Equal(new Size(10, 5), b.Size()); - } + Assert.Equal(new Size(3, 7), a.Size()); + Assert.Equal(new Size(10, 5), b.Size()); } [Theory] @@ -121,21 +111,19 @@ public void SwapOrCopyContent() public void CopyColumns(int width, int height, int startIndex, int destIndex, int columnCount) { var rnd = new Random(123); - using (Buffer2D b = this.MemoryAllocator.Allocate2D(width, height)) - { - rnd.RandomFill(b.GetSpan(), 0, 1); + using Buffer2D b = this.MemoryAllocator.Allocate2D(width, height); + rnd.RandomFill(b.GetSpan(), 0, 1); - b.CopyColumns(startIndex, destIndex, columnCount); + b.CopyColumns(startIndex, destIndex, columnCount); - for (int y = 0; y < b.Height; y++) - { - Span row = b.GetRowSpan(y); + for (int y = 0; y < b.Height; y++) + { + Span row = b.GetRowSpan(y); - Span s = row.Slice(startIndex, columnCount); - Span d = row.Slice(destIndex, columnCount); + Span s = row.Slice(startIndex, columnCount); + Span d = row.Slice(destIndex, columnCount); - Xunit.Assert.True(s.SequenceEqual(d)); - } + Xunit.Assert.True(s.SequenceEqual(d)); } } @@ -143,22 +131,20 @@ public void CopyColumns(int width, int height, int startIndex, int destIndex, in public void CopyColumns_InvokeMultipleTimes() { var rnd = new Random(123); - using (Buffer2D b = this.MemoryAllocator.Allocate2D(100, 100)) - { - rnd.RandomFill(b.GetSpan(), 0, 1); + using Buffer2D b = this.MemoryAllocator.Allocate2D(100, 100); + rnd.RandomFill(b.GetSpan(), 0, 1); - b.CopyColumns(0, 50, 22); - b.CopyColumns(0, 50, 22); + b.CopyColumns(0, 50, 22); + b.CopyColumns(0, 50, 22); - for (int y = 0; y < b.Height; y++) - { - Span row = b.GetRowSpan(y); + for (int y = 0; y < b.Height; y++) + { + Span row = b.GetRowSpan(y); - Span s = row.Slice(0, 22); - Span d = row.Slice(50, 22); + Span s = row.Slice(0, 22); + Span d = row.Slice(50, 22); - Xunit.Assert.True(s.SequenceEqual(d)); - } + Xunit.Assert.True(s.SequenceEqual(d)); } } } diff --git a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs index eaa2fea0f0..8c70123ac5 100644 --- a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs +++ b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs @@ -13,14 +13,12 @@ public class BufferAreaTests [Fact] public void Construct() { - using (var buffer = Configuration.Default.MemoryAllocator.Allocate2D(10, 20)) - { - var rectangle = new Rectangle(3, 2, 5, 6); - var area = new BufferArea(buffer, rectangle); + using var buffer = Configuration.Default.MemoryAllocator.Allocate2D(10, 20); + var rectangle = new Rectangle(3, 2, 5, 6); + var area = new BufferArea(buffer, rectangle); - Assert.Equal(buffer, area.DestinationBuffer); - Assert.Equal(rectangle, area.Rectangle); - } + Assert.Equal(buffer, area.DestinationBuffer); + Assert.Equal(rectangle, area.Rectangle); } private static Buffer2D CreateTestBuffer(int w, int h) @@ -42,16 +40,14 @@ private static Buffer2D CreateTestBuffer(int w, int h) [InlineData(5, 4, 3, 2)] public void Indexer(int rx, int ry, int x, int y) { - using (Buffer2D buffer = CreateTestBuffer(20, 30)) - { - var r = new Rectangle(rx, ry, 5, 6); + using Buffer2D buffer = CreateTestBuffer(20, 30); + var r = new Rectangle(rx, ry, 5, 6); - BufferArea area = buffer.GetArea(r); + BufferArea area = buffer.GetArea(r); - int value = area[x, y]; - int expected = ((ry + y) * 100) + rx + x; - Assert.Equal(expected, value); - } + int value = area[x, y]; + int expected = ((ry + y) * 100) + rx + x; + Assert.Equal(expected, value); } [Theory] @@ -59,89 +55,79 @@ public void Indexer(int rx, int ry, int x, int y) [InlineData(5, 4, 3, 6, 5)] public void GetRowSpan(int rx, int ry, int y, int w, int h) { - using (Buffer2D buffer = CreateTestBuffer(20, 30)) - { - var r = new Rectangle(rx, ry, w, h); + using Buffer2D buffer = CreateTestBuffer(20, 30); + var r = new Rectangle(rx, ry, w, h); - BufferArea area = buffer.GetArea(r); + BufferArea area = buffer.GetArea(r); - Span span = area.GetRowSpan(y); + Span span = area.GetRowSpan(y); - Assert.Equal(w, span.Length); + Assert.Equal(w, span.Length); - for (int i = 0; i < w; i++) - { - int expected = ((ry + y) * 100) + rx + i; - int value = span[i]; + for (int i = 0; i < w; i++) + { + int expected = ((ry + y) * 100) + rx + i; + int value = span[i]; - Assert.Equal(expected, value); - } + Assert.Equal(expected, value); } } [Fact] public void GetSubArea() { - using (Buffer2D buffer = CreateTestBuffer(20, 30)) - { - BufferArea area0 = buffer.GetArea(6, 8, 10, 10); + using Buffer2D buffer = CreateTestBuffer(20, 30); + BufferArea area0 = buffer.GetArea(6, 8, 10, 10); - BufferArea area1 = area0.GetSubArea(4, 4, 5, 5); + BufferArea area1 = area0.GetSubArea(4, 4, 5, 5); - var expectedRect = new Rectangle(10, 12, 5, 5); + var expectedRect = new Rectangle(10, 12, 5, 5); - Assert.Equal(buffer, area1.DestinationBuffer); - Assert.Equal(expectedRect, area1.Rectangle); + Assert.Equal(buffer, area1.DestinationBuffer); + Assert.Equal(expectedRect, area1.Rectangle); - int value00 = (12 * 100) + 10; - Assert.Equal(value00, area1[0, 0]); - } + int value00 = (12 * 100) + 10; + Assert.Equal(value00, area1[0, 0]); } [Fact] public void DangerousGetPinnableReference() { - using (Buffer2D buffer = CreateTestBuffer(20, 30)) - { - BufferArea area0 = buffer.GetArea(6, 8, 10, 10); + using Buffer2D buffer = CreateTestBuffer(20, 30); + BufferArea area0 = buffer.GetArea(6, 8, 10, 10); - ref int r = ref area0.GetReferenceToOrigin(); + ref int r = ref area0.GetReferenceToOrigin(); - int expected = buffer[6, 8]; - Assert.Equal(expected, r); - } + int expected = buffer[6, 8]; + Assert.Equal(expected, r); } [Fact] public void Clear_FullArea() { - using (Buffer2D buffer = CreateTestBuffer(22, 13)) - { - buffer.GetArea().Clear(); - Span fullSpan = buffer.GetSpan(); - Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length])); - } + using Buffer2D buffer = CreateTestBuffer(22, 13); + buffer.GetArea().Clear(); + Span fullSpan = buffer.GetSpan(); + Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length])); } [Fact] public void Clear_SubArea() { - using (Buffer2D buffer = CreateTestBuffer(20, 30)) - { - BufferArea area = buffer.GetArea(5, 5, 10, 10); - area.Clear(); + using Buffer2D buffer = CreateTestBuffer(20, 30); + BufferArea area = buffer.GetArea(5, 5, 10, 10); + area.Clear(); - Assert.NotEqual(0, buffer[4, 4]); - Assert.NotEqual(0, buffer[15, 15]); + Assert.NotEqual(0, buffer[4, 4]); + Assert.NotEqual(0, buffer[15, 15]); - Assert.Equal(0, buffer[5, 5]); - Assert.Equal(0, buffer[14, 14]); + Assert.Equal(0, buffer[5, 5]); + Assert.Equal(0, buffer[14, 14]); - for (int y = area.Rectangle.Y; y < area.Rectangle.Bottom; y++) - { - Span span = buffer.GetRowSpan(y).Slice(area.Rectangle.X, area.Width); - Assert.True(span.SequenceEqual(new int[area.Width])); - } + for (int y = area.Rectangle.Y; y < area.Rectangle.Bottom; y++) + { + Span span = buffer.GetRowSpan(y).Slice(area.Rectangle.X, area.Width); + Assert.True(span.SequenceEqual(new int[area.Width])); } } } diff --git a/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs b/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs index bdca87ef7e..d97e8805cf 100644 --- a/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs +++ b/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs @@ -91,17 +91,15 @@ public void SyncProfiles() exifProfile.SetValue(ExifTag.XResolution, new Rational(200)); exifProfile.SetValue(ExifTag.YResolution, new Rational(300)); - using (var image = new Image(1, 1)) - { - image.Metadata.ExifProfile = exifProfile; - image.Metadata.HorizontalResolution = 400; - image.Metadata.VerticalResolution = 500; + using var image = new Image(1, 1); + image.Metadata.ExifProfile = exifProfile; + image.Metadata.HorizontalResolution = 400; + image.Metadata.VerticalResolution = 500; - image.Metadata.SyncProfiles(); + image.Metadata.SyncProfiles(); - Assert.Equal(400, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); - Assert.Equal(500, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); - } + Assert.Equal(400, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); + Assert.Equal(500, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); } } } diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs index d3177f6f59..f3a540d84a 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs @@ -95,42 +95,40 @@ public void ConstructorCopy() [InlineData(TestImageWriteFormat.Png)] public void WriteFraction(TestImageWriteFormat imageFormat) { - using (var memStream = new MemoryStream()) - { - double exposureTime = 1.0 / 1600; + using var memStream = new MemoryStream(); + double exposureTime = 1.0 / 1600; - ExifProfile profile = GetExifProfile(); + ExifProfile profile = GetExifProfile(); - profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime)); + profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime)); - var image = new Image(1, 1); - image.Metadata.ExifProfile = profile; + var image = new Image(1, 1); + image.Metadata.ExifProfile = profile; - image = WriteAndRead(image, imageFormat); + image = WriteAndRead(image, imageFormat); - profile = image.Metadata.ExifProfile; - Assert.NotNull(profile); + profile = image.Metadata.ExifProfile; + Assert.NotNull(profile); - IExifValue value = profile.GetValue(ExifTag.ExposureTime); - Assert.NotNull(value); - Assert.NotEqual(exposureTime, value.Value.ToDouble()); + IExifValue value = profile.GetValue(ExifTag.ExposureTime); + Assert.NotNull(value); + Assert.NotEqual(exposureTime, value.Value.ToDouble()); - memStream.Position = 0; - profile = GetExifProfile(); + memStream.Position = 0; + profile = GetExifProfile(); - profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime, true)); - image.Metadata.ExifProfile = profile; + profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime, true)); + image.Metadata.ExifProfile = profile; - image = WriteAndRead(image, imageFormat); + image = WriteAndRead(image, imageFormat); - profile = image.Metadata.ExifProfile; - Assert.NotNull(profile); + profile = image.Metadata.ExifProfile; + Assert.NotNull(profile); - value = profile.GetValue(ExifTag.ExposureTime); - Assert.Equal(exposureTime, value.Value.ToDouble()); + value = profile.GetValue(ExifTag.ExposureTime); + Assert.Equal(exposureTime, value.Value.ToDouble()); - image.Dispose(); - } + image.Dispose(); } [Theory] @@ -454,26 +452,22 @@ private static Image WriteAndRead(Image image, TestImageWriteFor private static Image WriteAndReadJpeg(Image image) { - using (var memStream = new MemoryStream()) - { - image.SaveAsJpeg(memStream); - image.Dispose(); + using var memStream = new MemoryStream(); + image.SaveAsJpeg(memStream); + image.Dispose(); - memStream.Position = 0; - return Image.Load(memStream); - } + memStream.Position = 0; + return Image.Load(memStream); } private static Image WriteAndReadPng(Image image) { - using (var memStream = new MemoryStream()) - { - image.SaveAsPng(memStream); - image.Dispose(); + using var memStream = new MemoryStream(); + image.SaveAsPng(memStream); + image.Dispose(); - memStream.Position = 0; - return Image.Load(memStream); - } + memStream.Position = 0; + return Image.Load(memStream); } private static void TestProfile(ExifProfile profile) diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs index 7f52fb6cae..47b5dbbd2e 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs @@ -13,10 +13,8 @@ public class ExifValueTests public ExifValueTests() { - using (Image image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image()) - { - this.profile = image.Metadata.ExifProfile; - } + using Image image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image(); + this.profile = image.Metadata.ExifProfile; } private IExifValue GetExifValue() diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs index a91ea09776..d57abb4996 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs @@ -33,28 +33,24 @@ public class PorterDuffCompositorTests public void PorterDuffOutputIsCorrect(TestImageProvider provider, PixelAlphaCompositionMode mode) { var srcFile = TestFile.Create(TestImages.Png.PDSrc); - using (Image src = srcFile.CreateRgba32Image()) - using (Image dest = provider.GetImage()) + using Image src = srcFile.CreateRgba32Image(); + using Image dest = provider.GetImage(); + var options = new GraphicsOptions { - var options = new GraphicsOptions - { - Antialias = false, - AlphaCompositionMode = mode - }; - - using (Image res = dest.Clone(x => x.DrawImage(src, options))) - { - string combinedMode = mode.ToString(); + Antialias = false, + AlphaCompositionMode = mode + }; - if (combinedMode != "Src" && combinedMode.StartsWith("Src")) - { - combinedMode = combinedMode.Substring(3); - } + using Image res = dest.Clone(x => x.DrawImage(src, options)); + string combinedMode = mode.ToString(); - res.DebugSave(provider, combinedMode); - res.CompareToReferenceOutput(provider, combinedMode); - } + if (combinedMode != "Src" && combinedMode.StartsWith("Src")) + { + combinedMode = combinedMode.Substring(3); } + + res.DebugSave(provider, combinedMode); + res.CompareToReferenceOutput(provider, combinedMode); } } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs index 1ecbaf3615..98a657950d 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs +++ b/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. using System.Buffers; @@ -30,17 +30,15 @@ public void Benchmark_ToVector4() const int times = 200000; const int count = 1024; - using (IMemoryOwner source = Configuration.Default.MemoryAllocator.Allocate(count)) - using (IMemoryOwner dest = Configuration.Default.MemoryAllocator.Allocate(count)) - { - this.Measure( - times, - () => PixelOperations.Instance.ToVector4( - this.Configuration, - source.GetSpan(), - dest.GetSpan())); - } + using IMemoryOwner source = Configuration.Default.MemoryAllocator.Allocate(count); + using IMemoryOwner dest = Configuration.Default.MemoryAllocator.Allocate(count); + this.Measure( + times, + () => PixelOperations.Instance.ToVector4( + this.Configuration, + source.GetSpan(), + dest.GetSpan())); } } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs index 0cea91c781..0dc542673d 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs @@ -997,11 +997,9 @@ internal static void TestOperation( where TSource : struct where TDest : struct { - using (var buffers = new TestBuffers(source, expected)) - { - action(buffers.SourceBuffer, buffers.ActualDestBuffer); - buffers.Verify(); - } + using var buffers = new TestBuffers(source, expected); + action(buffers.SourceBuffer, buffers.ActualDestBuffer); + buffers.Verify(); } internal static Vector4[] CreateVector4TestData(int length, RefAction vectorModifier = null) diff --git a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs index 3ab6049953..4802b26c61 100644 --- a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs +++ b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs @@ -32,19 +32,18 @@ public void HistogramEqualizationTest(int luminanceLevels) 70, 87, 69, 68, 65, 73, 78, 90 }; - using (var image = new Image(8, 8)) + using var image = new Image(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++) - { - byte luminance = pixels[(y * 8) + x]; - image[x, y] = new Rgba32(luminance, luminance, luminance); - } + byte luminance = pixels[(y * 8) + x]; + image[x, y] = new Rgba32(luminance, luminance, luminance); } + } - var expected = new byte[] - { + var expected = new byte[] + { 0, 12, 53, 32, 146, 53, 174, 53, 57, 32, 12, 227, 219, 202, 32, 154, 65, 85, 93, 239, 251, 227, 65, 158, @@ -53,24 +52,23 @@ public void HistogramEqualizationTest(int luminanceLevels) 117, 190, 36, 190, 178, 93, 20, 170, 130, 202, 73, 20, 12, 53, 85, 194, 146, 206, 130, 117, 85, 166, 182, 215 - }; + }; - // Act - image.Mutate(x => x.HistogramEqualization(new HistogramEqualizationOptions - { - LuminanceLevels = luminanceLevels - })); + // Act + image.Mutate(x => x.HistogramEqualization(new HistogramEqualizationOptions + { + LuminanceLevels = luminanceLevels + })); - // Assert - for (int y = 0; y < 8; y++) + // Assert + for (int y = 0; y < 8; y++) + { + for (int x = 0; x < 8; x++) { - for (int x = 0; x < 8; x++) - { - Rgba32 actual = image[x, y]; - Assert.Equal(expected[(y * 8) + x], actual.R); - Assert.Equal(expected[(y * 8) + x], actual.G); - Assert.Equal(expected[(y * 8) + x], actual.B); - } + Rgba32 actual = image[x, y]; + Assert.Equal(expected[(y * 8) + x], actual.R); + Assert.Equal(expected[(y * 8) + x], actual.G); + Assert.Equal(expected[(y * 8) + x], actual.B); } } } @@ -80,19 +78,17 @@ public void HistogramEqualizationTest(int luminanceLevels) public void Adaptive_SlidingWindow_15Tiles_WithClipping(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new HistogramEqualizationOptions { - var options = new HistogramEqualizationOptions - { - Method = HistogramEqualizationMethod.AdaptiveSlidingWindow, - LuminanceLevels = 256, - ClipHistogram = true, - NumberOfTiles = 15 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + Method = HistogramEqualizationMethod.AdaptiveSlidingWindow, + LuminanceLevels = 256, + ClipHistogram = true, + NumberOfTiles = 15 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -100,19 +96,17 @@ public void Adaptive_SlidingWindow_15Tiles_WithClipping(TestImageProvide public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new HistogramEqualizationOptions { - var options = new HistogramEqualizationOptions - { - Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, - LuminanceLevels = 256, - ClipHistogram = true, - NumberOfTiles = 10 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, + LuminanceLevels = 256, + ClipHistogram = true, + NumberOfTiles = 10 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } /// @@ -127,20 +121,18 @@ public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImagePro public void Issue984(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new HistogramEqualizationOptions() { - var options = new HistogramEqualizationOptions() - { - Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, - LuminanceLevels = 256, - ClipHistogram = true, - ClipLimit = 5, - NumberOfTiles = 10 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, + LuminanceLevels = 256, + ClipHistogram = true, + ClipLimit = 5, + NumberOfTiles = 10 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs index 3fe624498a..1a42136d50 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs @@ -52,11 +52,9 @@ public class BinaryDitherTests public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider provider, string name, IOrderedDither ditherer) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.BinaryDither(ditherer)); - image.DebugSave(provider, name); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.BinaryDither(ditherer)); + image.DebugSave(provider, name); } [Theory] @@ -65,11 +63,9 @@ public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider(TestImageProvider provider, string name, IErrorDiffuser diffuser) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.BinaryDiffuse(diffuser, .5F)); - image.DebugSave(provider, name); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.BinaryDiffuse(diffuser, .5F)); + image.DebugSave(provider, name); } [Theory] @@ -77,11 +73,9 @@ public void DiffusionFilter_WorksWithAllErrorDiffusers(TestImageProvider public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.BinaryDither(DefaultDitherer)); - image.DebugSave(provider); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.BinaryDither(DefaultDitherer)); + image.DebugSave(provider); } [Theory] @@ -89,11 +83,9 @@ public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType(TestImag public void DiffusionFilter_ShouldNotDependOnSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f)); - image.DebugSave(provider); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f)); + image.DebugSave(provider); } [Theory] @@ -101,16 +93,14 @@ public void DiffusionFilter_ShouldNotDependOnSinglePixelType(TestImagePr public void ApplyDitherFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image source = provider.GetImage()) - using (Image image = source.Clone()) - { - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using Image source = provider.GetImage(); + using Image image = source.Clone(); + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds)); - image.DebugSave(provider); + image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds)); + image.DebugSave(provider); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); - } + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); } [Theory] @@ -118,16 +108,14 @@ public void ApplyDitherFilterInBox(TestImageProvider provider) public void ApplyDiffusionFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image source = provider.GetImage()) - using (Image image = source.Clone()) - { - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using Image source = provider.GetImage(); + using Image image = source.Clone(); + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds)); - image.DebugSave(provider); + image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds)); + image.DebugSave(provider); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); - } + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs index dd999757db..f06b601527 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs @@ -32,11 +32,9 @@ public static readonly TheoryData BinaryThresholdValues public void ImageShouldApplyBinaryThresholdFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.BinaryThreshold(value)); - image.DebugSave(provider, value); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.BinaryThreshold(value)); + image.DebugSave(provider, value); } [Theory] @@ -44,16 +42,14 @@ public void ImageShouldApplyBinaryThresholdFilter(TestImageProvider(TestImageProvider provider, float value) where TPixel : struct, IPixel { - using (Image source = provider.GetImage()) - using (var image = source.Clone()) - { - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using Image source = provider.GetImage(); + using var image = source.Clone(); + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryThreshold(value, bounds)); - image.DebugSave(provider, value); + image.Mutate(x => x.BinaryThreshold(value, bounds)); + image.DebugSave(provider, value); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); - } + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs index e9baee6bd7..b4b64e2100 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs @@ -56,23 +56,19 @@ public void VerifyComplexComponents() } // Make sure the kernel components are the same - using (var image = new Image(1, 1)) + using var image = new Image(1, 1); + Configuration configuration = image.GetConfiguration(); + var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); + using var processor = (BokehBlurProcessor)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds()); + Assert.Equal(components.Count, processor.Kernels.Count); + foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) { - Configuration configuration = image.GetConfiguration(); - var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); - using (var processor = (BokehBlurProcessor)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds())) + Span spanA = a.AsSpan(), spanB = b.AsSpan(); + Assert.Equal(spanA.Length, spanB.Length); + for (int i = 0; i < spanA.Length; i++) { - Assert.Equal(components.Count, processor.Kernels.Count); - foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) - { - Span spanA = a.AsSpan(), spanB = b.AsSpan(); - Assert.Equal(spanA.Length, spanB.Length); - for (int i = 0; i < spanA.Length; i++) - { - Assert.True(Math.Abs(Math.Abs(spanA[i].Real) - Math.Abs(spanB[i].Real)) < 0.0001f); - Assert.True(Math.Abs(Math.Abs(spanA[i].Imaginary) - Math.Abs(spanB[i].Imaginary)) < 0.0001f); - } - } + Assert.True(Math.Abs(Math.Abs(spanA[i].Real) - Math.Abs(spanB[i].Real)) < 0.0001f); + Assert.True(Math.Abs(Math.Abs(spanA[i].Imaginary) - Math.Abs(spanB[i].Imaginary)) < 0.0001f); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs index 2396f6ee25..b742554f5b 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs @@ -57,12 +57,10 @@ public void DetectEdges_WorksOnWrappedMemoryImage(TestImageProvider(TestImageProvider provider, EdgeDetectionOperators detector) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.DetectEdges(detector)); - image.DebugSave(provider, detector.ToString()); - image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString()); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.DetectEdges(detector)); + image.DebugSave(provider, detector.ToString()); + image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString()); } [Theory] @@ -70,12 +68,10 @@ public void DetectEdges_WorksWithAllFilters(TestImageProvider pr public void DetectEdges_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.DetectEdges()); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.DetectEdges()); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -83,11 +79,9 @@ public void DetectEdges_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.DetectEdges()); - image.DebugSave(provider, extension: "gif"); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.DetectEdges()); + image.DebugSave(provider, extension: "gif"); } [Theory] @@ -95,14 +89,12 @@ public void DetectEdges_IsAppliedToAllFrames(TestImageProvider p public void DetectEdges_InBox(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using Image image = provider.GetImage(); + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.DetectEdges(bounds)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.Mutate(x => x.DetectEdges(bounds)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs index 68852a939a..8cca265477 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs @@ -44,15 +44,13 @@ public static readonly TheoryData InvalidOrientationValues public void AutoOrient_WorksForAllExifOrientations(TestImageProvider provider, ushort orientation) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Metadata.ExifProfile = new ExifProfile(); - image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation); + using Image image = provider.GetImage(); + image.Metadata.ExifProfile = new ExifProfile(); + image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation); - image.Mutate(x => x.AutoOrient()); - image.DebugSave(provider, orientation, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false); - } + image.Mutate(x => x.AutoOrient()); + image.DebugSave(provider, orientation, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false); } [Theory] @@ -80,14 +78,12 @@ public void AutoOrient_WorksWithCorruptExifData(TestImageProvider image = provider.GetImage()) - using (Image reference = image.Clone()) - { - image.Metadata.ExifProfile = new ExifProfile(bytes); - image.Mutate(x => x.AutoOrient()); - image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false); - ImageComparer.Exact.VerifySimilarity(image, reference); - } + using Image image = provider.GetImage(); + using Image reference = image.Clone(); + image.Metadata.ExifProfile = new ExifProfile(bytes); + image.Mutate(x => x.AutoOrient()); + image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false); + ImageComparer.Exact.VerifySimilarity(image, reference); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs index dbaff43f0c..edaccb7534 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs @@ -19,18 +19,16 @@ public class PadTest public void ImageShouldPad(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50)); - image.DebugSave(provider); + using Image image = provider.GetImage(); + image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50)); + image.DebugSave(provider); - // Check pixels are empty - for (int y = 0; y < 25; y++) + // Check pixels are empty + for (int y = 0; y < 25; y++) + { + for (int x = 0; x < 25; x++) { - for (int x = 0; x < 25; x++) - { - Assert.Equal(default, image[x, y]); - } + Assert.Equal(default, image[x, y]); } } } @@ -42,18 +40,16 @@ public void ImageShouldPadWithBackgroundColor(TestImageProvider { var color = Color.Red; TPixel expected = color.ToPixel(); - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color)); - image.DebugSave(provider); + using Image image = provider.GetImage(); + image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color)); + image.DebugSave(provider); - // Check pixels are filled - for (int y = 0; y < 25; y++) + // Check pixels are filled + for (int y = 0; y < 25; y++) + { + for (int x = 0; x < 25; x++) { - for (int x = 0; x < 25; x++) - { - Assert.Equal(expected, image[x, y]); - } + Assert.Equal(expected, image[x, y]); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs index 6dd2b4293e..d5addc2c4e 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs @@ -45,15 +45,13 @@ public void Resize_PixelAgnostic() { var filePath = TestFile.GetInputFileFullPath(TestImages.Jpeg.Baseline.Calliphora); - using (var image = Image.Load(filePath)) - { - image.Mutate(x => x.Resize(image.Size() / 2)); - string path = System.IO.Path.Combine( - TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)), - nameof(this.Resize_PixelAgnostic) + ".png"); + using var image = Image.Load(filePath); + image.Mutate(x => x.Resize(image.Size() / 2)); + string path = System.IO.Path.Combine( + TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)), + nameof(this.Resize_PixelAgnostic) + ".png"); - image.Save(path); - } + image.Save(path); } [Theory(Skip = "Debug only, enable manually")] @@ -70,11 +68,9 @@ public void LargeImage(TestImageProvider provider, int destSize, provider.Configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInKilobytes * 1024; - using (var image = provider.GetImage()) - { - image.Mutate(x => x.Resize(destSize, destSize)); - image.DebugSave(provider, appendPixelTypeToFileName: false); - } + using var image = provider.GetImage(); + image.Mutate(x => x.Resize(destSize, destSize)); + image.DebugSave(provider, appendPixelTypeToFileName: false); } [Theory] @@ -88,14 +84,12 @@ public void Resize_BasicSmall(TestImageProvider provider, int wN // [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] means: // resizing: (15, 12) -> (10, 6) // kernel dimensions: (3, 4) - using (Image image = provider.GetImage()) - { - var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); - image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); - FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})"; - image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false); - } + using Image image = provider.GetImage(); + var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); + image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); + FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})"; + image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false); } private static readonly int SizeOfVector4 = Unsafe.SizeOf(); @@ -113,47 +107,43 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( int workingBufferLimitInRows) where TPixel : struct, IPixel { - using (Image image0 = provider.GetImage()) - { - Size destSize = image0.Size() / 4; + using Image image0 = provider.GetImage(); + Size destSize = image0.Size() / 4; + + var configuration = Configuration.CreateDefaultInstance(); + + int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4; + var allocator = new TestMemoryAllocator(); + configuration.MemoryAllocator = allocator; + configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes; + + var verticalKernelMap = ResizeKernelMap.Calculate( + KnownResamplers.Bicubic, + destSize.Height, + image0.Height, + Configuration.Default.MemoryAllocator); + int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4; + verticalKernelMap.Dispose(); + + using Image image = image0.Clone(configuration); + image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); + + image.DebugSave( + provider, + testOutputDetails: workingBufferLimitInRows, + appendPixelTypeToFileName: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.001f), + provider, + testOutputDetails: workingBufferLimitInRows, + appendPixelTypeToFileName: false); - Configuration configuration = Configuration.CreateDefaultInstance(); + Assert.NotEmpty(allocator.AllocationLog); - int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4; - TestMemoryAllocator allocator = new TestMemoryAllocator(); - configuration.MemoryAllocator = allocator; - configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes; + int maxAllocationSize = allocator.AllocationLog.Where( + e => e.ElementType == typeof(Vector4)).Max(e => e.LengthInBytes); - var verticalKernelMap = ResizeKernelMap.Calculate( - KnownResamplers.Bicubic, - destSize.Height, - image0.Height, - Configuration.Default.MemoryAllocator); - int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4; - verticalKernelMap.Dispose(); - - using (Image image = image0.Clone(configuration)) - { - image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); - - image.DebugSave( - provider, - testOutputDetails: workingBufferLimitInRows, - appendPixelTypeToFileName: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.001f), - provider, - testOutputDetails: workingBufferLimitInRows, - appendPixelTypeToFileName: false); - - Assert.NotEmpty(allocator.AllocationLog); - - int maxAllocationSize = allocator.AllocationLog.Where( - e => e.ElementType == typeof(Vector4)).Max(e => e.LengthInBytes); - - Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes)); - } - } + Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes)); } [Theory] @@ -161,13 +151,11 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( public void Resize_Compand(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(image.Size() / 2, true)); + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(image.Size() / 2, true)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -190,13 +178,11 @@ public void Resize_DoesNotBleedAlphaPixels(TestImageProvider pro public void Resize_IsAppliedToAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic)); + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic)); - // Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :( - image.DebugSave(provider, extension: "gif"); - } + // Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :( + image.DebugSave(provider, extension: "gif"); } [Theory] @@ -212,16 +198,12 @@ public void Resize_IsNotBoundToSinglePixelType(TestImageProvider public void Resize_ThrowsForWrappedMemoryImage(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image0 = provider.GetImage()) - { - var mmg = TestMemoryManager.CreateAsCopyOf(image0.GetPixelSpan()); + using Image image0 = provider.GetImage(); + var mmg = TestMemoryManager.CreateAsCopyOf(image0.GetPixelSpan()); - using (var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height)) - { - Assert.ThrowsAny( - () => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); }); - } - } + using var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height); + Assert.ThrowsAny( + () => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); }); } [Theory] @@ -328,27 +310,25 @@ public void Resize_WorksWithAllResamplers( public void ResizeFromSourceRectangle(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var sourceRectangle = new Rectangle( - image.Width / 8, - image.Height / 8, - image.Width / 4, - image.Height / 4); - var destRectangle = new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2); - - image.Mutate( - x => x.Resize( - image.Width, - image.Height, - KnownResamplers.Bicubic, - sourceRectangle, - destRectangle, - false)); - - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + using Image image = provider.GetImage(); + var sourceRectangle = new Rectangle( + image.Width / 8, + image.Height / 8, + image.Width / 4, + image.Height / 4); + var destRectangle = new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2); + + image.Mutate( + x => x.Resize( + image.Width, + image.Height, + KnownResamplers.Bicubic, + sourceRectangle, + destRectangle, + false)); + + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -356,13 +336,11 @@ public void ResizeFromSourceRectangle(TestImageProvider provider public void ResizeHeightAndKeepAspect(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(0, image.Height / 3, false)); + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(0, image.Height / 3, false)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -370,12 +348,10 @@ public void ResizeHeightAndKeepAspect(TestImageProvider provider public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(0, 5)); - Assert.Equal(1, image.Width); - Assert.Equal(5, image.Height); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(0, 5)); + Assert.Equal(1, image.Width); + Assert.Equal(5, image.Height); } [Theory] @@ -383,13 +359,11 @@ public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider< public void ResizeWidthAndKeepAspect(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(image.Width / 3, 0, false)); + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(image.Width / 3, 0, false)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -397,12 +371,10 @@ public void ResizeWidthAndKeepAspect(TestImageProvider provider) public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.Resize(5, 0)); - Assert.Equal(5, image.Width); - Assert.Equal(1, image.Height); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.Resize(5, 0)); + Assert.Equal(5, image.Width); + Assert.Equal(1, image.Height); } [Theory] @@ -410,19 +382,17 @@ public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new ResizeOptions { - var options = new ResizeOptions - { - Size = new Size(image.Width + 200, image.Height + 200), - Mode = ResizeMode.BoxPad - }; + Size = new Size(image.Width + 200, image.Height + 200), + Mode = ResizeMode.BoxPad + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -430,15 +400,13 @@ public void ResizeWithBoxPadMode(TestImageProvider provider) public void ResizeWithCropHeightMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) }; + using Image image = provider.GetImage(); + var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -446,15 +414,13 @@ public void ResizeWithCropHeightMode(TestImageProvider provider) public void ResizeWithCropWidthMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) }; + using Image image = provider.GetImage(); + var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -462,19 +428,17 @@ public void ResizeWithCropWidthMode(TestImageProvider provider) public void CanResizeLargeImageWithCropMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new ResizeOptions { - var options = new ResizeOptions - { - Size = new Size(480, 600), - Mode = ResizeMode.Crop - }; + Size = new Size(480, 600), + Mode = ResizeMode.Crop + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -482,15 +446,13 @@ public void CanResizeLargeImageWithCropMode(TestImageProvider pr public void ResizeWithMaxMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max }; + using Image image = provider.GetImage(); + var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -498,21 +460,19 @@ public void ResizeWithMaxMode(TestImageProvider provider) public void ResizeWithMinMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new ResizeOptions { - var options = new ResizeOptions - { - Size = new Size( - (int)Math.Round(image.Width * .75F), - (int)Math.Round(image.Height * .95F)), - Mode = ResizeMode.Min - }; - - image.Mutate(x => x.Resize(options)); - - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + Size = new Size( + (int)Math.Round(image.Width * .75F), + (int)Math.Round(image.Height * .95F)), + Mode = ResizeMode.Min + }; + + image.Mutate(x => x.Resize(options)); + + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -520,19 +480,17 @@ public void ResizeWithMinMode(TestImageProvider provider) public void ResizeWithPadMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new ResizeOptions { - var options = new ResizeOptions - { - Size = new Size(image.Width + 200, image.Height), - Mode = ResizeMode.Pad - }; + Size = new Size(image.Width + 200, image.Height), + Mode = ResizeMode.Pad + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -540,19 +498,17 @@ public void ResizeWithPadMode(TestImageProvider provider) public void ResizeWithStretchMode(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + var options = new ResizeOptions { - var options = new ResizeOptions - { - Size = new Size(image.Width / 2, image.Height), - Mode = ResizeMode.Stretch - }; + Size = new Size(image.Width / 2, image.Height), + Mode = ResizeMode.Stretch + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -568,11 +524,10 @@ public void CanResizeExifIssueImages(TestImageProvider provider) return; } - using (Image image = provider.GetImage()) - { - // Don't bother saving, we're testing the EXIF metadata updates. - image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2)); - } + using Image image = provider.GetImage(); + + // Don't bother saving, we're testing the EXIF metadata updates. + image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2)); } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs index 1606a7f7bb..0dd2ff5ef8 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs +++ b/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. using SixLabors.ImageSharp.PixelFormats; @@ -29,11 +29,9 @@ public static readonly TheoryData RotateFlipValues public void RotateFlip(TestImageProvider provider, RotateMode rotateType, FlipMode flipType) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.Mutate(x => x.RotateFlip(rotateType, flipType)); - image.DebugSave(provider, string.Join("_", rotateType, flipType)); - } + using Image image = provider.GetImage(); + image.Mutate(x => x.RotateFlip(rotateType, flipType)); + image.DebugSave(provider, string.Join("_", rotateType, flipType)); } } -} \ No newline at end of file +} diff --git a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs index 38839e44a1..94e503479e 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs @@ -81,16 +81,14 @@ public void Transform_DoesNotCreateEdgeArtifacts(TestImageProvider { IResampler resampler = GetResampler(resamplerName); - using (Image image = provider.GetImage()) - { - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(30); + using Image image = provider.GetImage(); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(30); - image.Mutate(c => c.Transform(builder, resampler)); - image.DebugSave(provider, resamplerName); + image.Mutate(c => c.Transform(builder, resampler)); + image.DebugSave(provider, resamplerName); - VerifyAllPixelsAreWhiteOrTransparent(image); - } + VerifyAllPixelsAreWhiteOrTransparent(image); } [Theory] @@ -104,22 +102,20 @@ public void Transform_RotateScaleTranslate( float ty) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.DebugSave(provider, $"_original"); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(angleDeg) - .AppendScale(new SizeF(sx, sy)) - .AppendTranslation(new PointF(tx, ty)); + using Image image = provider.GetImage(); + image.DebugSave(provider, $"_original"); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(angleDeg) + .AppendScale(new SizeF(sx, sy)) + .AppendTranslation(new PointF(tx, ty)); - this.PrintMatrix(builder.BuildMatrix(image.Size())); + this.PrintMatrix(builder.BuildMatrix(image.Size())); - image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); + image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); - FormattableString testOutputDetails = $"R({angleDeg})_S({sx},{sy})_T({tx},{ty})"; - image.DebugSave(provider, testOutputDetails); - image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); - } + FormattableString testOutputDetails = $"R({angleDeg})_S({sx},{sy})_T({tx},{ty})"; + image.DebugSave(provider, testOutputDetails); + image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); } [Theory] @@ -127,18 +123,16 @@ public void Transform_RotateScaleTranslate( public void Transform_RotateScale_ManuallyCentered(TestImageProvider provider, float angleDeg, float s) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(angleDeg) - .AppendScale(new SizeF(s, s)); + using Image image = provider.GetImage(); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(angleDeg) + .AppendScale(new SizeF(s, s)); - image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); + image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); - FormattableString testOutputDetails = $"R({angleDeg})_S({s})"; - image.DebugSave(provider, testOutputDetails); - image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); - } + FormattableString testOutputDetails = $"R({angleDeg})_S({s})"; + image.DebugSave(provider, testOutputDetails); + image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); } public static readonly TheoryData Transform_IntoRectangle_Data = @@ -163,17 +157,15 @@ public void Transform_FromSourceRectangle1(TestImageProvider pro { var rectangle = new Rectangle(48, 0, 48, 24); - using (Image image = provider.GetImage()) - { - image.DebugSave(provider, $"_original"); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendScale(new SizeF(2, 1.5F)); + using Image image = provider.GetImage(); + image.DebugSave(provider, $"_original"); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendScale(new SizeF(2, 1.5F)); - image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); + image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -183,16 +175,14 @@ public void Transform_FromSourceRectangle2(TestImageProvider pro { var rectangle = new Rectangle(0, 24, 48, 24); - using (Image image = provider.GetImage()) - { - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendScale(new SizeF(1F, 2F)); + using Image image = provider.GetImage(); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendScale(new SizeF(1F, 2F)); - image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); + image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); } [Theory] @@ -201,17 +191,15 @@ public void Transform_WithSampler(TestImageProvider provider, st where TPixel : struct, IPixel { IResampler sampler = GetResampler(resamplerName); - using (Image image = provider.GetImage()) - { - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(50) - .AppendScale(new SizeF(.6F, .6F)); + using Image image = provider.GetImage(); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(50) + .AppendScale(new SizeF(.6F, .6F)); - image.Mutate(i => i.Transform(builder, sampler)); + image.Mutate(i => i.Transform(builder, sampler)); - image.DebugSave(provider, resamplerName); - image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); - } + image.DebugSave(provider, resamplerName); + image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); } private static IResampler GetResampler(string name) diff --git a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs index 5c68247a7d..65be7d3721 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs @@ -64,16 +64,14 @@ public void Transform_WithSampler(TestImageProvider provider, st where TPixel : struct, IPixel { IResampler sampler = GetResampler(resamplerName); - using (Image image = provider.GetImage()) - { - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() - .AppendTaper(TaperSide.Right, TaperCorner.Both, .5F); + using Image image = provider.GetImage(); + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + .AppendTaper(TaperSide.Right, TaperCorner.Both, .5F); - image.Mutate(i => i.Transform(builder, sampler)); + image.Mutate(i => i.Transform(builder, sampler)); - image.DebugSave(provider, resamplerName); - image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); - } + image.DebugSave(provider, resamplerName); + image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); } [Theory] @@ -81,17 +79,15 @@ public void Transform_WithSampler(TestImageProvider provider, st public void Transform_WithTaperMatrix(TestImageProvider provider, TaperSide taperSide, TaperCorner taperCorner) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() - .AppendTaper(taperSide, taperCorner, .5F); + using Image image = provider.GetImage(); + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + .AppendTaper(taperSide, taperCorner, .5F); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - FormattableString testOutputDetails = $"{taperSide}-{taperCorner}"; - image.DebugSave(provider, testOutputDetails); - image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails); - } + FormattableString testOutputDetails = $"{taperSide}-{taperCorner}"; + image.DebugSave(provider, testOutputDetails); + image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails); } [Theory] @@ -104,19 +100,17 @@ public void RawTransformMatchesDocumentedExample(TestImageProvider image = provider.GetImage()) - { - Matrix4x4 matrix = Matrix4x4.Identity; - matrix.M14 = 0.01F; + using Image image = provider.GetImage(); + Matrix4x4 matrix = Matrix4x4.Identity; + matrix.M14 = 0.01F; - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() .AppendMatrix(matrix); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - image.DebugSave(provider); - image.CompareToReferenceOutput(TolerantComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(TolerantComparer, provider); } [Theory] @@ -126,24 +120,22 @@ public void PerspectiveTransformMatchesCSS(TestImageProvider pro { // https://jsfiddle.net/dFrHS/545/ // https://github.com/SixLabors/ImageSharp/issues/787 - using (Image image = provider.GetImage()) - { + using Image image = provider.GetImage(); #pragma warning disable SA1117 // Parameters should be on same line or separate lines - var matrix = new Matrix4x4( - 0.260987f, -0.434909f, 0, -0.0022184f, - 0.373196f, 0.949882f, 0, -0.000312129f, - 0, 0, 1, 0, - 52, 165, 0, 1); + var matrix = new Matrix4x4( + 0.260987f, -0.434909f, 0, -0.0022184f, + 0.373196f, 0.949882f, 0, -0.000312129f, + 0, 0, 1, 0, + 52, 165, 0, 1); #pragma warning restore SA1117 // Parameters should be on same line or separate lines - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() .AppendMatrix(matrix); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - image.DebugSave(provider); - image.CompareToReferenceOutput(TolerantComparer, provider); - } + image.DebugSave(provider); + image.CompareToReferenceOutput(TolerantComparer, provider); } private static IResampler GetResampler(string name) diff --git a/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs b/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs index 9f8034fa37..d964a7d15e 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs @@ -15,21 +15,19 @@ public void HelperCanChangeExifDataType() { int xy = 1; - using (var img = new Image(xy, xy)) - { - var profile = new ExifProfile(); - img.Metadata.ExifProfile = profile; - profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue); - profile.SetValue(ExifTag.PixelYDimension, xy + ushort.MaxValue); + using var img = new Image(xy, xy); + var profile = new ExifProfile(); + img.Metadata.ExifProfile = profile; + profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue); + profile.SetValue(ExifTag.PixelYDimension, xy + ushort.MaxValue); - Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelXDimension).DataType); - Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelYDimension).DataType); + Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelXDimension).DataType); + Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelYDimension).DataType); - TransformProcessorHelpers.UpdateDimensionalMetadata(img); + TransformProcessorHelpers.UpdateDimensionalMetadata(img); - Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelXDimension).DataType); - Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelYDimension).DataType); - } + Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelXDimension).DataType); + Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelYDimension).DataType); } } } diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs index 858607a02f..df61d06ade 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs @@ -26,21 +26,19 @@ public void LoadResizeSave(string imagePath) byte[] imageBytes = TestFile.Create(imagePath).Bytes; - using (var ms = new MemoryStream()) - { - this.Measure( - 30, - () => - { - using (var image = Image.Load(configuration, imageBytes)) - { - image.Mutate(x => x.Resize(image.Size() / 4)); - image.SaveAsJpeg(ms); - } - - ms.Seek(0, SeekOrigin.Begin); - }); - } + using var ms = new MemoryStream(); + this.Measure( + 30, + () => + { + using (var image = Image.Load(configuration, imageBytes)) + { + image.Mutate(x => x.Resize(image.Size() / 4)); + image.SaveAsJpeg(ms); + } + + ms.Seek(0, SeekOrigin.Begin); + }); } } } diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs index ba5eb532b2..c38e3234cf 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs @@ -29,12 +29,10 @@ public void ResizeBicubic(int width, int height) this.Measure( this.ExecutionCount, () => - { - using (var image = new Image(this.configuration, width, height)) - { - image.Mutate(x => x.Resize(width / 5, height / 5)); - } - }); + { + using var image = new Image(this.configuration, width, height); + image.Mutate(x => x.Resize(width / 5, height / 5)); + }); } } } diff --git a/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs b/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs index 7750017095..ddf2a5752d 100644 --- a/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs +++ b/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs @@ -41,20 +41,18 @@ public void OctreeQuantizerYieldsCorrectTransparentPixel( bool dither) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - Assert.True(image[0, 0].Equals(default(TPixel))); + using Image image = provider.GetImage(); + Assert.True(image[0, 0].Equals(default(TPixel))); - var quantizer = new OctreeQuantizer(dither); + var quantizer = new OctreeQuantizer(dither); - foreach (ImageFrame frame in image.Frames) - { - IQuantizedFrame quantized = - quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); + foreach (ImageFrame frame in image.Frames) + { + IQuantizedFrame quantized = + quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); - int index = this.GetTransparentIndex(quantized); - Assert.Equal(index, quantized.GetPixelSpan()[0]); - } + int index = this.GetTransparentIndex(quantized); + Assert.Equal(index, quantized.GetPixelSpan()[0]); } } @@ -64,20 +62,18 @@ public void OctreeQuantizerYieldsCorrectTransparentPixel( public void WuQuantizerYieldsCorrectTransparentPixel(TestImageProvider provider, bool dither) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - Assert.True(image[0, 0].Equals(default(TPixel))); + using Image image = provider.GetImage(); + Assert.True(image[0, 0].Equals(default(TPixel))); - var quantizer = new WuQuantizer(dither); + var quantizer = new WuQuantizer(dither); - foreach (ImageFrame frame in image.Frames) - { - IQuantizedFrame quantized = - quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); + foreach (ImageFrame frame in image.Frames) + { + IQuantizedFrame quantized = + quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); - int index = this.GetTransparentIndex(quantized); - Assert.Equal(index, quantized.GetPixelSpan()[0]); - } + int index = this.GetTransparentIndex(quantized); + Assert.Equal(index, quantized.GetPixelSpan()[0]); } } diff --git a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs index 1b0253147a..32c5586b57 100644 --- a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs +++ b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs @@ -17,15 +17,13 @@ public void SinglePixelOpaque() Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); - using (var image = new Image(config, 1, 1, Rgba32.Black)) - using (IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0])) - { - Assert.Equal(1, result.Palette.Length); - Assert.Equal(1, result.GetPixelSpan().Length); + using var image = new Image(config, 1, 1, Rgba32.Black); + using IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0]); + Assert.Equal(1, result.Palette.Length); + Assert.Equal(1, result.GetPixelSpan().Length); - Assert.Equal(Rgba32.Black, result.Palette.Span[0]); - Assert.Equal(0, result.GetPixelSpan()[0]); - } + Assert.Equal(Rgba32.Black, result.Palette.Span[0]); + Assert.Equal(0, result.GetPixelSpan()[0]); } [Fact] @@ -34,15 +32,13 @@ public void SinglePixelTransparent() Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); - using (var image = new Image(config, 1, 1, default(Rgba32))) - using (IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0])) - { - Assert.Equal(1, result.Palette.Length); - Assert.Equal(1, result.GetPixelSpan().Length); + using var image = new Image(config, 1, 1, default(Rgba32)); + using IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0]); + Assert.Equal(1, result.Palette.Length); + Assert.Equal(1, result.GetPixelSpan().Length); - Assert.Equal(default, result.Palette.Span[0]); - Assert.Equal(0, result.GetPixelSpan()[0]); - } + Assert.Equal(default, result.Palette.Span[0]); + Assert.Equal(0, result.GetPixelSpan()[0]); } [Fact] @@ -63,46 +59,42 @@ public void SinglePixelTransparent() [Fact] public void Palette256() { - using (var image = new Image(1, 256)) + using var image = new Image(1, 256); + for (int i = 0; i < 256; i++) { - for (int i = 0; i < 256; i++) - { - byte r = (byte)((i % 4) * 85); - byte g = (byte)(((i / 4) % 4) * 85); - byte b = (byte)(((i / 16) % 4) * 85); - byte a = (byte)((i / 64) * 85); + byte r = (byte)((i % 4) * 85); + byte g = (byte)(((i / 4) % 4) * 85); + byte b = (byte)(((i / 16) % 4) * 85); + byte a = (byte)((i / 64) * 85); - image[0, i] = new Rgba32(r, g, b, a); - } + image[0, i] = new Rgba32(r, g, b, a); + } - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); - using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) - using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); + using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); + using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); + Assert.Equal(256, result.Palette.Length); + Assert.Equal(256, result.GetPixelSpan().Length); + + var actualImage = new Image(1, 256); + + ReadOnlySpan paletteSpan = result.Palette.Span; + int paletteCount = result.Palette.Length - 1; + for (int y = 0; y < actualImage.Height; y++) + { + Span row = actualImage.GetPixelRowSpan(y); + ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); + int yy = y * actualImage.Width; + + for (int x = 0; x < actualImage.Width; x++) { - Assert.Equal(256, result.Palette.Length); - Assert.Equal(256, result.GetPixelSpan().Length); - - var actualImage = new Image(1, 256); - - ReadOnlySpan paletteSpan = result.Palette.Span; - int paletteCount = result.Palette.Length - 1; - for (int y = 0; y < actualImage.Height; y++) - { - Span row = actualImage.GetPixelRowSpan(y); - ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); - int yy = y * actualImage.Width; - - for (int x = 0; x < actualImage.Width; x++) - { - int i = x + yy; - row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; - } - } - - Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); + int i = x + yy; + row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; } } + + Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); } [Theory] @@ -111,63 +103,55 @@ public void LowVariance(TestImageProvider provider) where TPixel : struct, IPixel { // See https://github.com/SixLabors/ImageSharp/issues/866 - using (Image image = provider.GetImage()) - { - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); - using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) - using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) - { - Assert.Equal(48, result.Palette.Length); - } - } + using Image image = provider.GetImage(); + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); + using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); + using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); + Assert.Equal(48, result.Palette.Length); } private static void TestScale(Func pixelBuilder) { - using (var image = new Image(1, 256)) - using (var expectedImage = new Image(1, 256)) - using (var actualImage = new Image(1, 256)) + using var image = new Image(1, 256); + using var expectedImage = new Image(1, 256); + using var actualImage = new Image(1, 256); + for (int i = 0; i < 256; i++) { - for (int i = 0; i < 256; i++) - { - byte c = (byte)i; - image[0, i] = pixelBuilder.Invoke(c); - } + byte c = (byte)i; + image[0, i] = pixelBuilder.Invoke(c); + } - for (int i = 0; i < 256; i++) - { - byte c = (byte)((i & ~7) + 4); - expectedImage[0, i] = pixelBuilder.Invoke(c); - } + for (int i = 0; i < 256; i++) + { + byte c = (byte)((i & ~7) + 4); + expectedImage[0, i] = pixelBuilder.Invoke(c); + } + + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); + using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); + using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); + Assert.Equal(4 * 8, result.Palette.Length); + Assert.Equal(256, result.GetPixelSpan().Length); - using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) - using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) + ReadOnlySpan paletteSpan = result.Palette.Span; + int paletteCount = result.Palette.Length - 1; + for (int y = 0; y < actualImage.Height; y++) + { + Span row = actualImage.GetPixelRowSpan(y); + ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); + int yy = y * actualImage.Width; + + for (int x = 0; x < actualImage.Width; x++) { - Assert.Equal(4 * 8, result.Palette.Length); - Assert.Equal(256, result.GetPixelSpan().Length); - - ReadOnlySpan paletteSpan = result.Palette.Span; - int paletteCount = result.Palette.Length - 1; - for (int y = 0; y < actualImage.Height; y++) - { - Span row = actualImage.GetPixelRowSpan(y); - ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); - int yy = y * actualImage.Width; - - for (int x = 0; x < actualImage.Width; x++) - { - int i = x + yy; - row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; - } - } + int i = x + yy; + row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; } - - Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); } + + Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs similarity index 100% rename from tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs rename to tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs diff --git a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs index cce0c87126..afd66e8ce4 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs @@ -223,14 +223,10 @@ public string[] SaveTestOutputFileMultiFrame( for (int i = 0; i < image.Frames.Count; i++) { - using (Image frameImage = image.Frames.CloneFrame(i)) - { - string filePath = files[i]; - using (FileStream stream = File.OpenWrite(filePath)) - { - frameImage.Save(stream, encoder); - } - } + using Image frameImage = image.Frames.CloneFrame(i); + string filePath = files[i]; + using FileStream stream = File.OpenWrite(filePath); + frameImage.Save(stream, encoder); } return files; diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs index 58afd48a7e..413717d362 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs @@ -20,42 +20,38 @@ public class MagickReferenceDecoder : IImageDecoder public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - using (var magickImage = new MagickImage(stream)) + using var magickImage = new MagickImage(stream); + var result = new Image(configuration, magickImage.Width, magickImage.Height); + Span resultPixels = result.GetPixelSpan(); + + using IPixelCollection pixels = magickImage.GetPixelsUnsafe(); + if (magickImage.Depth == 8) + { + byte[] data = pixels.ToByteArray(PixelMapping.RGBA); + + PixelOperations.Instance.FromRgba32Bytes( + configuration, + data, + resultPixels, + resultPixels.Length); + } + else if (magickImage.Depth == 16) { - var result = new Image(configuration, magickImage.Width, magickImage.Height); - Span resultPixels = result.GetPixelSpan(); - - using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) - { - if (magickImage.Depth == 8) - { - byte[] data = pixels.ToByteArray(PixelMapping.RGBA); - - PixelOperations.Instance.FromRgba32Bytes( - configuration, - data, - resultPixels, - resultPixels.Length); - } - else if (magickImage.Depth == 16) - { - ushort[] data = pixels.ToShortArray(PixelMapping.RGBA); - Span bytes = MemoryMarshal.Cast(data.AsSpan()); - - PixelOperations.Instance.FromRgba64Bytes( - configuration, - bytes, - resultPixels, - resultPixels.Length); - } - else - { - throw new InvalidOperationException(); - } - } - - return result; + ushort[] data = pixels.ToShortArray(PixelMapping.RGBA); + Span bytes = MemoryMarshal.Cast(data.AsSpan()); + + PixelOperations.Instance.FromRgba64Bytes( + configuration, + bytes, + resultPixels, + resultPixels.Length); } + else + { + throw new InvalidOperationException(); + } + + return result; } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs index 87ec827af0..19e02399c2 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs @@ -49,22 +49,20 @@ internal static unsafe Image From32bppArgbSystemDrawingBitmap(Bi Configuration configuration = image.GetConfiguration(); - using (IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w)) + using IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(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++) - { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - - byte* sourcePtr = sourcePtrBase + (data.Stride * y); - - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); - PixelOperations.Instance.FromBgra32( - configuration, - workBuffer.GetSpan().Slice(0, w), - row); - } + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + + byte* sourcePtr = sourcePtrBase + (data.Stride * y); + + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + PixelOperations.Instance.FromBgra32( + configuration, + workBuffer.GetSpan().Slice(0, w), + row); } } } @@ -108,19 +106,17 @@ internal static unsafe Image From24bppRgbSystemDrawingBitmap(Bit Configuration configuration = image.GetConfiguration(); - using (IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w)) + using IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(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++) - { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - byte* sourcePtr = sourcePtrBase + (data.Stride * y); + byte* sourcePtr = sourcePtrBase + (data.Stride * y); - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); - PixelOperations.Instance.FromBgr24(configuration, workBuffer.GetSpan().Slice(0, w), row); - } + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + PixelOperations.Instance.FromBgr24(configuration, workBuffer.GetSpan().Slice(0, w), row); } } } @@ -149,18 +145,16 @@ internal static unsafe Bitmap To32bppArgbSystemDrawingBitmap(Image workBuffer = image.GetConfiguration().MemoryAllocator.Allocate(w)) + using IMemoryOwner workBuffer = image.GetConfiguration().MemoryAllocator.Allocate(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++) - { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - PixelOperations.Instance.ToBgra32(configuration, row, workBuffer.GetSpan()); - byte* destPtr = destPtrBase + (data.Stride * y); - - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); - } + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + PixelOperations.Instance.ToBgra32(configuration, row, workBuffer.GetSpan()); + byte* destPtr = destPtrBase + (data.Stride * y); + + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs index 286ab9caee..dcd1c2bbbf 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs @@ -16,40 +16,32 @@ public class SystemDrawingReferenceDecoder : IImageDecoder, IImageInfoDetector public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - 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(sourceBitmap); - } - - using (var convertedBitmap = new System.Drawing.Bitmap( - sourceBitmap.Width, - sourceBitmap.Height, - System.Drawing.Imaging.PixelFormat.Format32bppArgb)) - { - using (var g = System.Drawing.Graphics.FromImage(convertedBitmap)) - { - g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; - - g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height); - } - - return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(convertedBitmap); - } + return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sourceBitmap); } + + using var convertedBitmap = new System.Drawing.Bitmap( + sourceBitmap.Width, + sourceBitmap.Height, + System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using var g = System.Drawing.Graphics.FromImage(convertedBitmap); + g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + + g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height); + + return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(convertedBitmap); } public IImageInfo Identify(Configuration configuration, Stream stream) { - using (var sourceBitmap = new System.Drawing.Bitmap(stream)) - { - var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat)); - return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata()); - } + using var sourceBitmap = new System.Drawing.Bitmap(stream); + var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat)); + return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata()); } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs index 46dae17a11..bfad7414ea 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs +++ b/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. using System.Drawing.Imaging; @@ -25,10 +25,8 @@ public SystemDrawingReferenceEncoder(ImageFormat imageFormat) public void Encode(Image image, Stream stream) where TPixel : struct, IPixel { - using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image)) - { - sdBitmap.Save(stream, this.imageFormat); - } + using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image); + sdBitmap.Save(stream, this.imageFormat); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs index 585703a82b..84f8a830e8 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs @@ -287,19 +287,17 @@ public static Image CompareFirstFrameToReferenceOutput( bool appendSourceFileOrDescription = true) where TPixel : struct, IPixel { - using (var firstFrameOnlyImage = new Image(image.Width, image.Height)) - using (Image referenceImage = GetReferenceOutputImage( + using var firstFrameOnlyImage = new Image(image.Width, image.Height); + using Image referenceImage = GetReferenceOutputImage( provider, testOutputDetails, extension, appendPixelTypeToFileName, - appendSourceFileOrDescription)) - { - firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame); - firstFrameOnlyImage.Frames.RemoveFrame(0); + appendSourceFileOrDescription); + firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame); + firstFrameOnlyImage.Frames.RemoveFrame(0); - comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage); - } + comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage); return image; } @@ -405,13 +403,11 @@ public static IEnumerable GetReferenceOutputSimilarityRep bool appendPixelTypeToFileName = true) where TPixel : struct, IPixel { - using (Image referenceImage = provider.GetReferenceOutputImage( + using Image referenceImage = provider.GetReferenceOutputImage( testOutputDetails, extension, - appendPixelTypeToFileName)) - { - return comparer.CompareImages(referenceImage, image); - } + appendPixelTypeToFileName); + return comparer.CompareImages(referenceImage, image); } public static Image ComparePixelBufferTo( @@ -556,23 +552,21 @@ internal static void VerifyOperation( bool appendSourceFileOrDescription = true) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - operation(image); - - image.DebugSave( - provider, - testOutputDetails, - appendPixelTypeToFileName: appendPixelTypeToFileName, - appendSourceFileOrDescription: appendSourceFileOrDescription); - - image.CompareToReferenceOutput( - comparer, - provider, - testOutputDetails, - appendPixelTypeToFileName: appendPixelTypeToFileName, - appendSourceFileOrDescription: appendSourceFileOrDescription); - } + using Image image = provider.GetImage(); + operation(image); + + image.DebugSave( + provider, + testOutputDetails, + appendPixelTypeToFileName: appendPixelTypeToFileName, + appendSourceFileOrDescription: appendSourceFileOrDescription); + + image.CompareToReferenceOutput( + comparer, + provider, + testOutputDetails, + appendPixelTypeToFileName: appendPixelTypeToFileName, + appendSourceFileOrDescription: appendSourceFileOrDescription); } /// @@ -660,11 +654,9 @@ internal static void VerifyEncoder( referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile); - using (var actualImage = Image.Load(actualOutputFile, referenceDecoder)) - { - ImageComparer comparer = customComparer ?? ImageComparer.Exact; - comparer.VerifySimilarity(actualImage, image); - } + using var actualImage = Image.Load(actualOutputFile, referenceDecoder); + ImageComparer comparer = customComparer ?? ImageComparer.Exact; + comparer.VerifySimilarity(actualImage, image); } internal static Image ToGrayscaleImage(this Buffer2D buffer, float scale) diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs index bbebb32bdc..2b67c8d198 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs @@ -34,14 +34,10 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( int pixelThreshold) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold); - comparer.VerifySimilarity(image, clone); - } - } + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold); + comparer.VerifySimilarity(image, clone); } [Theory] @@ -49,16 +45,12 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); - var comparer = ImageComparer.Tolerant(); - comparer.VerifySimilarity(image, clone); - } - } + var comparer = ImageComparer.Tolerant(); + comparer.VerifySimilarity(image, clone); } [Theory] @@ -66,22 +58,18 @@ public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestI public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - byte perChannelChange = 20; - ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange); + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + byte perChannelChange = 20; + ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange); - var comparer = ImageComparer.Tolerant(); + var comparer = ImageComparer.Tolerant(); - ImageDifferenceIsOverThresholdException ex = Assert.ThrowsAny( - () => comparer.VerifySimilarity(image, clone)); + ImageDifferenceIsOverThresholdException ex = Assert.ThrowsAny( + () => comparer.VerifySimilarity(image, clone)); - PixelDifference diff = ex.Reports.Single().Differences.Single(); - Assert.Equal(new Point(3, 1), diff.Position); - } - } + PixelDifference diff = ex.Reports.Single().Differences.Single(); + Assert.Equal(new Point(3, 1), diff.Position); } [Theory] @@ -89,18 +77,14 @@ public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); - ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1); - ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1); - - var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3); - comparer.VerifySimilarity(image, clone); - } - } + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); + ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1); + ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1); + + var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3); + comparer.VerifySimilarity(image, clone); } [Theory] @@ -109,19 +93,15 @@ public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvide public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider provider, int w, int h) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone(ctx => ctx.Resize(w, h))) + using Image image = provider.GetImage(); + using Image clone = image.Clone(ctx => ctx.Resize(w, h)); + ImageDimensionsMismatchException ex = Assert.ThrowsAny( + () => { - ImageDimensionsMismatchException ex = Assert.ThrowsAny( - () => - { - ImageComparer comparer = Mock.Of(); - comparer.VerifySimilarity(image, clone); - }); - this.Output.WriteLine(ex.Message); - } - } + ImageComparer comparer = Mock.Of(); + comparer.VerifySimilarity(image, clone); + }); + this.Output.WriteLine(ex.Message); } [Theory] @@ -129,18 +109,14 @@ public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1); + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1); - IEnumerable reports = ImageComparer.Exact.CompareImages(image, clone); + IEnumerable reports = ImageComparer.Exact.CompareImages(image, clone); - PixelDifference difference = reports.Single().Differences.Single(); - Assert.Equal(new Point(42, 43), difference.Position); - } - } + PixelDifference difference = reports.Single().Differences.Single(); + Assert.Equal(new Point(42, 43), difference.Position); } [Theory] diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs index e9843b2b72..4d7981fb03 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs @@ -39,17 +39,15 @@ public void MagickDecode_8BitDepthImage_IsEquivalentTo_SystemDrawingResult(path, magickDecoder)) - using (var sdImage = Image.Load(path, sdDecoder)) - { - ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); + using var mImage = Image.Load(path, magickDecoder); + using var sdImage = Image.Load(path, sdDecoder); + ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); - mImage.DebugSave(dummyProvider); + mImage.DebugSave(dummyProvider); - if (TestEnvironment.IsWindows) - { - Assert.True(report.IsEmpty); - } + if (TestEnvironment.IsWindows) + { + Assert.True(report.IsEmpty); } } @@ -70,17 +68,15 @@ public void MagickDecode_16BitDepthImage_IsApproximatelyEquivalentTo_SystemDrawi // 1020 == 4 * 255 (Equivalent to manhattan distance of 1+1+1+1=4 in Rgba32 space) var comparer = ImageComparer.TolerantPercentage(1, 1020); - using (var mImage = Image.Load(path, magickDecoder)) - using (var sdImage = Image.Load(path, sdDecoder)) - { - ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); + using var mImage = Image.Load(path, magickDecoder); + using var sdImage = Image.Load(path, sdDecoder); + ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); - mImage.DebugSave(dummyProvider); + mImage.DebugSave(dummyProvider); - if (TestEnvironment.IsWindows) - { - Assert.True(report.IsEmpty); - } + if (TestEnvironment.IsWindows) + { + Assert.True(report.IsEmpty); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs index 4ca9cc4bbc..2983262153 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs @@ -26,14 +26,10 @@ public SystemDrawingReferenceCodecTests(ITestOutputHelper output) public void To32bppArgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image)) - { - string fileName = provider.Utility.GetTestOutputFileName("png"); - sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); - } - } + using Image image = provider.GetImage(); + using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image); + string fileName = provider.Utility.GetTestOutputFileName("png"); + sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); } [Theory] @@ -43,28 +39,22 @@ public void From32bppArgbSystemDrawingBitmap(TestImageProvider d { string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); - using (var sdBitmap = new System.Drawing.Bitmap(path)) - { - using (Image image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap)) - { - image.DebugSave(dummyProvider); - } - } + using var sdBitmap = new System.Drawing.Bitmap(path); + using Image image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap); + image.DebugSave(dummyProvider); } private static string SavePng(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { - using (Image sourceImage = provider.GetImage()) + using Image sourceImage = provider.GetImage(); + if (pngColorType != PngColorType.RgbWithAlpha) { - if (pngColorType != PngColorType.RgbWithAlpha) - { - sourceImage.Mutate(c => c.MakeOpaque()); - } - - var encoder = new PngEncoder { ColorType = pngColorType }; - return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder); + sourceImage.Mutate(c => c.MakeOpaque()); } + + var encoder = new PngEncoder { ColorType = pngColorType }; + return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder); } [Theory] @@ -79,15 +69,11 @@ public void From32bppArgbSystemDrawingBitmap2(TestImageProvider string path = SavePng(provider, PngColorType.RgbWithAlpha); - using (var sdBitmap = new System.Drawing.Bitmap(path)) - { - using (Image original = provider.GetImage()) - using (Image resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap)) - { - ImageComparer comparer = ImageComparer.Exact; - comparer.VerifySimilarity(original, resaved); - } - } + using var sdBitmap = new System.Drawing.Bitmap(path); + using Image original = provider.GetImage(); + using Image resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap); + ImageComparer comparer = ImageComparer.Exact; + comparer.VerifySimilarity(original, resaved); } [Theory] @@ -97,17 +83,11 @@ public void From24bppRgbSystemDrawingBitmap(TestImageProvider pr { string path = SavePng(provider, PngColorType.Rgb); - using (Image original = provider.GetImage()) - { - using (var sdBitmap = new System.Drawing.Bitmap(path)) - { - using (Image resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap(sdBitmap)) - { - ImageComparer comparer = ImageComparer.Exact; - comparer.VerifySimilarity(original, resaved); - } - } - } + using Image original = provider.GetImage(); + using var sdBitmap = new System.Drawing.Bitmap(path); + using Image resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap(sdBitmap); + ImageComparer comparer = ImageComparer.Exact; + comparer.VerifySimilarity(original, resaved); } [Theory] @@ -116,10 +96,8 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv where TPixel : struct, IPixel { string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); - using (var image = Image.Load(path, SystemDrawingReferenceDecoder.Instance)) - { - image.DebugSave(dummyProvider); - } + using var image = Image.Load(path, SystemDrawingReferenceDecoder.Instance); + image.DebugSave(dummyProvider); } [Theory] @@ -127,10 +105,8 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv public void SaveWithReferenceEncoder(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png); - } + using Image image = provider.GetImage(); + provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs index adb51e723f..e4043b4b5d 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs @@ -20,10 +20,8 @@ public void CompareToReferenceOutput_WhenReferenceOutputMatches_ShouldNotThrow provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.CompareToReferenceOutput(provider); - } + using Image image = provider.GetImage(); + image.CompareToReferenceOutput(provider); } [Theory] @@ -32,10 +30,8 @@ public void CompareToReferenceOutput_WhenReferenceOutputDoesNotMatch_Throws provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); - } + using Image image = provider.GetImage(); + Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); } [Theory] @@ -44,11 +40,9 @@ public void CompareToReferenceOutput_DoNotAppendPixelType( TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - image.DebugSave(provider, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false); - } + using Image image = provider.GetImage(); + image.DebugSave(provider, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false); } [Theory] @@ -56,10 +50,8 @@ public void CompareToReferenceOutput_DoNotAppendPixelType( public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); - } + using Image image = provider.GetImage(); + Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); } [Theory] @@ -67,13 +59,9 @@ public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws(Tes public void CompareToOriginal_WhenSimilar(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - using (Image clone = image.Clone()) - { - clone.CompareToOriginal(provider, ImageComparer.Exact); - } - } + using Image image = provider.GetImage(); + using Image clone = image.Clone(); + clone.CompareToOriginal(provider, ImageComparer.Exact); } [Theory] @@ -81,15 +69,13 @@ public void CompareToOriginal_WhenSimilar(TestImageProvider prov public void CompareToOriginal_WhenDifferent_Throws(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1); + using Image image = provider.GetImage(); + ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1); - Assert.ThrowsAny(() => - { - image.CompareToOriginal(provider, ImageComparer.Exact); - }); - } + Assert.ThrowsAny(() => + { + image.CompareToOriginal(provider, ImageComparer.Exact); + }); } [Theory] @@ -97,13 +83,11 @@ public void CompareToOriginal_WhenDifferent_Throws(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) + using Image image = provider.GetImage(); + Assert.ThrowsAny(() => { - Assert.ThrowsAny(() => - { - image.CompareToOriginal(provider, Mock.Of()); - }); - } + image.CompareToOriginal(provider, Mock.Of()); + }); } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs index 1807738692..82cf34ee04 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs @@ -179,16 +179,14 @@ public void PixelType_PropertyValueIsCorrect(TestImageProvider p public void SaveTestOutputFileMultiFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image image = provider.GetImage()) - { - string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image); + using Image image = provider.GetImage(); + string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image); - Assert.True(files.Length > 2); - foreach (string path in files) - { - this.Output.WriteLine(path); - Assert.True(File.Exists(path)); - } + Assert.True(files.Length > 2); + foreach (string path in files) + { + this.Output.WriteLine(path); + Assert.True(File.Exists(path)); } } @@ -199,10 +197,8 @@ public void SaveTestOutputFileMultiFrame(TestImageProvider provi public void Use_WithBasicTestPatternImages(TestImageProvider provider) where TPixel : struct, IPixel { - using (Image img = provider.GetImage()) - { - img.DebugSave(provider); - } + using Image img = provider.GetImage(); + img.DebugSave(provider); } [Theory] @@ -238,15 +234,13 @@ public void Use_WithFileAttribute(TestImageProvider provider, in where TPixel : struct, IPixel { Assert.NotNull(provider.Utility.SourceFileOrDescription); - using (Image img = provider.GetImage()) - { - Assert.True(img.Width * img.Height > 0); + using Image img = provider.GetImage(); + Assert.True(img.Width * img.Height > 0); - Assert.Equal(123, yo); + Assert.Equal(123, yo); - string fn = provider.Utility.GetTestOutputFileName("jpg"); - this.Output.WriteLine(fn); - } + string fn = provider.Utility.GetTestOutputFileName("jpg"); + this.Output.WriteLine(fn); } [Theory] @@ -263,10 +257,8 @@ public void Use_WithFileCollection(TestImageProvider provider) where TPixel : struct, IPixel { Assert.NotNull(provider.Utility.SourceFileOrDescription); - using (Image image = provider.GetImage()) - { - provider.Utility.SaveTestOutputFile(image, "png"); - } + using Image image = provider.GetImage(); + provider.Utility.SaveTestOutputFile(image, "png"); } [Theory] @@ -334,12 +326,10 @@ private static void EnsureCustomConfigurationIsApplied(TestImageProvider var customConfiguration = Configuration.CreateDefaultInstance(); provider.Configuration = customConfiguration; - using (Image image2 = provider.GetImage()) - using (Image image3 = provider.GetImage()) - { - Assert.Same(customConfiguration, image2.GetConfiguration()); - Assert.Same(customConfiguration, image3.GetConfiguration()); - } + using Image image2 = provider.GetImage(); + using Image image3 = provider.GetImage(); + Assert.Same(customConfiguration, image2.GetConfiguration()); + Assert.Same(customConfiguration, image3.GetConfiguration()); } } From 6c40593e0c13329a3029e7ed7fb350152102c598 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 13:09:56 +0100 Subject: [PATCH 03/15] Remove regions --- .../TestDataIcc/IccTestDataArray.cs | 24 --- .../TestDataIcc/IccTestDataCurves.cs | 26 +--- .../TestDataIcc/IccTestDataLut.cs | 24 --- .../TestDataIcc/IccTestDataMatrix.cs | 8 - .../IccTestDataMultiProcessElements.cs | 16 -- .../TestDataIcc/IccTestDataNonPrimitives.cs | 40 ----- .../TestDataIcc/IccTestDataPrimitives.cs | 56 ------- .../TestDataIcc/IccTestDataTagDataEntry.cs | 140 ------------------ 8 files changed, 2 insertions(+), 332 deletions(-) diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs index 0a039e18e8..a4d5e7c133 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs @@ -5,8 +5,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataArray { - #region Byte - public static readonly byte[] UInt8 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly object[][] UInt8TestData = @@ -14,10 +12,6 @@ internal static class IccTestDataArray new object[] { UInt8, UInt8 } }; - #endregion - - #region UInt16 - public static readonly ushort[] UInt16_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly byte[] UInt16_Arr = ArrayHelper.Concat( @@ -37,10 +31,6 @@ internal static class IccTestDataArray new object[] { UInt16_Arr, UInt16_Val } }; - #endregion - - #region Int16 - public static readonly short[] Int16_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly byte[] Int16_Arr = ArrayHelper.Concat( @@ -60,10 +50,6 @@ internal static class IccTestDataArray new object[] { Int16_Arr, Int16_Val } }; - #endregion - - #region UInt32 - public static readonly uint[] UInt32_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly byte[] UInt32_Arr = ArrayHelper.Concat( @@ -83,10 +69,6 @@ internal static class IccTestDataArray new object[] { UInt32_Arr, UInt32_Val } }; - #endregion - - #region Int32 - public static readonly int[] Int32_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly byte[] Int32_Arr = ArrayHelper.Concat( @@ -106,10 +88,6 @@ internal static class IccTestDataArray new object[] { Int32_Arr, Int32_Val } }; - #endregion - - #region UInt64 - public static readonly ulong[] UInt64_Val = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; public static readonly byte[] UInt64_Arr = ArrayHelper.Concat( @@ -128,7 +106,5 @@ internal static class IccTestDataArray { new object[] { UInt64_Arr, UInt64_Val } }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs index f679d6a324..837674e708 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataCurves.cs @@ -8,8 +8,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataCurves { - #region Response - #pragma warning disable SA1118 // Parameter should not span multiple lines /// /// Channels: 3 @@ -53,10 +51,6 @@ internal static class IccTestDataCurves new object[] { Response_Grad, Response_ValGrad, 3 }, }; - #endregion - - #region Parametric - public static readonly IccParametricCurve Parametric_ValVar1 = new IccParametricCurve(1); public static readonly IccParametricCurve Parametric_ValVar2 = new IccParametricCurve(1, 2, 3); public static readonly IccParametricCurve Parametric_ValVar3 = new IccParametricCurve(1, 2, 3, 4); @@ -127,10 +121,7 @@ internal static class IccTestDataCurves new object[] { Parametric_Var5, Parametric_ValVar5 }, }; - #endregion - - #region Formula Segment - + // Formula Segment public static readonly IccFormulaCurveElement Formula_ValVar1 = new IccFormulaCurveElement(IccFormulaCurveType.Type1, 1, 2, 3, 4, 0, 0); public static readonly IccFormulaCurveElement Formula_ValVar2 = new IccFormulaCurveElement(IccFormulaCurveType.Type2, 1, 2, 3, 4, 5, 0); public static readonly IccFormulaCurveElement Formula_ValVar3 = new IccFormulaCurveElement(IccFormulaCurveType.Type3, 0, 2, 3, 4, 5, 6); @@ -177,10 +168,7 @@ internal static class IccTestDataCurves new object[] { Formula_Var3, Formula_ValVar3 }, }; - #endregion - - #region Sampled Segment - + // Sampled Segment public static readonly IccSampledCurveElement Sampled_ValGrad1 = new IccSampledCurveElement(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); public static readonly IccSampledCurveElement Sampled_ValGrad2 = new IccSampledCurveElement(new float[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }); @@ -214,10 +202,6 @@ internal static class IccTestDataCurves new object[] { Sampled_Grad2, Sampled_ValGrad2 }, }; - #endregion - - #region Segment - public static readonly IccCurveSegment Segment_ValFormula1 = Formula_ValVar1; public static readonly IccCurveSegment Segment_ValFormula2 = Formula_ValVar2; public static readonly IccCurveSegment Segment_ValFormula3 = Formula_ValVar3; @@ -273,10 +257,6 @@ internal static class IccTestDataCurves new object[] { Segment_Sampled2, Segment_ValSampled2 }, }; - #endregion - - #region One Dimensional - public static readonly IccOneDimensionalCurve OneDimensional_ValFormula1 = new IccOneDimensionalCurve( new float[] { 0, 1 }, new IccCurveSegment[] { Segment_ValFormula1, Segment_ValFormula2, Segment_ValFormula3 }); @@ -331,7 +311,5 @@ internal static class IccTestDataCurves new object[] { OneDimensional_Formula2, OneDimensional_ValFormula2 }, new object[] { OneDimensional_Sampled, OneDimensional_ValSampled }, }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs index cc7ab7d71c..31f368cecc 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataLut.cs @@ -7,8 +7,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataLut { - #region LUT8 - public static readonly IccLut LUT8_ValGrad = CreateLUT8Val(); public static readonly byte[] LUT8_Grad = CreateLUT8(); @@ -39,10 +37,6 @@ private static byte[] CreateLUT8() new object[] { LUT8_Grad, LUT8_ValGrad }, }; - #endregion - - #region LUT16 - public static readonly IccLut LUT16_ValGrad = new IccLut(new float[] { 1f / ushort.MaxValue, @@ -76,10 +70,6 @@ private static byte[] CreateLUT8() new object[] { LUT16_Grad, LUT16_ValGrad, 11 }, }; - #endregion - - #region CLUT8 - public static readonly IccClut CLUT8_ValGrad = new IccClut( new float[][] { @@ -123,10 +113,6 @@ private static byte[] CreateLUT8() new object[] { CLUT8_Grad, CLUT8_ValGrad, 2, 3, new byte[] { 3, 3 } }, }; - #endregion - - #region CLUT16 - public static readonly IccClut CLUT16_ValGrad = new IccClut( new float[][] { @@ -170,10 +156,6 @@ private static byte[] CreateLUT8() new object[] { CLUT16_Grad, CLUT16_ValGrad, 2, 3, new byte[] { 3, 3 } }, }; - #endregion - - #region CLUTf32 - public static readonly IccClut CLUTf32_ValGrad = new IccClut( new float[][] { @@ -231,10 +213,6 @@ private static byte[] CreateLUT8() new object[] { CLUTf32_Grad, CLUTf32_ValGrad, 2, 3, new byte[] { 3, 3 } }, }; - #endregion - - #region CLUT - public static readonly IccClut CLUT_Val8 = CLUT8_ValGrad; public static readonly IccClut CLUT_Val16 = CLUT16_ValGrad; public static readonly IccClut CLUT_Valf32 = CLUTf32_ValGrad; @@ -259,7 +237,5 @@ private static byte[] CreateLUT8() new object[] { CLUT_16, CLUT_Val16, 2, 3, false }, new object[] { CLUT_f32, CLUT_Valf32, 2, 3, true }, }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs index 811150a18a..3bc787b344 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMatrix.cs @@ -9,8 +9,6 @@ namespace SixLabors.ImageSharp.Tests internal static class IccTestDataMatrix { - #region 2D - /// /// 3x3 Matrix /// @@ -114,10 +112,6 @@ internal static class IccTestDataMatrix new object[] { Single_2D_Grad, 3, 3, true, Single_Matrix4x4_ValGrad }, }; - #endregion - - #region 1D - /// /// 3x1 Matrix /// @@ -155,7 +149,5 @@ internal static class IccTestDataMatrix new object[] { Fix16_1D_Grad, 3, false, Single_Vector3_ValGrad }, new object[] { Single_1D_Grad, 3, true, Single_Vector3_ValGrad }, }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs index 32015dfd83..d7f9dd877a 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs @@ -7,8 +7,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataMultiProcessElements { - #region CurveSet - /// /// Input Channel Count: 3 /// Output Channel Count: 3 @@ -34,10 +32,6 @@ internal static class IccTestDataMultiProcessElements new object[] { CurvePE_Grad, CurvePE_ValGrad, 3, 3 }, }; - #endregion - - #region Matrix - /// /// Input Channel Count: 3 /// Output Channel Count: 3 @@ -59,10 +53,6 @@ internal static class IccTestDataMultiProcessElements new object[] { MatrixPE_Grad, MatrixPE_ValGrad, 3, 3 }, }; - #endregion - - #region CLUT - /// /// Input Channel Count: 2 /// Output Channel Count: 3 @@ -80,10 +70,6 @@ internal static class IccTestDataMultiProcessElements new object[] { CLUTPE_Grad, CLUTPE_ValGrad, 2, 3 }, }; - #endregion - - #region MultiProcessElement - public static readonly IccMultiProcessElement MPE_ValMatrix = MatrixPE_ValGrad; public static readonly IccMultiProcessElement MPE_ValCLUT = CLUTPE_ValGrad; public static readonly IccMultiProcessElement MPE_ValCurve = CurvePE_ValGrad; @@ -141,7 +127,5 @@ internal static class IccTestDataMultiProcessElements new object[] { MPE_bACS, MPE_ValbACS }, new object[] { MPE_eACS, MPE_ValeACS }, }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs index a75a04a364..91f81cb433 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataNonPrimitives.cs @@ -10,8 +10,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataNonPrimitives { - #region DateTime - public static readonly DateTime DateTime_ValMin = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static readonly DateTime DateTime_ValMax = new DateTime(9999, 12, 31, 23, 59, 59, DateTimeKind.Utc); public static readonly DateTime DateTime_ValRand1 = new DateTime(1990, 11, 26, 3, 19, 47, DateTimeKind.Utc); @@ -63,10 +61,6 @@ internal static class IccTestDataNonPrimitives new object[] { DateTime_Rand1, DateTime_ValRand1 }, }; - #endregion - - #region VersionNumber - public static readonly IccVersion VersionNumber_ValMin = new IccVersion(0, 0, 0); public static readonly IccVersion VersionNumber_Val211 = new IccVersion(2, 1, 1); public static readonly IccVersion VersionNumber_Val430 = new IccVersion(4, 3, 0); @@ -85,10 +79,6 @@ internal static class IccTestDataNonPrimitives new object[] { VersionNumber_Max, VersionNumber_ValMax }, }; - #endregion - - #region XyzNumber - public static readonly Vector3 XyzNumber_ValMin = new Vector3(IccTestDataPrimitives.Fix16_ValMin, IccTestDataPrimitives.Fix16_ValMin, IccTestDataPrimitives.Fix16_ValMin); public static readonly Vector3 XyzNumber_Val0 = new Vector3(0, 0, 0); public static readonly Vector3 XyzNumber_Val1 = new Vector3(1, 1, 1); @@ -113,10 +103,6 @@ internal static class IccTestDataNonPrimitives new object[] { XyzNumber_Max, XyzNumber_ValMax }, }; - #endregion - - #region ProfileId - public static readonly IccProfileId ProfileId_ValMin = new IccProfileId(0, 0, 0, 0); public static readonly IccProfileId ProfileId_ValRand = new IccProfileId(IccTestDataPrimitives.UInt32_ValRand1, IccTestDataPrimitives.UInt32_ValRand2, IccTestDataPrimitives.UInt32_ValRand3, IccTestDataPrimitives.UInt32_ValRand4); public static readonly IccProfileId ProfileId_ValMax = new IccProfileId(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue); @@ -132,10 +118,6 @@ internal static class IccTestDataNonPrimitives new object[] { ProfileId_Max, ProfileId_ValMax }, }; - #endregion - - #region PositionNumber - public static readonly IccPositionNumber PositionNumber_ValMin = new IccPositionNumber(0, 0); public static readonly IccPositionNumber PositionNumber_ValRand = new IccPositionNumber(IccTestDataPrimitives.UInt32_ValRand1, IccTestDataPrimitives.UInt32_ValRand2); public static readonly IccPositionNumber PositionNumber_ValMax = new IccPositionNumber(uint.MaxValue, uint.MaxValue); @@ -151,10 +133,6 @@ internal static class IccTestDataNonPrimitives new object[] { PositionNumber_Max, PositionNumber_ValMax }, }; - #endregion - - #region ResponseNumber - public static readonly IccResponseNumber ResponseNumber_ValMin = new IccResponseNumber(0, IccTestDataPrimitives.Fix16_ValMin); public static readonly IccResponseNumber ResponseNumber_Val1 = new IccResponseNumber(1, 1); public static readonly IccResponseNumber ResponseNumber_Val2 = new IccResponseNumber(2, 2); @@ -187,10 +165,6 @@ internal static class IccTestDataNonPrimitives new object[] { ResponseNumber_Max, ResponseNumber_ValMax }, }; - #endregion - - #region NamedColor - public static readonly IccNamedColor NamedColor_ValMin = new IccNamedColor( ArrayHelper.Fill('A', 31), new ushort[] { 0, 0, 0 }, @@ -243,10 +217,6 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte pCS, b new object[] { NamedColor_Max, NamedColor_ValMax, 4u }, }; - #endregion - - #region ProfileDescription - private static readonly CultureInfo CultureEnUs = new CultureInfo("en-US"); private static readonly CultureInfo CultureDeAT = new CultureInfo("de-AT"); @@ -342,10 +312,6 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte pCS, b new object[] { ProfileDescription_Rand1, ProfileDescription_ValRand1 }, }; - #endregion - - #region ColorantTableEntry - public static readonly IccColorantTableEntry ColorantTableEntry_ValRand1 = new IccColorantTableEntry(ArrayHelper.Fill('A', 31), 1, 2, 3); public static readonly IccColorantTableEntry ColorantTableEntry_ValRand2 = new IccColorantTableEntry(ArrayHelper.Fill('4', 31), 4, 5, 6); @@ -369,10 +335,6 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte pCS, b new object[] { ColorantTableEntry_Rand2, ColorantTableEntry_ValRand2 }, }; - #endregion - - #region ScreeningChannel - public static readonly IccScreeningChannel ScreeningChannel_ValRand1 = new IccScreeningChannel(4, 6, IccScreeningSpotType.Cross); public static readonly IccScreeningChannel ScreeningChannel_ValRand2 = new IccScreeningChannel(8, 5, IccScreeningSpotType.Diamond); @@ -391,7 +353,5 @@ private static byte[] CreateNamedColor(int devCoordCount, byte name, byte pCS, b new object[] { ScreeningChannel_Rand1, ScreeningChannel_ValRand1 }, new object[] { ScreeningChannel_Rand2, ScreeningChannel_ValRand2 }, }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs index f034313ace..c7b856a601 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataPrimitives.cs @@ -5,8 +5,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataPrimitives { - #region UInt16 - public static readonly byte[] UInt16_0 = { 0x00, 0x00 }; public static readonly byte[] UInt16_1 = { 0x00, 0x01 }; public static readonly byte[] UInt16_2 = { 0x00, 0x02 }; @@ -20,10 +18,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] UInt16_32768 = { 0x80, 0x00 }; public static readonly byte[] UInt16_Max = { 0xFF, 0xFF }; - #endregion - - #region Int16 - public static readonly byte[] Int16_Min = { 0x80, 0x00 }; public static readonly byte[] Int16_0 = { 0x00, 0x00 }; public static readonly byte[] Int16_1 = { 0x00, 0x01 }; @@ -37,10 +31,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] Int16_9 = { 0x00, 0x09 }; public static readonly byte[] Int16_Max = { 0x7F, 0xFF }; - #endregion - - #region UInt32 - public static readonly byte[] UInt32_0 = { 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] UInt32_1 = { 0x00, 0x00, 0x00, 0x01 }; public static readonly byte[] UInt32_2 = { 0x00, 0x00, 0x00, 0x02 }; @@ -63,10 +53,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] UInt32_Rand3 = { 0x3E, 0x97, 0x1B, 0x5E }; public static readonly byte[] UInt32_Rand4 = { 0xD3, 0x9C, 0x8F, 0x4A }; - #endregion - - #region Int32 - public static readonly byte[] Int32_Min = { 0x80, 0x00, 0x00, 0x00 }; public static readonly byte[] Int32_0 = { 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Int32_1 = { 0x00, 0x00, 0x00, 0x01 }; @@ -80,10 +66,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] Int32_9 = { 0x00, 0x00, 0x00, 0x09 }; public static readonly byte[] Int32_Max = { 0x7F, 0xFF, 0xFF, 0xFF }; - #endregion - - #region UInt64 - public static readonly byte[] UInt64_0 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] UInt64_1 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; public static readonly byte[] UInt64_2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }; @@ -96,10 +78,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] UInt64_9 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09 }; public static readonly byte[] UInt64_Max = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; - #endregion - - #region Int64 - public static readonly byte[] Int64_Min = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Int64_0 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Int64_1 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; @@ -113,10 +91,6 @@ internal static class IccTestDataPrimitives public static readonly byte[] Int64_9 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09 }; public static readonly byte[] Int64_Max = { 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; - #endregion - - #region Single - public static readonly byte[] Single_Min = { 0xFF, 0x7F, 0xFF, 0xFF }; public static readonly byte[] Single_0 = { 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Single_1 = { 0x3F, 0x80, 0x00, 0x00 }; @@ -130,19 +104,11 @@ internal static class IccTestDataPrimitives public static readonly byte[] Single_9 = { 0x41, 0x10, 0x00, 0x00 }; public static readonly byte[] Single_Max = { 0x7F, 0x7F, 0xFF, 0xFF }; - #endregion - - #region Double - public static readonly byte[] Double_Min = { 0xFF, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; public static readonly byte[] Double_0 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Double_1 = { 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; public static readonly byte[] Double_Max = { 0x7F, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; - #endregion - - #region Fix16 - public const float Fix16_ValMin = short.MinValue; public const float Fix16_ValMax = short.MaxValue + (65535f / 65536f); @@ -167,10 +133,6 @@ internal static class IccTestDataPrimitives new object[] { Fix16_Max, Fix16_ValMax }, }; - #endregion - - #region UFix16 - public const float UFix16_ValMin = 0; public const float UFix16_ValMax = ushort.MaxValue + (65535f / 65536f); @@ -193,10 +155,6 @@ internal static class IccTestDataPrimitives new object[] { UFix16_Max, UFix16_ValMax }, }; - #endregion - - #region U1Fix15 - public const float U1Fix15_ValMin = 0; public const float U1Fix15_ValMax = 1f + (32767f / 32768f); @@ -211,10 +169,6 @@ internal static class IccTestDataPrimitives new object[] { U1Fix15_Max, U1Fix15_ValMax }, }; - #endregion - - #region UFix8 - public const float UFix8_ValMin = 0; public const float UFix8_ValMax = byte.MaxValue + (255f / 256f); @@ -237,10 +191,6 @@ internal static class IccTestDataPrimitives new object[] { UFix8_Max, UFix8_ValMax }, }; - #endregion - - #region ASCII String - public const string Ascii_ValRand = "aBcdEf1234"; public const string Ascii_ValRand1 = "Ecf3a"; public const string Ascii_ValRand2 = "2Bd4c"; @@ -282,10 +232,6 @@ internal static class IccTestDataPrimitives new object[] { Ascii_RandLength4, 4, Ascii_ValRand, false }, }; - #endregion - - #region Unicode String - public const string Unicode_ValRand1 = ".6Abäñ$€β𐐷𤭢"; public const string Unicode_ValRand2 = ".6Abäñ"; public const string Unicode_ValRand3 = "$€β𐐷𤭢"; @@ -323,7 +269,5 @@ internal static class IccTestDataPrimitives 0xD8, 0x01, 0xDC, 0x37, // 𐐷 0xD8, 0x52, 0xDF, 0x62, // 𤭢 }; - - #endregion } } diff --git a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs index 37245a5dda..bfe7d94b11 100644 --- a/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs +++ b/tests/ImageSharp.Tests/TestDataIcc/IccTestDataTagDataEntry.cs @@ -9,8 +9,6 @@ namespace SixLabors.ImageSharp.Tests { internal static class IccTestDataTagDataEntry { - #region TagDataEntry Header - public static readonly IccTypeSignature TagDataEntryHeader_UnknownVal = IccTypeSignature.Unknown; public static readonly byte[] TagDataEntryHeader_UnknownArr = { @@ -39,10 +37,6 @@ internal static class IccTestDataTagDataEntry new object[] { TagDataEntryHeader_CurveArr, TagDataEntryHeader_CurveVal }, }; - #endregion - - #region UnknownTagDataEntry - public static readonly IccUnknownTagDataEntry Unknown_Val = new IccUnknownTagDataEntry(new byte[] { 0x00, 0x01, 0x02, 0x03 }); public static readonly byte[] Unknown_Arr = { 0x00, 0x01, 0x02, 0x03 }; @@ -51,10 +45,6 @@ internal static class IccTestDataTagDataEntry new object[] { Unknown_Arr, Unknown_Val, 12u }, }; - #endregion - - #region ChromaticityTagDataEntry - public static readonly IccChromaticityTagDataEntry Chromaticity_Val1 = new IccChromaticityTagDataEntry(IccColorantEncoding.ItuRBt709_2); public static readonly byte[] Chromaticity_Arr1 = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_3, @@ -101,10 +91,6 @@ internal static class IccTestDataTagDataEntry new object[] { Chromaticity_Arr2, Chromaticity_Val2 }, }; - #endregion - - #region ColorantOrderTagDataEntry - public static readonly IccColorantOrderTagDataEntry ColorantOrder_Val = new IccColorantOrderTagDataEntry(new byte[] { 0x00, 0x01, 0x02 }); public static readonly byte[] ColorantOrder_Arr = ArrayHelper.Concat(IccTestDataPrimitives.UInt32_3, new byte[] { 0x00, 0x01, 0x02 }); @@ -113,10 +99,6 @@ internal static class IccTestDataTagDataEntry new object[] { ColorantOrder_Arr, ColorantOrder_Val }, }; - #endregion - - #region ColorantTableTagDataEntry - public static readonly IccColorantTableTagDataEntry ColorantTable_Val = new IccColorantTableTagDataEntry( new IccColorantTableEntry[] { @@ -134,10 +116,6 @@ internal static class IccTestDataTagDataEntry new object[] { ColorantTable_Arr, ColorantTable_Val }, }; - #endregion - - #region CurveTagDataEntry - public static readonly IccCurveTagDataEntry Curve_Val_0 = new IccCurveTagDataEntry(); public static readonly byte[] Curve_Arr_0 = IccTestDataPrimitives.UInt32_0; @@ -160,10 +138,6 @@ internal static class IccTestDataTagDataEntry new object[] { Curve_Arr_2, Curve_Val_2 }, }; - #endregion - - #region DataTagDataEntry - public static readonly IccDataTagDataEntry Data_ValNoASCII = new IccDataTagDataEntry( new byte[] { 0x01, 0x02, 0x03, 0x04 }, false); @@ -190,10 +164,6 @@ internal static class IccTestDataTagDataEntry new object[] { Data_ArrASCII, Data_ValASCII, 17u }, }; - #endregion - - #region DateTimeTagDataEntry - public static readonly IccDateTimeTagDataEntry DateTime_Val = new IccDateTimeTagDataEntry(IccTestDataNonPrimitives.DateTime_ValRand1); public static readonly byte[] DateTime_Arr = IccTestDataNonPrimitives.DateTime_Rand1; @@ -202,10 +172,6 @@ internal static class IccTestDataTagDataEntry new object[] { DateTime_Arr, DateTime_Val }, }; - #endregion - - #region Lut16TagDataEntry - public static readonly IccLut16TagDataEntry Lut16_Val = new IccLut16TagDataEntry( new IccLut[] { IccTestDataLut.LUT16_ValGrad, IccTestDataLut.LUT16_ValGrad }, IccTestDataLut.CLUT16_ValGrad, @@ -227,10 +193,6 @@ internal static class IccTestDataTagDataEntry new object[] { Lut16_Arr, Lut16_Val }, }; - #endregion - - #region Lut8TagDataEntry - public static readonly IccLut8TagDataEntry Lut8_Val = new IccLut8TagDataEntry( new IccLut[] { IccTestDataLut.LUT8_ValGrad, IccTestDataLut.LUT8_ValGrad }, IccTestDataLut.CLUT8_ValGrad, @@ -251,10 +213,6 @@ internal static class IccTestDataTagDataEntry new object[] { Lut8_Arr, Lut8_Val }, }; - #endregion - - #region LutAToBTagDataEntry - private static readonly byte[] CurveFull_0 = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, Curve_Arr_0); @@ -324,10 +282,6 @@ internal static class IccTestDataTagDataEntry new object[] { LutAToB_Arr, LutAToB_Val }, }; - #endregion - - #region LutBToATagDataEntry - public static readonly IccLutBToATagDataEntry LutBToA_Val = new IccLutBToATagDataEntry( new[] { @@ -373,10 +327,6 @@ internal static class IccTestDataTagDataEntry new object[] { LutBToA_Arr, LutBToA_Val }, }; - #endregion - - #region MeasurementTagDataEntry - public static readonly IccMeasurementTagDataEntry Measurement_Val = new IccMeasurementTagDataEntry( IccStandardObserver.Cie1931Observer, IccTestDataNonPrimitives.XyzNumber_ValVar1, @@ -396,10 +346,6 @@ internal static class IccTestDataTagDataEntry new object[] { Measurement_Arr, Measurement_Val }, }; - #endregion - - #region MultiLocalizedUnicodeTagDataEntry - private static readonly IccLocalizedString LocalizedString_Rand_enUS = CreateLocalizedString("en", "US", IccTestDataPrimitives.Unicode_ValRand2); private static readonly IccLocalizedString LocalizedString_Rand_deDE = CreateLocalizedString("de", "DE", IccTestDataPrimitives.Unicode_ValRand3); private static readonly IccLocalizedString LocalizedString_Rand2_deDE = CreateLocalizedString("de", "DE", IccTestDataPrimitives.Unicode_ValRand2); @@ -527,10 +473,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { MultiLocalizedUnicode_Arr3, MultiLocalizedUnicode_Val3 }, }; - #endregion - - #region MultiProcessElementsTagDataEntry - public static readonly IccMultiProcessElementsTagDataEntry MultiProcessElements_Val = new IccMultiProcessElementsTagDataEntry( new IccMultiProcessElement[] { @@ -554,10 +496,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { MultiProcessElements_Arr, MultiProcessElements_Val }, }; - #endregion - - #region NamedColor2TagDataEntry - public static readonly IccNamedColor2TagDataEntry NamedColor2_Val = new IccNamedColor2TagDataEntry( 16909060, ArrayHelper.Fill('A', 31), @@ -580,10 +518,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { NamedColor2_Arr, NamedColor2_Val }, }; - #endregion - - #region ParametricCurveTagDataEntry - public static readonly IccParametricCurveTagDataEntry ParametricCurve_Val = new IccParametricCurveTagDataEntry(IccTestDataCurves.Parametric_ValVar1); public static readonly byte[] ParametricCurve_Arr = IccTestDataCurves.Parametric_Var1; @@ -592,10 +526,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { ParametricCurve_Arr, ParametricCurve_Val }, }; - #endregion - - #region ProfileSequenceDescTagDataEntry - public static readonly IccProfileSequenceDescTagDataEntry ProfileSequenceDesc_Val = new IccProfileSequenceDescTagDataEntry( new IccProfileDescription[] { @@ -613,10 +543,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { ProfileSequenceDesc_Arr, ProfileSequenceDesc_Val }, }; - #endregion - - #region ProfileSequenceIdentifierTagDataEntry - public static readonly IccProfileSequenceIdentifierTagDataEntry ProfileSequenceIdentifier_Val = new IccProfileSequenceIdentifierTagDataEntry( new IccProfileSequenceIdentifier[] { @@ -644,10 +570,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { ProfileSequenceIdentifier_Arr, ProfileSequenceIdentifier_Val }, }; - #endregion - - #region ResponseCurveSet16TagDataEntry - public static readonly IccResponseCurveSet16TagDataEntry ResponseCurveSet16_Val = new IccResponseCurveSet16TagDataEntry( new IccResponseCurve[] { @@ -668,10 +590,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { ResponseCurveSet16_Arr, ResponseCurveSet16_Val }, }; - #endregion - - #region Fix16ArrayTagDataEntry - public static readonly IccFix16ArrayTagDataEntry Fix16Array_Val = new IccFix16ArrayTagDataEntry(new float[] { 1 / 256f, 2 / 256f, 3 / 256f }); public static readonly byte[] Fix16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.Fix16_1, @@ -683,10 +601,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { Fix16Array_Arr, Fix16Array_Val, 20u }, }; - #endregion - - #region SignatureTagDataEntry - public static readonly IccSignatureTagDataEntry Signature_Val = new IccSignatureTagDataEntry("ABCD"); public static readonly byte[] Signature_Arr = { 0x41, 0x42, 0x43, 0x44, }; @@ -695,10 +609,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { Signature_Arr, Signature_Val }, }; - #endregion - - #region TextTagDataEntry - public static readonly IccTextTagDataEntry Text_Val = new IccTextTagDataEntry("ABCD"); public static readonly byte[] Text_Arr = { 0x41, 0x42, 0x43, 0x44 }; @@ -707,10 +617,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { Text_Arr, Text_Val, 12u }, }; - #endregion - - #region UFix16ArrayTagDataEntry - public static readonly IccUFix16ArrayTagDataEntry UFix16Array_Val = new IccUFix16ArrayTagDataEntry(new float[] { 1, 2, 3 }); public static readonly byte[] UFix16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UFix16_1, @@ -722,10 +628,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UFix16Array_Arr, UFix16Array_Val, 20u }, }; - #endregion - - #region UInt16ArrayTagDataEntry - public static readonly IccUInt16ArrayTagDataEntry UInt16Array_Val = new IccUInt16ArrayTagDataEntry(new ushort[] { 1, 2, 3 }); public static readonly byte[] UInt16Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt16_1, @@ -737,10 +639,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UInt16Array_Arr, UInt16Array_Val, 14u }, }; - #endregion - - #region UInt32ArrayTagDataEntry - public static readonly IccUInt32ArrayTagDataEntry UInt32Array_Val = new IccUInt32ArrayTagDataEntry(new uint[] { 1, 2, 3 }); public static readonly byte[] UInt32Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt32_1, @@ -752,10 +650,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UInt32Array_Arr, UInt32Array_Val, 20u }, }; - #endregion - - #region UInt64ArrayTagDataEntry - public static readonly IccUInt64ArrayTagDataEntry UInt64Array_Val = new IccUInt64ArrayTagDataEntry(new ulong[] { 1, 2, 3 }); public static readonly byte[] UInt64Array_Arr = ArrayHelper.Concat( IccTestDataPrimitives.UInt64_1, @@ -767,10 +661,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UInt64Array_Arr, UInt64Array_Val, 32u }, }; - #endregion - - #region UInt8ArrayTagDataEntry - public static readonly IccUInt8ArrayTagDataEntry UInt8Array_Val = new IccUInt8ArrayTagDataEntry(new byte[] { 1, 2, 3 }); public static readonly byte[] UInt8Array_Arr = { 1, 2, 3 }; @@ -779,10 +669,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UInt8Array_Arr, UInt8Array_Val, 11u }, }; - #endregion - - #region ViewingConditionsTagDataEntry - public static readonly IccViewingConditionsTagDataEntry ViewingConditions_Val = new IccViewingConditionsTagDataEntry( IccTestDataNonPrimitives.XyzNumber_ValVar1, IccTestDataNonPrimitives.XyzNumber_ValVar2, @@ -798,10 +684,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { ViewingConditions_Arr, ViewingConditions_Val }, }; - #endregion - - #region XYZTagDataEntry - public static readonly IccXyzTagDataEntry XYZ_Val = new IccXyzTagDataEntry(new Vector3[] { IccTestDataNonPrimitives.XyzNumber_ValVar1, @@ -819,10 +701,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { XYZ_Arr, XYZ_Val, 44u }, }; - #endregion - - #region TextDescriptionTagDataEntry - public static readonly IccTextDescriptionTagDataEntry TextDescription_Val1 = new IccTextDescriptionTagDataEntry( IccTestDataPrimitives.Ascii_ValRand, IccTestDataPrimitives.Unicode_ValRand1, @@ -858,10 +736,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { TextDescription_Arr2, TextDescription_Val2 }, }; - #endregion - - #region CrdInfoTagDataEntry - public static readonly IccCrdInfoTagDataEntry CrdInfo_Val = new IccCrdInfoTagDataEntry( IccTestDataPrimitives.Ascii_ValRand4, IccTestDataPrimitives.Ascii_ValRand1, @@ -891,10 +765,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { CrdInfo_Arr, CrdInfo_Val }, }; - #endregion - - #region ScreeningTagDataEntry - public static readonly IccScreeningTagDataEntry Screening_Val = new IccScreeningTagDataEntry( IccScreeningFlag.DefaultScreens | IccScreeningFlag.UnitLinesPerCm, new IccScreeningChannel[] { IccTestDataNonPrimitives.ScreeningChannel_ValRand1, IccTestDataNonPrimitives.ScreeningChannel_ValRand2 }); @@ -910,10 +780,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { Screening_Arr, Screening_Val }, }; - #endregion - - #region UcrBgTagDataEntry - public static readonly IccUcrBgTagDataEntry UcrBg_Val = new IccUcrBgTagDataEntry( new ushort[] { 3, 4, 6 }, new ushort[] { 9, 7, 2, 5 }, @@ -937,10 +803,6 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { UcrBg_Arr, UcrBg_Val, 41 }, }; - #endregion - - #region TagDataEntry - public static readonly IccTagDataEntry TagDataEntry_CurveVal = Curve_Val_2; public static readonly byte[] TagDataEntry_CurveArr = ArrayHelper.Concat( TagDataEntryHeader_CurveArr, @@ -965,7 +827,5 @@ private static IccLocalizedString CreateLocalizedString(string language, string new object[] { TagDataEntry_CurveArr, TagDataEntry_CurveVal }, new object[] { TagDataEntry_MultiLocalizedUnicodeArr, TagDataEntry_MultiLocalizedUnicodeVal }, }; - - #endregion } } From f897ab6f8da1c3efe770039dd0d9d41ad879afb3 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 13:31:51 +0100 Subject: [PATCH 04/15] Change WithTestPatternImageAttribute to WithTestPatternImagesAttribute --- .../Advanced/AdvancedImageExtensionsTests.cs | 10 ++--- .../Drawing/DrawImageTests.cs | 8 ++-- .../Formats/Bmp/BmpEncoderTests.cs | 10 ++--- .../Formats/Gif/GifEncoderTests.cs | 2 +- .../Formats/Jpg/JpegEncoderTests.cs | 12 ++--- .../Formats/Png/PngEncoderTests.cs | 44 +++++++++---------- .../Formats/Png/PngSmokeTests.cs | 4 +- .../ImageSharp.Tests/Image/ImageCloneTests.cs | 8 ++-- .../ImageFrameCollectionTests.Generic.cs | 4 +- .../ImageFrameCollectionTests.NonGeneric.cs | 4 +- .../HistogramEqualizationTests.cs | 4 +- .../Binarization/BinaryDitherTests.cs | 4 +- .../Processors/Convolution/BokehBlurTest.cs | 8 ++-- .../Processors/Convolution/DetectEdgesTest.cs | 2 +- .../Processors/Effects/OilPaintTest.cs | 2 +- .../Processors/Effects/PixelateTest.cs | 2 +- .../Processors/Filters/BlackWhiteTest.cs | 2 +- .../Processors/Filters/BrightnessTest.cs | 2 +- .../Processors/Filters/ColorBlindnessTest.cs | 2 +- .../Processors/Filters/ContrastTest.cs | 2 +- .../Processors/Filters/FilterTest.cs | 4 +- .../Processors/Filters/GrayscaleTest.cs | 2 +- .../Processing/Processors/Filters/HueTest.cs | 2 +- .../Processors/Filters/InvertTest.cs | 2 +- .../Processors/Filters/KodachromeTest.cs | 2 +- .../Processors/Filters/LightnessTest.cs | 2 +- .../Processors/Filters/LomographTest.cs | 2 +- .../Processors/Filters/OpacityTest.cs | 2 +- .../Processors/Filters/PolaroidTest.cs | 2 +- .../Processors/Filters/SaturateTest.cs | 2 +- .../Processors/Filters/SepiaTest.cs | 2 +- .../Processors/Transforms/CropTest.cs | 4 +- .../Processors/Transforms/FlipTests.cs | 10 ++--- .../Processors/Transforms/ResizeTests.cs | 40 ++++++++--------- .../Processors/Transforms/RotateFlipTests.cs | 4 +- .../Processors/Transforms/RotateTests.cs | 8 ++-- .../Processors/Transforms/SkewTests.cs | 2 +- .../Transforms/AffineTransformTests.cs | 10 ++--- .../Transforms/ProjectiveTransformTests.cs | 2 +- ...e.cs => WithTestPatternImagesAttribute.cs} | 6 +-- .../TestUtilities/Tests/ImageComparerTests.cs | 18 ++++---- .../Tests/SystemDrawingReferenceCodecTests.cs | 8 ++-- .../Tests/TestImageProviderTests.cs | 4 +- 43 files changed, 138 insertions(+), 138 deletions(-) rename tests/ImageSharp.Tests/TestUtilities/Attributes/{WithTestPatternImageAttribute.cs => WithTestPatternImagesAttribute.cs} (86%) diff --git a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs index 1dab897f30..877e3a9f8e 100644 --- a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs @@ -16,7 +16,7 @@ public class GetPixelMemory { [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void WhenMemoryIsOwned(TestImageProvider provider) where TPixel : struct, IPixel { @@ -38,7 +38,7 @@ public void WhenMemoryIsOwned(TestImageProvider provider) [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32 | PixelTypes.Bgr24)] - [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void WhenMemoryIsConsumed(TestImageProvider provider) where TPixel : struct, IPixel { @@ -64,7 +64,7 @@ public void WhenMemoryIsConsumed(TestImageProvider provider) [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void GetPixelRowMemory(TestImageProvider provider) where TPixel : struct, IPixel { @@ -87,7 +87,7 @@ public void GetPixelRowMemory(TestImageProvider provider) [Theory] [WithSolidFilledImages(1, 1, "Red", PixelTypes.Rgba32)] - [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void GetPixelRowSpan(TestImageProvider provider) where TPixel : struct, IPixel { @@ -111,7 +111,7 @@ public void GetPixelRowSpan(TestImageProvider provider) #pragma warning disable 0618 [Theory] - [WithTestPatternImage(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(131, 127, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public unsafe void DangerousGetPinnableReference_CopyToBuffer(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs index 8ee9dfc302..e1ad5a0a84 100644 --- a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs @@ -57,9 +57,9 @@ public void ImageBlendingMatchesSvgSpecExamples(TestImageProvider( } [Theory] - [WithTestPatternImage(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImages(200, 200, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void DrawImageOfDifferentPixelType(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs index 84009c4b6a..743248b5d4 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs @@ -85,16 +85,16 @@ public void Encode_PreserveBitsPerPixel(string imagePath, BmpBitsPerPixel bmpBit } [Theory] - [WithTestPatternImage(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] + [WithTestPatternImages(nameof(BitsPerPixel), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] public void Encode_IsNotBoundToSinglePixelType(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel); [Theory] - [WithTestPatternImage(nameof(BitsPerPixel), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel), 47, 8, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel), 49, 7, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel), 47, 8, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel), 49, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BitsPerPixel), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel), 7, 5, PixelTypes.Rgba32)] public void Encode_WorksWithDifferentSizes(TestImageProvider provider, BmpBitsPerPixel bitsPerPixel) where TPixel : struct, IPixel => TestBmpEncoderCore(provider, bitsPerPixel); diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs index a4a1506014..711cd89908 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs @@ -26,7 +26,7 @@ public class GifEncoderTests }; [Theory] - [WithTestPatternImage(100, 100, TestPixelTypes)] + [WithTestPatternImages(100, 100, TestPixelTypes)] public void EncodeGeneratedPatterns(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs index e54414c496..01a428b62b 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs @@ -59,17 +59,17 @@ public void Encode_PreserveQuality(string imagePath, int quality) [Theory] [WithFile(TestImages.Png.CalliphoraPartial, nameof(BitsPerPixel_Quality), PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 73, 71, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 46, 8, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 51, 7, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 73, 71, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 46, 8, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 51, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BitsPerPixel_Quality), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 7, 5, PixelTypes.Rgba32)] public void EncodeBaseline_WorksWithDifferentSizes(TestImageProvider provider, JpegSubsample subsample, int quality) where TPixel : struct, IPixel => TestJpegEncoderCore(provider, subsample, quality); [Theory] - [WithTestPatternImage(nameof(BitsPerPixel_Quality), 48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImages(nameof(BitsPerPixel_Quality), 48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void EncodeBaseline_IsNotBoundToSinglePixelType(TestImageProvider provider, JpegSubsample subsample, int quality) where TPixel : struct, IPixel => TestJpegEncoderCore(provider, subsample, quality); diff --git a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs index cd884def1c..18fba302df 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs @@ -92,11 +92,11 @@ public class PngEncoderTests [Theory] [WithFile(TestImages.Png.Palette8Bpp, nameof(PngColorTypes), PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(PngColorTypes), 48, 24, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(PngColorTypes), 47, 8, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(PngColorTypes), 49, 7, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PngColorTypes), 48, 24, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PngColorTypes), 47, 8, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PngColorTypes), 49, 7, PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(PngColorTypes), 1, 1, 255, 100, 50, 255, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(PngColorTypes), 7, 5, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PngColorTypes), 7, 5, PixelTypes.Rgba32)] public void WorksWithDifferentSizes(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { @@ -110,7 +110,7 @@ public void WorksWithDifferentSizes(TestImageProvider provider, } [Theory] - [WithTestPatternImage(nameof(PngColorTypes), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] + [WithTestPatternImages(nameof(PngColorTypes), 24, 24, PixelTypes.Rgba32 | PixelTypes.Bgra32 | PixelTypes.Rgb24)] public void IsNotBoundToSinglePixelType(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { @@ -128,7 +128,7 @@ public void IsNotBoundToSinglePixelType(TestImageProvider provid } [Theory] - [WithTestPatternImage(nameof(PngFilterMethods), 24, 24, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PngFilterMethods), 24, 24, PixelTypes.Rgba32)] public void WorksWithAllFilterMethods(TestImageProvider provider, PngFilterMethod pngFilterMethod) where TPixel : struct, IPixel { @@ -145,7 +145,7 @@ public void WorksWithAllFilterMethods(TestImageProvider provider } [Theory] - [WithTestPatternImage(nameof(CompressionLevels), 24, 24, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(CompressionLevels), 24, 24, PixelTypes.Rgba32)] public void WorksWithAllCompressionLevels(TestImageProvider provider, int compressionLevel) where TPixel : struct, IPixel { @@ -163,21 +163,21 @@ public void WorksWithAllCompressionLevels(TestImageProvider prov } [Theory] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Rgb, PngBitDepth.Bit8)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.Rgb, PngBitDepth.Bit16)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.RgbWithAlpha, PngBitDepth.Bit8)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.RgbWithAlpha, PngBitDepth.Bit16)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit1)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit2)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit4)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit8)] - [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit1)] - [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit2)] - [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit4)] - [WithTestPatternImage(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit8)] - [WithTestPatternImage(24, 24, PixelTypes.Rgb48, PngColorType.Grayscale, PngBitDepth.Bit16)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba32, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit8)] - [WithTestPatternImage(24, 24, PixelTypes.Rgba64, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit16)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Rgb, PngBitDepth.Bit8)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.Rgb, PngBitDepth.Bit16)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.RgbWithAlpha, PngBitDepth.Bit8)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.RgbWithAlpha, PngBitDepth.Bit16)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit1)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit2)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit4)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.Palette, PngBitDepth.Bit8)] + [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit1)] + [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit2)] + [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit4)] + [WithTestPatternImages(24, 24, PixelTypes.Rgb24, PngColorType.Grayscale, PngBitDepth.Bit8)] + [WithTestPatternImages(24, 24, PixelTypes.Rgb48, PngColorType.Grayscale, PngBitDepth.Bit16)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba32, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit8)] + [WithTestPatternImages(24, 24, PixelTypes.Rgba64, PngColorType.GrayscaleWithAlpha, PngBitDepth.Bit16)] public void WorksWithAllBitDepths(TestImageProvider provider, PngColorType pngColorType, PngBitDepth pngBitDepth) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs index a2842964de..645ee08bf5 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Png public class PngSmokeTests { [Theory] - [WithTestPatternImage(300, 300, PixelTypes.Rgba32)] + [WithTestPatternImages(300, 300, PixelTypes.Rgba32)] public void GeneralTest(TestImageProvider provider) where TPixel : struct, IPixel { @@ -95,7 +95,7 @@ public void CanSaveIndexedPngTwice(TestImageProvider provider) }*/ [Theory] - [WithTestPatternImage(300, 300, PixelTypes.Rgba32)] + [WithTestPatternImages(300, 300, PixelTypes.Rgba32)] public void Resize(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs index ccaee3d108..fb3fdf2b0b 100644 --- a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs @@ -29,7 +29,7 @@ public void Clone_WhenDisposed_Throws() } [Theory] - [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgra32(TestImageProvider provider) { using Image image = provider.GetImage(); @@ -53,7 +53,7 @@ public void CloneAs_ToBgra32(TestImageProvider provider) } [Theory] - [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgr24(TestImageProvider provider) { using Image image = provider.GetImage(); @@ -76,7 +76,7 @@ public void CloneAs_ToBgr24(TestImageProvider provider) } [Theory] - [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToArgb32(TestImageProvider provider) { using Image image = provider.GetImage(); @@ -100,7 +100,7 @@ public void CloneAs_ToArgb32(TestImageProvider provider) } [Theory] - [WithTestPatternImage(9, 9, PixelTypes.Rgba32)] + [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToRgb24(TestImageProvider provider) { using Image image = provider.GetImage(); diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs index 644fa40649..0ead18c765 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs @@ -188,7 +188,7 @@ public void Dispose_DisposesAllInnerFrames() } [Theory] - [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { @@ -200,7 +200,7 @@ public void CloneFrame(TestImageProvider provider) } [Theory] - [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs index 754804cf2a..92945f6f50 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs @@ -144,7 +144,7 @@ public void RootFrameIsFrameAtIndexZero() } [Theory] - [WithTestPatternImage(10, 10, PixelTypes.Rgba32 | PixelTypes.Bgr24)] + [WithTestPatternImages(10, 10, PixelTypes.Rgba32 | PixelTypes.Bgr24)] public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { @@ -161,7 +161,7 @@ public void CloneFrame(TestImageProvider provider) } [Theory] - [WithTestPatternImage(10, 10, PixelTypes.Rgba32)] + [WithTestPatternImages(10, 10, PixelTypes.Rgba32)] public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs index 4802b26c61..d543d03934 100644 --- a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs +++ b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs @@ -116,8 +116,8 @@ public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImagePro /// /// The pixel type of the image. [Theory] - [WithTestPatternImage(110, 110, PixelTypes.Rgb24)] - [WithTestPatternImage(170, 170, PixelTypes.Rgb24)] + [WithTestPatternImages(110, 110, PixelTypes.Rgb24)] + [WithTestPatternImages(170, 170, PixelTypes.Rgb24)] public void Issue984(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs index adb7f6c66e..4f69e55b6f 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs @@ -47,7 +47,7 @@ public class BinaryDitherTests [Theory] [WithFileCollection(nameof(CommonTestImages), nameof(OrderedDitherers), PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(OrderedDitherers), 100, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(OrderedDitherers), 100, 100, PixelTypes.Rgba32)] public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider provider, string name, IOrderedDither ditherer) where TPixel : struct, IPixel { @@ -58,7 +58,7 @@ public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider(TestImageProvider provider, string name, IErrorDiffuser diffuser) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs index 67aeabddd4..44120684de 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs @@ -114,9 +114,9 @@ public void Serialize(IXunitSerializationInfo info) [Theory] [WithFileCollection(nameof(TestFiles), nameof(BokehBlurValues), PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BokehBlurValues), 50, 50, "Red", PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BokehBlurValues), 200, 100, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BokehBlurValues), 23, 31, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(BokehBlurValues), 30, 20, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BokehBlurValues), 200, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BokehBlurValues), 23, 31, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BokehBlurValues), 30, 20, PixelTypes.Rgba32)] public void BokehBlurFilterProcessor(TestImageProvider provider, BokehBlurInfo value) where TPixel : struct, IPixel { @@ -131,7 +131,7 @@ public void BokehBlurFilterProcessor(TestImageProvider provider, TODO: Re-enable L8 when we update the reference images. [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32 | PixelTypes.L8)] */ - [WithTestPatternImage(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32)] + [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32)] public void BokehBlurFilterProcessor_WorksWithAllPixelTypes(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs index 44f8b18441..80cd4158c9 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs @@ -51,7 +51,7 @@ public void DetectEdges_WorksOnWrappedMemoryImage(TestImageProvider(TestImageProvider provider, EdgeDetectionOperators detector) where TPixel : struct, IPixel diff --git a/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs index 579663cf44..8b03106da4 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Effects/OilPaintTest.cs @@ -36,7 +36,7 @@ public void FullImage(TestImageProvider provider, int levels, in [Theory] [WithFileCollection(nameof(InputImages), nameof(OilPaintValues), PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(OilPaintValues), 100, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(OilPaintValues), 100, 100, PixelTypes.Rgba32)] public void InBox(TestImageProvider provider, int levels, int brushSize) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs index d4e4d749b6..e95452ffb7 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Effects/PixelateTest.cs @@ -22,7 +22,7 @@ public void FullImage(TestImageProvider provider, int value) } [Theory] - [WithTestPatternImage(nameof(PixelateValues), 320, 240, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(PixelateValues), 320, 240, PixelTypes.Rgba32)] [WithFile(TestImages.Png.CalliphoraPartial, nameof(PixelateValues), PixelTypes.Rgba32)] public void InBox(TestImageProvider provider, int value) where TPixel : struct, IPixel diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs index 4cf4e5144a..64aeae0534 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/BlackWhiteTest.cs @@ -14,7 +14,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class BlackWhiteTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyBlackWhiteFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs index 8434ce7d7a..4ad6015838 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/BrightnessTest.cs @@ -23,7 +23,7 @@ public static readonly TheoryData BrightnessValues }; [Theory] - [WithTestPatternImage(nameof(BrightnessValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(BrightnessValues), 48, 48, PixelTypes.Rgba32)] public void ApplyBrightnessFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(ctx => ctx.Brightness(value), value, this.imageComparer); } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs index b075e73d3c..8ac56655ea 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/ColorBlindnessTest.cs @@ -29,7 +29,7 @@ public static readonly TheoryData ColorBlindnessFilters }; [Theory] - [WithTestPatternImage(nameof(ColorBlindnessFilters), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(ColorBlindnessFilters), 48, 48, PixelTypes.Rgba32)] public void ApplyColorBlindnessFilter(TestImageProvider provider, ColorBlindnessMode colorBlindness) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(x => x.ColorBlindness(colorBlindness), colorBlindness.ToString(), this.imageComparer); } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs index 3c734769de..d822def919 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/ContrastTest.cs @@ -20,7 +20,7 @@ public static readonly TheoryData ContrastValues }; [Theory] - [WithTestPatternImage(nameof(ContrastValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(ContrastValues), 48, 48, PixelTypes.Rgba32)] public void ApplyContrastFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs index 3e9e998834..a6d7ba4511 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/FilterTest.cs @@ -18,7 +18,7 @@ public class FilterTest // Testing the generic FilterProcessor with more than one pixel type intentionally. // There is no need to do this with the specialized ones. [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void ApplyFilter(TestImageProvider provider) where TPixel : struct, IPixel { @@ -28,7 +28,7 @@ public void ApplyFilter(TestImageProvider provider) } [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs index e8535bc836..32fc47a80c 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/GrayscaleTest.cs @@ -24,7 +24,7 @@ public static readonly TheoryData GrayscaleModeTypes /// /// The pixel type of the image. [Theory] - [WithTestPatternImage(nameof(GrayscaleModeTypes), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(GrayscaleModeTypes), 48, 48, PixelTypes.Rgba32)] public void ApplyGrayscaleFilter(TestImageProvider provider, GrayscaleMode value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs index b99ae38d5d..0ede3cef8e 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/HueTest.cs @@ -20,7 +20,7 @@ public static readonly TheoryData HueValues }; [Theory] - [WithTestPatternImage(nameof(HueValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(HueValues), 48, 48, PixelTypes.Rgba32)] public void ApplyHueFilter(TestImageProvider provider, int value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs index 4889a1a630..1b4c70646a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/InvertTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Effects public class InvertTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyInvertFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs index 4d6f163298..b7b635c2d2 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/KodachromeTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class KodachromeTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyKodachromeFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs index 39b1aa1c1f..8934816acc 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/LightnessTest.cs @@ -23,7 +23,7 @@ public static readonly TheoryData LightnessValues }; [Theory] - [WithTestPatternImage(nameof(LightnessValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(LightnessValues), 48, 48, PixelTypes.Rgba32)] public void ApplyLightnessFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel => provider.RunValidatingProcessorTest(ctx => ctx.Lightness(value), value, this.imageComparer); } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs index e366a86aad..013ec38740 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/LomographTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class LomographTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyLomographFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs index 7e6bf49c58..dfc67324c5 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/OpacityTest.cs @@ -20,7 +20,7 @@ public static readonly TheoryData AlphaValues }; [Theory] - [WithTestPatternImage(nameof(AlphaValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(AlphaValues), 48, 48, PixelTypes.Rgba32)] public void ApplyAlphaFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs index 6ac3009ad1..3b39542a55 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/PolaroidTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class PolaroidTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplyPolaroidFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs index 943f432a8c..17ffc80de4 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/SaturateTest.cs @@ -20,7 +20,7 @@ public static readonly TheoryData SaturationValues }; [Theory] - [WithTestPatternImage(nameof(SaturationValues), 48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(SaturationValues), 48, 48, PixelTypes.Rgba32)] public void ApplySaturationFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs index 7c88859138..b7d381f5f2 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Filters/SepiaTest.cs @@ -13,7 +13,7 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Filters public class SepiaTest { [Theory] - [WithTestPatternImage(48, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(48, 48, PixelTypes.Rgba32)] public void ApplySepiaFilter(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/CropTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/CropTest.cs index 7ddb028cf4..b49ac3ea9a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/CropTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/CropTest.cs @@ -15,8 +15,8 @@ namespace SixLabors.ImageSharp.Tests.Processing.Processors.Transforms public class CropTest { [Theory] - [WithTestPatternImage(70, 30, PixelTypes.Rgba32, 0, 0, 70, 30)] - [WithTestPatternImage(30, 70, PixelTypes.Rgba32, 7, 13, 20, 50)] + [WithTestPatternImages(70, 30, PixelTypes.Rgba32, 0, 0, 70, 30)] + [WithTestPatternImages(30, 70, PixelTypes.Rgba32, 7, 13, 20, 50)] public void Crop(TestImageProvider provider, int x, int y, int w, int h) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs index c82ca891fc..d1208d955f 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/FlipTests.cs @@ -21,9 +21,9 @@ public class FlipTests }; [Theory] - [WithTestPatternImage(nameof(FlipValues), 20, 37, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(FlipValues), 20, 37, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] public void Flip(TestImageProvider provider, FlipMode flipMode) where TPixel : struct, IPixel { @@ -34,8 +34,8 @@ public void Flip(TestImageProvider provider, FlipMode flipMode) } [Theory] - [WithTestPatternImage(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(FlipValues), 53, 37, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(FlipValues), 17, 32, PixelTypes.Rgba32)] public void Flip_WorksOnWrappedMemoryImage(TestImageProvider provider, FlipMode flipMode) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs index d557f7c6c1..4e5ffbfab2 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs @@ -54,9 +54,9 @@ public void Resize_PixelAgnostic() } [Theory(Skip = "Debug only, enable manually")] - [WithTestPatternImage(4000, 4000, PixelTypes.Rgba32, 300, 1024)] - [WithTestPatternImage(3032, 3032, PixelTypes.Rgba32, 400, 1024)] - [WithTestPatternImage(3032, 3032, PixelTypes.Rgba32, 400, 128)] + [WithTestPatternImages(4000, 4000, PixelTypes.Rgba32, 300, 1024)] + [WithTestPatternImages(3032, 3032, PixelTypes.Rgba32, 400, 1024)] + [WithTestPatternImages(3032, 3032, PixelTypes.Rgba32, 400, 128)] public void LargeImage(TestImageProvider provider, int destSize, int workingBufferSizeHintInKilobytes) where TPixel : struct, IPixel { @@ -94,13 +94,13 @@ public void Resize_BasicSmall(TestImageProvider provider, int wN private static readonly int SizeOfVector4 = Unsafe.SizeOf(); [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 50)] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 60)] - [WithTestPatternImage(100, 400, PixelTypes.Rgba32, 110)] - [WithTestPatternImage(79, 97, PixelTypes.Rgba32, 73)] - [WithTestPatternImage(79, 97, PixelTypes.Rgba32, 5)] - [WithTestPatternImage(47, 193, PixelTypes.Rgba32, 73)] - [WithTestPatternImage(23, 211, PixelTypes.Rgba32, 31)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 50)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 60)] + [WithTestPatternImages(100, 400, PixelTypes.Rgba32, 110)] + [WithTestPatternImages(79, 97, PixelTypes.Rgba32, 73)] + [WithTestPatternImages(79, 97, PixelTypes.Rgba32, 5)] + [WithTestPatternImages(47, 193, PixelTypes.Rgba32, 73)] + [WithTestPatternImages(23, 211, PixelTypes.Rgba32, 31)] public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( TestImageProvider provider, int workingBufferLimitInRows) @@ -146,7 +146,7 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( } [Theory] - [WithTestPatternImage(100, 100, DefaultPixelType)] + [WithTestPatternImages(100, 100, DefaultPixelType)] public void Resize_Compand(TestImageProvider provider) where TPixel : struct, IPixel { @@ -185,7 +185,7 @@ public void Resize_IsAppliedToAllFrames(TestImageProvider provid } [Theory] - [WithTestPatternImage(50, 50, CommonNonDefaultPixelTypes)] + [WithTestPatternImages(50, 50, CommonNonDefaultPixelTypes)] public void Resize_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { @@ -243,12 +243,12 @@ public void Resize_WorksWithAllParallelismLevels( 1.8f, null, null)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 0.5f, null, null)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 1f, null, null)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 50, 50, DefaultPixelType, 8f, null, null)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 201, 199, DefaultPixelType, null, 100, 99)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 301, 1180, DefaultPixelType, null, 300, 480)] - [WithTestPatternImage(nameof(SmokeTestResamplerNames), 49, 80, DefaultPixelType, null, 301, 100)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 0.5f, null, null)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 100, 100, DefaultPixelType, 1f, null, null)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 50, 50, DefaultPixelType, 8f, null, null)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 201, 199, DefaultPixelType, null, 100, 99)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 301, 1180, DefaultPixelType, null, 300, 480)] + [WithTestPatternImages(nameof(SmokeTestResamplerNames), 49, 80, DefaultPixelType, null, 301, 100)] public void Resize_WorksWithAllResamplers( TestImageProvider provider, string samplerName, @@ -343,7 +343,7 @@ public void ResizeHeightAndKeepAspect(TestImageProvider provider } [Theory] - [WithTestPatternImage(10, 100, DefaultPixelType)] + [WithTestPatternImages(10, 100, DefaultPixelType)] public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { @@ -366,7 +366,7 @@ public void ResizeWidthAndKeepAspect(TestImageProvider provider) } [Theory] - [WithTestPatternImage(100, 10, DefaultPixelType)] + [WithTestPatternImages(100, 10, DefaultPixelType)] public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs index 0dd2ff5ef8..a1c03a3d3b 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs @@ -24,8 +24,8 @@ public static readonly TheoryData RotateFlipValues }; [Theory] - [WithTestPatternImage(nameof(RotateFlipValues), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(RotateFlipValues), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateFlipValues), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateFlipValues), 50, 100, PixelTypes.Rgba32)] public void RotateFlip(TestImageProvider provider, RotateMode rotateType, FlipMode flipType) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs index 72619f2dc9..7801c71432 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateTests.cs @@ -26,8 +26,8 @@ public static readonly TheoryData RotateEnumValues }; [Theory] - [WithTestPatternImage(nameof(RotateAngles), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(RotateAngles), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateAngles), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateAngles), 50, 100, PixelTypes.Rgba32)] public void Rotate_WithAngle(TestImageProvider provider, float value) where TPixel : struct, IPixel { @@ -35,8 +35,8 @@ public void Rotate_WithAngle(TestImageProvider provider, float v } [Theory] - [WithTestPatternImage(nameof(RotateEnumValues), 100, 50, PixelTypes.Rgba32)] - [WithTestPatternImage(nameof(RotateEnumValues), 50, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateEnumValues), 100, 50, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(RotateEnumValues), 50, 100, PixelTypes.Rgba32)] public void Rotate_WithRotateTypeEnum(TestImageProvider provider, RotateMode value) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs index 631cb84246..ad77027f0f 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/SkewTests.cs @@ -43,7 +43,7 @@ public class SkewTests private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.01f); [Theory] - [WithTestPatternImage(nameof(SkewValues), 100, 50, CommonPixelTypes)] + [WithTestPatternImages(nameof(SkewValues), 100, 50, CommonPixelTypes)] public void Skew_IsNotBoundToSinglePixelType(TestImageProvider provider, float x, float y) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs index cbc23dfcd9..016a77fd0c 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs @@ -91,7 +91,7 @@ public void Transform_DoesNotCreateEdgeArtifacts(TestImageProvider( TestImageProvider provider, float angleDeg, @@ -118,7 +118,7 @@ public void Transform_RotateScaleTranslate( } [Theory] - [WithTestPatternImage(96, 96, PixelTypes.Rgba32, 50, 0.8f)] + [WithTestPatternImages(96, 96, PixelTypes.Rgba32, 50, 0.8f)] public void Transform_RotateScale_ManuallyCentered(TestImageProvider provider, float angleDeg, float s) where TPixel : struct, IPixel { @@ -150,7 +150,7 @@ public void Transform_RotateScale_ManuallyCentered(TestImageProvider /// The pixel type of the image. [Theory] - [WithTestPatternImage(96, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(96, 48, PixelTypes.Rgba32)] public void Transform_FromSourceRectangle1(TestImageProvider provider) where TPixel : struct, IPixel { @@ -168,7 +168,7 @@ public void Transform_FromSourceRectangle1(TestImageProvider pro } [Theory] - [WithTestPatternImage(96, 48, PixelTypes.Rgba32)] + [WithTestPatternImages(96, 48, PixelTypes.Rgba32)] public void Transform_FromSourceRectangle2(TestImageProvider provider) where TPixel : struct, IPixel { @@ -185,7 +185,7 @@ public void Transform_FromSourceRectangle2(TestImageProvider pro } [Theory] - [WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] public void Transform_WithSampler(TestImageProvider provider, string resamplerName) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs index 65be7d3721..8b0cc02b1f 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs @@ -59,7 +59,7 @@ public class ProjectiveTransformTests public ProjectiveTransformTests(ITestOutputHelper output) => this.Output = output; [Theory] - [WithTestPatternImage(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] + [WithTestPatternImages(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)] public void Transform_WithSampler(TestImageProvider provider, string resamplerName) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImagesAttribute.cs similarity index 86% rename from tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs rename to tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImagesAttribute.cs index e4a9b2bdd1..7c659c64fc 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImageAttribute.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Attributes/WithTestPatternImagesAttribute.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.Tests /// Triggers passing instances which produce a blank image of size width * height. /// One instance will be passed for each the pixel format defined by the pixelTypes parameter /// - public class WithTestPatternImageAttribute : ImageDataAttributeBase + public class WithTestPatternImagesAttribute : ImageDataAttributeBase { /// /// Triggers passing an that produces a test pattern image of size width * height @@ -19,7 +19,7 @@ public class WithTestPatternImageAttribute : ImageDataAttributeBase /// The required height /// The requested parameter /// Additional theory parameter values - public WithTestPatternImageAttribute(int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) + public WithTestPatternImagesAttribute(int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) : this(null, width, height, pixelTypes, additionalParameters) { } @@ -32,7 +32,7 @@ public WithTestPatternImageAttribute(int width, int height, PixelTypes pixelType /// The required height /// The requested parameter /// Additional theory parameter values - public WithTestPatternImageAttribute(string memberData, int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) + public WithTestPatternImagesAttribute(string memberData, int width, int height, PixelTypes pixelTypes, params object[] additionalParameters) : base(memberData, pixelTypes, additionalParameters) { this.Width = width; diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs index 8c18e16bb9..de7b5f84a5 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs @@ -25,8 +25,8 @@ public ImageComparerTests(ITestOutputHelper output) private ITestOutputHelper Output { get; } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 0.0001f, 1)] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 0, 0)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 0.0001f, 1)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 0, 0)] public void TolerantImageComparer_ApprovesPerfectSimilarity( TestImageProvider provider, float imageThreshold, @@ -40,7 +40,7 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( } [Theory] - [WithTestPatternImage(110, 110, PixelTypes.Rgba32)] + [WithTestPatternImages(110, 110, PixelTypes.Rgba32)] public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestImageProvider provider) where TPixel : struct, IPixel { @@ -53,7 +53,7 @@ public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestI } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance(TestImageProvider provider) where TPixel : struct, IPixel { @@ -72,7 +72,7 @@ public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba64)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba64)] public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvider provider) where TPixel : struct, IPixel { @@ -87,8 +87,8 @@ public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvide } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 99, 100)] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32, 100, 99)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 99, 100)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32, 100, 99)] public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider provider, int w, int h) where TPixel : struct, IPixel { @@ -119,7 +119,7 @@ public void VerifySimilarity_WhenAnImageFrameIsDifferent_Reports(TestIma } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] public void ExactComparer_ApprovesExactEquality(TestImageProvider provider) where TPixel : struct, IPixel { @@ -133,7 +133,7 @@ public void ExactComparer_ApprovesExactEquality(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs index 2983262153..98f02f6ebd 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs @@ -22,7 +22,7 @@ public SystemDrawingReferenceCodecTests(ITestOutputHelper output) } [Theory] - [WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Bgra32)] + [WithTestPatternImages(20, 20, PixelTypes.Rgba32 | PixelTypes.Bgra32)] public void To32bppArgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { @@ -58,7 +58,7 @@ private static string SavePng(TestImageProvider provider, PngCol } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgba32)] + [WithTestPatternImages(100, 100, PixelTypes.Rgba32)] public void From32bppArgbSystemDrawingBitmap2(TestImageProvider provider) where TPixel : struct, IPixel { @@ -77,7 +77,7 @@ public void From32bppArgbSystemDrawingBitmap2(TestImageProvider } [Theory] - [WithTestPatternImage(100, 100, PixelTypes.Rgb24)] + [WithTestPatternImages(100, 100, PixelTypes.Rgb24)] public void From24bppRgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { @@ -101,7 +101,7 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv } [Theory] - [WithTestPatternImage(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)] + [WithTestPatternImages(20, 20, PixelTypes.Rgba32 | PixelTypes.Argb32)] public void SaveWithReferenceEncoder(TestImageProvider provider) where TPixel : struct, IPixel { diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs index 82cf34ee04..a33b0750b1 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs @@ -300,7 +300,7 @@ public void Use_WithSolidFilledImagesAttribute(TestImageProvider } [Theory] - [WithTestPatternImage(49, 20, PixelTypes.Rgba32)] + [WithTestPatternImages(49, 20, PixelTypes.Rgba32)] public void Use_WithTestPatternImages(TestImageProvider provider) where TPixel : struct, IPixel { @@ -311,7 +311,7 @@ public void Use_WithTestPatternImages(TestImageProvider provider } [Theory] - [WithTestPatternImage(20, 20, PixelTypes.Rgba32)] + [WithTestPatternImages(20, 20, PixelTypes.Rgba32)] public void Use_WithTestPatternImages_CustomConfiguration(TestImageProvider provider) where TPixel : struct, IPixel { From 94dc54b4144394f125673066487c0e5a18036a04 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 14:21:58 +0100 Subject: [PATCH 05/15] Rename method names again to be the same as in the reference implementation --- .../ReferenceImplementations.AccurateDCT.cs | 2 +- ...ceImplementations.LLM_FloatingPoint_DCT.cs | 140 ++++++++---------- 2 files changed, 64 insertions(+), 78 deletions(-) diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs index 23e047bd85..fc0540c64a 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.AccurateDCT.cs @@ -113,7 +113,7 @@ public static Block8x8F TransformFDCT(ref Block8x8F block) private static double[,] InitCosLut() { - var coslu = new double[8, 8]; + double[,] coslu = new double[8, 8]; int a, b; double tmp; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs index 82f0080c06..b3dafdbb89 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/ReferenceImplementations.LLM_FloatingPoint_DCT.cs @@ -168,23 +168,23 @@ internal static void IDCT2D_llm(Span s, Span d, Span temp) /// Destination public static void FDCT2D8x4_32f(Span s, Span d) { - Vector4 c0 = Mm_load_ps(s, 0); - Vector4 c1 = Mm_load_ps(s, 56); + Vector4 c0 = _mm_load_ps(s, 0); + Vector4 c1 = _mm_load_ps(s, 56); Vector4 t0 = c0 + c1; Vector4 t7 = c0 - c1; - c1 = Mm_load_ps(s, 48); - c0 = Mm_load_ps(s, 8); + c1 = _mm_load_ps(s, 48); + c0 = _mm_load_ps(s, 8); Vector4 t1 = c0 + c1; Vector4 t6 = c0 - c1; - c1 = Mm_load_ps(s, 40); - c0 = Mm_load_ps(s, 16); + c1 = _mm_load_ps(s, 40); + c0 = _mm_load_ps(s, 16); Vector4 t2 = c0 + c1; Vector4 t5 = c0 - c1; - c0 = Mm_load_ps(s, 24); - c1 = Mm_load_ps(s, 32); + c0 = _mm_load_ps(s, 24); + c1 = _mm_load_ps(s, 32); Vector4 t3 = c0 + c1; Vector4 t4 = c0 - c1; @@ -205,9 +205,9 @@ public static void FDCT2D8x4_32f(Span s, Span d) c1 = t1 + t2; c2 = t1 - t2; */ - Mm_store_ps(d, 0, c0 + c1); + _mm_store_ps(d, 0, c0 + c1); - Mm_store_ps(d, 32, c0 - c1); + _mm_store_ps(d, 32, c0 - c1); /*y[0] = c0 + c1; y[4] = c0 - c1;*/ @@ -215,9 +215,9 @@ public static void FDCT2D8x4_32f(Span s, Span d) var w0 = new Vector4(0.541196f); var w1 = new Vector4(1.306563f); - Mm_store_ps(d, 16, (w0 * c2) + (w1 * c3)); + _mm_store_ps(d, 16, (w0 * c2) + (w1 * c3)); - Mm_store_ps(d, 48, (w0 * c3) - (w1 * c2)); + _mm_store_ps(d, 48, (w0 * c3) - (w1 * c2)); /* y[2] = c2 * r[6] + c3 * r[2]; y[6] = c3 * r[6] - c2 * r[2]; @@ -241,23 +241,22 @@ public static void FDCT2D8x4_32f(Span s, Span d) c1 = t6 * r[1] - t5 * r[7]; */ - Mm_store_ps(d, 24, c0 - c2); + _mm_store_ps(d, 24, c0 - c2); - Mm_store_ps(d, 40, c3 - c1); + _mm_store_ps(d, 40, c3 - c1); // y[5] = c3 - c1; y[3] = c0 - c2; var invsqrt2 = new Vector4(0.707107f); c0 = (c0 + c2) * invsqrt2; c3 = (c3 + c1) * invsqrt2; - /* c0 = (c0 + c2) * invsqrt2; - c3 = (c3 + c1) * invsqrt2; */ - Mm_store_ps(d, 8, c0 + c3); + // c0 = (c0 + c2) * invsqrt2; + // c3 = (c3 + c1) * invsqrt2; + _mm_store_ps(d, 8, c0 + c3); + _mm_store_ps(d, 56, c0 - c3); - Mm_store_ps(d, 56, c0 - c3); - /* y[1] = c0 + c3; y[7] = c0 - c3; - - for(i = 0;i < 8;i++) + // y[1] = c0 + c3; y[7] = c0 - c3; + /*for(i = 0;i < 8;i++) { y[i] *= invsqrt2h; }*/ @@ -279,49 +278,39 @@ public static void FDCT8x8_llm_sse(Span s, Span d, Span tem var c = new Vector4(0.1250f); - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 0 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 1 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 2 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 3 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 4 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 5 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 6 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 7 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 8 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 9 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 10 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 11 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 12 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 13 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 14 - Mm_store_ps(d, 0, Mm_load_ps(d, 0) * c); - d = d.Slice(4); // 15 +#pragma warning disable SA1107 // Code should not contain multiple statements on one line + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 0 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 1 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 2 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 3 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 4 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 5 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 6 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 7 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 8 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 9 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 10 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 11 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 12 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 13 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 14 + _mm_store_ps(d, 0, _mm_load_ps(d, 0) * c); d = d.Slice(4); // 15 +#pragma warning restore SA1107 // Code should not contain multiple statements on one line } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static Vector4 Mm_load_ps(Span src, int offset) +#pragma warning disable SA1300 // Element should begin with upper-case letter + private static Vector4 _mm_load_ps(Span src, int offset) +#pragma warning restore SA1300 // Element should begin with upper-case letter { src = src.Slice(offset); return new Vector4(src[0], src[1], src[2], src[3]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Mm_store_ps(Span dest, int offset, Vector4 src) +#pragma warning disable SA1300 // Element should begin with upper-case letter + private static void _mm_store_ps(Span dest, int offset, Vector4 src) +#pragma warning restore SA1300 // Element should begin with upper-case letter { dest = dest.Slice(offset); dest[0] = src.X; @@ -369,7 +358,6 @@ internal static void IDCT2D8x4_32f(Span y, Span x) float a0,a1,a2,a3,b0,b1,b2,b3; float z0,z1,z2,z3,z4; float r[8]; int i; for(i = 0;i < 8;i++){ r[i] = (float)(cos((double)i / 16.0 * M_PI) * M_SQRT2); } */ - /* 0: 1.414214 1: 1.387040 @@ -381,20 +369,20 @@ internal static void IDCT2D8x4_32f(Span y, Span x) 7: 0.275899 */ - Vector4 my1 = Mm_load_ps(y, 8); - Vector4 my7 = Mm_load_ps(y, 56); + Vector4 my1 = _mm_load_ps(y, 8); + Vector4 my7 = _mm_load_ps(y, 56); Vector4 mz0 = my1 + my7; - Vector4 my3 = Mm_load_ps(y, 24); + Vector4 my3 = _mm_load_ps(y, 24); Vector4 mz2 = my3 + my7; - Vector4 my5 = Mm_load_ps(y, 40); + Vector4 my5 = _mm_load_ps(y, 40); Vector4 mz1 = my3 + my5; Vector4 mz3 = my1 + my5; Vector4 mz4 = (mz0 + mz1) * _1_175876; - /* z0 = y[1] + y[7]; z1 = y[3] + y[5]; z2 = y[3] + y[7]; z3 = y[1] + y[5]; - z4 = (z0 + z1) * r[3];*/ + // z0 = y[1] + y[7]; z1 = y[3] + y[5]; z2 = y[3] + y[7]; z3 = y[1] + y[5]; + // z4 = (z0 + z1) * r[3]; mz2 = (mz2 * _1_961571) + mz4; mz3 = (mz3 * _0_390181) + mz4; mz0 = mz0 * _0_899976; @@ -426,11 +414,11 @@ internal static void IDCT2D8x4_32f(Span y, Span x) b0 = y[1] * ( r[1] + r[3] - r[5] - r[7]) + z0 + z3; */ - Vector4 my2 = Mm_load_ps(y, 16); - Vector4 my6 = Mm_load_ps(y, 48); + Vector4 my2 = _mm_load_ps(y, 16); + Vector4 my6 = _mm_load_ps(y, 48); mz4 = (my2 + my6) * _0_541196; - Vector4 my0 = Mm_load_ps(y, 0); - Vector4 my4 = Mm_load_ps(y, 32); + Vector4 my0 = _mm_load_ps(y, 0); + Vector4 my4 = _mm_load_ps(y, 32); mz0 = my0 + my4; mz1 = my0 - my4; @@ -441,7 +429,6 @@ internal static void IDCT2D8x4_32f(Span y, Span x) my3 = mz0 - mz3; my1 = mz1 + mz2; my2 = mz1 - mz2; - /* 1.847759 0.765367 @@ -453,22 +440,21 @@ internal static void IDCT2D8x4_32f(Span y, Span x) a1 = z1 + z2; a2 = z1 - z2; */ - Mm_store_ps(x, 0, my0 + mb0); - - Mm_store_ps(x, 56, my0 - mb0); + _mm_store_ps(x, 0, my0 + mb0); - Mm_store_ps(x, 8, my1 + mb1); + _mm_store_ps(x, 56, my0 - mb0); - Mm_store_ps(x, 48, my1 - mb1); + _mm_store_ps(x, 8, my1 + mb1); - Mm_store_ps(x, 16, my2 + mb2); + _mm_store_ps(x, 48, my1 - mb1); - Mm_store_ps(x, 40, my2 - mb2); + _mm_store_ps(x, 16, my2 + mb2); - Mm_store_ps(x, 24, my3 + mb3); + _mm_store_ps(x, 40, my2 - mb2); - Mm_store_ps(x, 32, my3 - mb3); + _mm_store_ps(x, 24, my3 + mb3); + _mm_store_ps(x, 32, my3 - mb3); /* x[0] = a0 + b0; x[7] = a0 - b0; x[1] = a1 + b1; x[6] = a1 - b1; @@ -496,7 +482,7 @@ internal static void FDCT1Dllm_32f(Span x, Span y) const float invsqrt2 = 0.707107f; // (float)(1.0f / M_SQRT2); - // const float invsqrt2h = 0.353554f; // invsqrt2*0.5f; + // const float invsqrt2h = 0.353554f; //invsqrt2*0.5f; c1 = x[0]; c2 = x[7]; t0 = c1 + c2; From 715de4cd3c8d97b32f33e62a7a9d9977b77951d0 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 14:28:38 +0100 Subject: [PATCH 06/15] Defining the tmp vars in a single line again --- .../PixelConversion_Rgba32_To_Bgra32.cs | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs index 90591d1750..4b09dd81e1 100644 --- a/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs +++ b/tests/ImageSharp.Benchmarks/General/PixelConversion/PixelConversion_Rgba32_To_Bgra32.cs @@ -242,31 +242,19 @@ public void Bitops_Simd() } } +#pragma warning disable SA1132 // Do not combine fields [StructLayout(LayoutKind.Sequential)] private struct B { - public uint Tmp2; - public uint Tmp5; - public uint Tmp8; - public uint Tmp11; - public uint Tmp14; - public uint Tmp17; - public uint Tmp20; - public uint Tmp23; + public uint Tmp2, Tmp5, Tmp8, Tmp11, Tmp14, Tmp17, Tmp20, Tmp23; } [StructLayout(LayoutKind.Sequential)] private struct C { - public uint Tmp3; - public uint Tmp6; - public uint Tmp9; - public uint Tmp12; - public uint Tmp15; - public uint Tmp18; - public uint Tmp21; - public uint Tmp24; + public uint Tmp3, Tmp6, Tmp9, Tmp12, Tmp15, Tmp18, Tmp21, Tmp24; } +#pragma warning restore SA1132 // Do not combine fields [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void BitopsSimdImpl(ref Octet.OfUInt32 s, ref Octet.OfUInt32 d) From 8a6797c2e4c961974f1f99f884c7cca87edbc351 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 14:33:43 +0100 Subject: [PATCH 07/15] Move ITestImageProvider to a separate file --- .../ImageProviders/ITestImageProvider.cs | 164 ----------------- .../ImageProviders/TestImageProvider.cs | 169 ++++++++++++++++++ 2 files changed, 169 insertions(+), 164 deletions(-) create mode 100644 tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs index 347e809c0a..199cc43166 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/ITestImageProvider.cs @@ -1,16 +1,6 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using System; -using System.Reflection; -using Castle.Core.Internal; - -using SixLabors.ImageSharp.Formats; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; - -using Xunit.Abstractions; - namespace SixLabors.ImageSharp.Tests { public interface ITestImageProvider @@ -23,158 +13,4 @@ public interface ITestImageProvider Configuration Configuration { get; set; } } - - /// - /// Provides instances for parametric unit tests. - /// - /// The pixel format of the image. - public abstract partial class TestImageProvider : ITestImageProvider - where TPixel : struct, IPixel - { - public PixelTypes PixelType { get; private set; } = typeof(TPixel).GetPixelType(); - - public virtual string SourceFileOrDescription => string.Empty; - - public Configuration Configuration { get; set; } = Configuration.CreateDefaultInstance(); - - /// - /// Gets the utility instance to provide information about the test image & manage input/output. - /// - public ImagingTestCaseUtility Utility { get; private set; } - - public string TypeName { get; private set; } - - public string MethodName { get; private set; } - - public string OutputSubfolderName { get; private set; } - - public static TestImageProvider BasicTestPattern( - int width, - int height, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - => new BasicTestPatternProvider(width, height).Init(testMethod, pixelTypeOverride); - - public static TestImageProvider TestPattern( - int width, - int height, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - => new TestPatternProvider(width, height).Init(testMethod, pixelTypeOverride); - - public static TestImageProvider Blank( - int width, - int height, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - => new BlankProvider(width, height).Init(testMethod, pixelTypeOverride); - - public static TestImageProvider File( - string filePath, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - { - return new FileProvider(filePath).Init(testMethod, pixelTypeOverride); - } - - public static TestImageProvider Lambda( - Func> factoryFunc, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - => new LambdaProvider(factoryFunc).Init(testMethod, pixelTypeOverride); - - public static TestImageProvider Solid( - int width, - int height, - byte r, - byte g, - byte b, - byte a = 255, - MethodInfo testMethod = null, - PixelTypes pixelTypeOverride = PixelTypes.Undefined) - { - return new SolidProvider(width, height, r, g, b, a).Init(testMethod, pixelTypeOverride); - } - - /// - /// Returns an instance to the test case with the necessary traits. - /// - /// A test image. - public abstract Image GetImage(); - - public virtual Image GetImage(IImageDecoder decoder) - { - throw new NotSupportedException($"Decoder specific GetImage() is not supported with {this.GetType().Name}!"); - } - - /// - /// Returns an instance to the test case with the necessary traits. - /// - /// A test image. - public Image GetImage(Action operationsToApply) - { - Image img = this.GetImage(); - img.Mutate(operationsToApply); - return img; - } - - public virtual void Deserialize(IXunitSerializationInfo info) - { - PixelTypes pixelType = info.GetValue("PixelType"); - string typeName = info.GetValue("TypeName"); - string methodName = info.GetValue("MethodName"); - string outputSubfolderName = info.GetValue("OutputSubfolderName"); - - this.Init(typeName, methodName, outputSubfolderName, pixelType); - } - - public virtual void Serialize(IXunitSerializationInfo info) - { - info.AddValue("PixelType", this.PixelType); - info.AddValue("TypeName", this.TypeName); - info.AddValue("MethodName", this.MethodName); - info.AddValue("OutputSubfolderName", this.OutputSubfolderName); - } - - protected TestImageProvider Init( - string typeName, - string methodName, - string outputSubfolderName, - PixelTypes pixelTypeOverride) - { - if (pixelTypeOverride != PixelTypes.Undefined) - { - this.PixelType = pixelTypeOverride; - } - - this.TypeName = typeName; - this.MethodName = methodName; - this.OutputSubfolderName = outputSubfolderName; - - this.Utility = new ImagingTestCaseUtility - { - SourceFileOrDescription = this.SourceFileOrDescription, - PixelTypeName = this.PixelType.ToString() - }; - - if (methodName != null) - { - this.Utility.Init(typeName, methodName, outputSubfolderName); - } - - return this; - } - - protected TestImageProvider Init(MethodInfo testMethod, PixelTypes pixelTypeOverride) - { - string subfolder = testMethod?.DeclaringType.GetAttribute()?.Subfolder - ?? string.Empty; - return this.Init(testMethod?.DeclaringType.Name, testMethod?.Name, subfolder, pixelTypeOverride); - } - - public override string ToString() - { - return $"{this.SourceFileOrDescription}[{this.PixelType}]"; - } - } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs new file mode 100644 index 0000000000..aca1eae885 --- /dev/null +++ b/tests/ImageSharp.Tests/TestUtilities/ImageProviders/TestImageProvider.cs @@ -0,0 +1,169 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Reflection; +using Castle.Core.Internal; + +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; + +using Xunit.Abstractions; + +namespace SixLabors.ImageSharp.Tests +{ + /// + /// Provides instances for parametric unit tests. + /// + /// The pixel format of the image. + public abstract partial class TestImageProvider : ITestImageProvider + where TPixel : struct, IPixel + { + public PixelTypes PixelType { get; private set; } = typeof(TPixel).GetPixelType(); + + public virtual string SourceFileOrDescription => string.Empty; + + public Configuration Configuration { get; set; } = Configuration.CreateDefaultInstance(); + + /// + /// Gets the utility instance to provide information about the test image & manage input/output. + /// + public ImagingTestCaseUtility Utility { get; private set; } + + public string TypeName { get; private set; } + + public string MethodName { get; private set; } + + public string OutputSubfolderName { get; private set; } + + public static TestImageProvider BasicTestPattern( + int width, + int height, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + => new BasicTestPatternProvider(width, height).Init(testMethod, pixelTypeOverride); + + public static TestImageProvider TestPattern( + int width, + int height, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + => new TestPatternProvider(width, height).Init(testMethod, pixelTypeOverride); + + public static TestImageProvider Blank( + int width, + int height, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + => new BlankProvider(width, height).Init(testMethod, pixelTypeOverride); + + public static TestImageProvider File( + string filePath, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + { + return new FileProvider(filePath).Init(testMethod, pixelTypeOverride); + } + + public static TestImageProvider Lambda( + Func> factoryFunc, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + => new LambdaProvider(factoryFunc).Init(testMethod, pixelTypeOverride); + + public static TestImageProvider Solid( + int width, + int height, + byte r, + byte g, + byte b, + byte a = 255, + MethodInfo testMethod = null, + PixelTypes pixelTypeOverride = PixelTypes.Undefined) + { + return new SolidProvider(width, height, r, g, b, a).Init(testMethod, pixelTypeOverride); + } + + /// + /// Returns an instance to the test case with the necessary traits. + /// + /// A test image. + public abstract Image GetImage(); + + public virtual Image GetImage(IImageDecoder decoder) + { + throw new NotSupportedException($"Decoder specific GetImage() is not supported with {this.GetType().Name}!"); + } + + /// + /// Returns an instance to the test case with the necessary traits. + /// + /// A test image. + public Image GetImage(Action operationsToApply) + { + Image img = this.GetImage(); + img.Mutate(operationsToApply); + return img; + } + + public virtual void Deserialize(IXunitSerializationInfo info) + { + PixelTypes pixelType = info.GetValue("PixelType"); + string typeName = info.GetValue("TypeName"); + string methodName = info.GetValue("MethodName"); + string outputSubfolderName = info.GetValue("OutputSubfolderName"); + + this.Init(typeName, methodName, outputSubfolderName, pixelType); + } + + public virtual void Serialize(IXunitSerializationInfo info) + { + info.AddValue("PixelType", this.PixelType); + info.AddValue("TypeName", this.TypeName); + info.AddValue("MethodName", this.MethodName); + info.AddValue("OutputSubfolderName", this.OutputSubfolderName); + } + + protected TestImageProvider Init( + string typeName, + string methodName, + string outputSubfolderName, + PixelTypes pixelTypeOverride) + { + if (pixelTypeOverride != PixelTypes.Undefined) + { + this.PixelType = pixelTypeOverride; + } + + this.TypeName = typeName; + this.MethodName = methodName; + this.OutputSubfolderName = outputSubfolderName; + + this.Utility = new ImagingTestCaseUtility + { + SourceFileOrDescription = this.SourceFileOrDescription, + PixelTypeName = this.PixelType.ToString() + }; + + if (methodName != null) + { + this.Utility.Init(typeName, methodName, outputSubfolderName); + } + + return this; + } + + protected TestImageProvider Init(MethodInfo testMethod, PixelTypes pixelTypeOverride) + { + string subfolder = testMethod?.DeclaringType.GetAttribute()?.Subfolder + ?? string.Empty; + return this.Init(testMethod?.DeclaringType.Name, testMethod?.Name, subfolder, pixelTypeOverride); + } + + public override string ToString() + { + return $"{this.SourceFileOrDescription}[{this.PixelType}]"; + } + } +} From d59ca988a0e730db1bfbac9825593e58f2b8b1e9 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 23 Jan 2020 14:39:46 +0100 Subject: [PATCH 08/15] Revert comment as it was before, add exception for SA1115 --- .../Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs index cf87cb1a24..fb445f6a22 100644 --- a/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs +++ b/tests/ImageSharp.Benchmarks/Codecs/Jpeg/DecodeJpeg_ImageSpecific.cs @@ -47,12 +47,15 @@ public ShortClr() [Params( TestImages.Jpeg.BenchmarkSuite.Lake_Small444YCbCr, TestImages.Jpeg.BenchmarkSuite.BadRstProgressive518_Large444YCbCr, - /* The scaled result for the large image "ExifGetString750Transform_Huge420YCbCr" - is almost the same as the result for Jpeg420Exif, - which proves that the execution time for the most common YCbCr 420 path scales linearly. - TestImages.Jpeg.BenchmarkSuite.ExifGetString750Transform_Huge420YCbCr, - */ + +#pragma warning disable SA1115 // Parameter should follow comma + + // The scaled result for the large image "ExifGetString750Transform_Huge420YCbCr" + // is almost the same as the result for Jpeg420Exif, + // which proves that the execution time for the most common YCbCr 420 path scales linearly. + // TestImages.Jpeg.BenchmarkSuite.ExifGetString750Transform_Huge420YCbCr, TestImages.Jpeg.BenchmarkSuite.Jpeg420Exif_MidSizeYCbCr)] +#pragma warning restore SA1115 // Parameter should follow comma public string TestImage { get; set; } From 076a2bcb5b43b978c1bc70ae4febc7eb619dd33d Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 30 Jan 2020 15:14:17 +0100 Subject: [PATCH 09/15] Update external for the changed test ruleset --- shared-infrastructure | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared-infrastructure b/shared-infrastructure index 36b2d55f5b..13b1152a9e 160000 --- a/shared-infrastructure +++ b/shared-infrastructure @@ -1 +1 @@ -Subproject commit 36b2d55f5bb0d91024955bd26ba220ee41cc96e5 +Subproject commit 13b1152a9e93d1b67690e1e9325af248b7c2145d From 6f0e6e9a26d29effc4dee01e8eb547f770f91674 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 30 Jan 2020 15:26:56 +0100 Subject: [PATCH 10/15] Fix some leftover stylecop warnings --- .../Memory/Alocators/ArrayPoolMemoryAllocatorTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ImageSharp.Tests/Memory/Alocators/ArrayPoolMemoryAllocatorTests.cs b/tests/ImageSharp.Tests/Memory/Alocators/ArrayPoolMemoryAllocatorTests.cs index 22fcfa6fb4..dd497e57ee 100644 --- a/tests/ImageSharp.Tests/Memory/Alocators/ArrayPoolMemoryAllocatorTests.cs +++ b/tests/ImageSharp.Tests/Memory/Alocators/ArrayPoolMemoryAllocatorTests.cs @@ -21,12 +21,12 @@ public class ArrayPoolMemoryAllocatorTests private const int PoolSelectorThresholdInBytes = MaxPooledBufferSizeInBytes / 2; /// - /// Contains SUT for in-process tests. + /// Gets the SUT for in-process tests. /// private MemoryAllocatorFixture LocalFixture { get; } = new MemoryAllocatorFixture(); /// - /// Contains SUT for tests executed by , + /// Gets the SUT for tests executed by , /// recreated in each external process. /// private static MemoryAllocatorFixture StaticFixture { get; } = new MemoryAllocatorFixture(); From 9f181a3755a28da410fc1835fcbc5a5619a212b0 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 30 Jan 2020 15:27:32 +0100 Subject: [PATCH 11/15] Change InternalsVisibleTo from SixLabors.ImageSharp.Sandbox46 to ImageSharp.Tests.ProfilingSandbox --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index bcf444c75b..4be8d63d10 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -30,8 +30,8 @@ - + From 5ff7bb72d22c8e6cdd0df190ec622f09fc7ca758 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Fri, 31 Jan 2020 13:25:44 +0100 Subject: [PATCH 12/15] Revert "Change InternalsVisibleTo from SixLabors.ImageSharp.Sandbox46 to ImageSharp.Tests.ProfilingSandbox" This reverts commit 9f181a3755a28da410fc1835fcbc5a5619a212b0. --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 4be8d63d10..bcf444c75b 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -30,8 +30,8 @@ + - From 0bce7af847619aeae7bce0357a1d2179c128cb14 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Fri, 31 Jan 2020 13:30:34 +0100 Subject: [PATCH 13/15] Remove including tests into the profiling sandbox --- .../ImageSharp.Tests.ProfilingSandbox.csproj | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/ImageSharp.Tests.ProfilingSandbox/ImageSharp.Tests.ProfilingSandbox.csproj b/tests/ImageSharp.Tests.ProfilingSandbox/ImageSharp.Tests.ProfilingSandbox.csproj index 588f4395b7..7c80316930 100644 --- a/tests/ImageSharp.Tests.ProfilingSandbox/ImageSharp.Tests.ProfilingSandbox.csproj +++ b/tests/ImageSharp.Tests.ProfilingSandbox/ImageSharp.Tests.ProfilingSandbox.csproj @@ -14,10 +14,6 @@ false - - - - From 15a7a557f27f70209b66af8d36d669d46272d354 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Sun, 2 Feb 2020 14:27:32 +1100 Subject: [PATCH 14/15] Revert `using` declaration changes for until we establish guidelines. --- .../Advanced/AdvancedImageExtensionsTests.cs | 137 +++--- .../Common/StreamExtensionsTests.cs | 42 +- .../Drawing/DrawImageTests.cs | 192 +++++---- .../Formats/Bmp/BmpDecoderTests.cs | 346 +++++++++------ .../Formats/Bmp/BmpEncoderTests.cs | 113 +++-- .../Formats/Bmp/BmpMetadataTests.cs | 14 +- .../Formats/GeneralFormatTests.cs | 119 ++--- .../Formats/Gif/GifDecoderTests.cs | 74 ++-- .../Formats/Gif/GifEncoderTests.cs | 162 ++++--- .../Formats/Gif/GifMetadataTests.cs | 86 ++-- .../Formats/ImageFormatManagerTests.cs | 12 +- .../Jpg/Block8x8FTests.CopyToBufferArea.cs | 48 ++- .../Formats/Jpg/GenericBlock8x8Tests.cs | 80 ++-- .../Formats/Jpg/JpegDecoderTests.Metadata.cs | 88 ++-- .../Formats/Jpg/JpegDecoderTests.cs | 34 +- .../Formats/Jpg/JpegEncoderTests.cs | 107 +++-- .../Jpg/JpegImagePostProcessorTests.cs | 58 +-- .../Formats/Jpg/ParseStreamTests.cs | 60 +-- .../Formats/Jpg/SpectralJpegTests.cs | 20 +- .../Formats/Jpg/Utils/JpegFixture.cs | 10 +- .../Formats/Jpg/Utils/LibJpegTools.cs | 46 +- .../Formats/Jpg/Utils/VerifyJpeg.cs | 8 +- .../Formats/Png/PngDecoderTests.Chunks.cs | 18 +- .../Formats/Png/PngDecoderTests.cs | 102 +++-- .../Formats/Png/PngEncoderTests.cs | 224 +++++----- .../Formats/Png/PngMetadataTests.cs | 185 ++++---- .../Formats/Png/PngSmokeTests.cs | 44 +- .../Formats/Tga/TgaDecoderTests.cs | 120 ++++-- .../Formats/Tga/TgaEncoderTests.cs | 66 +-- .../Formats/Tga/TgaTestUtils.cs | 28 +- .../Helpers/ParallelHelperTests.cs | 60 +-- .../Helpers/RowIntervalTests.cs | 18 +- .../IO/DoubleBufferedStreamReaderTests.cs | 190 ++++---- .../ImageSharp.Tests/Image/ImageCloneTests.cs | 116 ++--- .../ImageFrameCollectionTests.Generic.cs | 30 +- .../ImageFrameCollectionTests.NonGeneric.cs | 81 ++-- .../Image/ImageRotationTests.cs | 12 +- .../Image/ImageTests.DetectFormat.cs | 8 +- .../Image/ImageTests.LoadPixelData.cs | 40 +- ..._FileSystemPath_UseDefaultConfiguration.cs | 40 +- ...s.Load_FromBytes_UseGlobalConfiguration.cs | 40 +- ...Load_FromStream_UseDefaultConfiguration.cs | 40 +- .../ImageSharp.Tests/Image/ImageTests.Save.cs | 28 +- .../Image/ImageTests.WrapMemory.cs | 88 ++-- tests/ImageSharp.Tests/Image/ImageTests.cs | 56 +-- .../ImageSharp.Tests/Memory/Buffer2DTests.cs | 106 +++-- .../Memory/BufferAreaTests.cs | 112 ++--- .../Metadata/ImageMetadataTests.cs | 16 +- .../Profiles/Exif/ExifProfileTests.cs | 70 +-- .../Metadata/Profiles/Exif/ExifValueTests.cs | 6 +- .../PorterDuffCompositorTests.cs | 32 +- ...elOperationsTests.Rgba32OperationsTests.cs | 22 +- .../PixelOperations/PixelOperationsTests.cs | 8 +- .../HistogramEqualizationTests.cs | 114 ++--- .../Binarization/BinaryDitherTests.cs | 60 +-- .../Binarization/BinaryThresholdTest.cs | 22 +- .../Processors/Convolution/BokehBlurTest.cs | 26 +- .../Processors/Convolution/DetectEdgesTest.cs | 40 +- .../Processors/Transforms/AutoOrientTests.cs | 28 +- .../Processors/Transforms/PadTest.cs | 36 +- .../Processors/Transforms/ResizeTests.cs | 407 ++++++++++-------- .../Processors/Transforms/RotateFlipTests.cs | 12 +- .../Transforms/AffineTransformTests.cs | 102 +++-- .../Transforms/ProjectiveTransformTests.cs | 68 +-- .../Transforms/TransformsHelpersTest.cs | 22 +- .../LoadResizeSaveProfilingBenchmarks.cs | 28 +- .../ResizeProfilingBenchmarks.cs | 10 +- .../Quantization/QuantizedImageTests.cs | 40 +- .../Quantization/WuQuantizerTests.cs | 176 ++++---- .../TestUtilities/ImagingTestCaseUtility.cs | 12 +- .../ReferenceCodecs/MagickReferenceDecoder.cs | 64 +-- .../ReferenceCodecs/SystemDrawingBridge.cs | 60 +-- .../SystemDrawingReferenceDecoder.cs | 48 ++- .../SystemDrawingReferenceEncoder.cs | 8 +- .../TestUtilities/TestImageExtensions.cs | 62 +-- .../TestUtilities/Tests/ImageComparerTests.cs | 104 +++-- .../Tests/MagickReferenceCodecTests.cs | 32 +- .../Tests/SystemDrawingReferenceCodecTests.cs | 78 ++-- .../Tests/TestImageExtensionsTests.cs | 60 ++- .../Tests/TestImageProviderTests.cs | 50 ++- 80 files changed, 3219 insertions(+), 2412 deletions(-) diff --git a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs index 877e3a9f8e..f6b51e8c54 100644 --- a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs @@ -20,20 +20,23 @@ public class GetPixelMemory public void WhenMemoryIsOwned(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image0 = provider.GetImage(); - var targetBuffer = new TPixel[image0.Width * image0.Height]; - - // Act: - Memory memory = image0.GetPixelMemory(); - - // Assert: - Assert.Equal(image0.Width * image0.Height, memory.Length); - memory.Span.CopyTo(targetBuffer); - - using Image image1 = provider.GetImage(); - - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); + using (Image image0 = provider.GetImage()) + { + var targetBuffer = new TPixel[image0.Width * image0.Height]; + + // Act: + Memory memory = image0.GetPixelMemory(); + + // Assert: + Assert.Equal(image0.Width * image0.Height, memory.Length); + memory.Span.CopyTo(targetBuffer); + + using (Image image1 = provider.GetImage()) + { + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); + } + } } [Theory] @@ -42,23 +45,27 @@ public void WhenMemoryIsOwned(TestImageProvider provider) public void WhenMemoryIsConsumed(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image0 = provider.GetImage(); - var targetBuffer = new TPixel[image0.Width * image0.Height]; - image0.GetPixelSpan().CopyTo(targetBuffer); + using (Image image0 = provider.GetImage()) + { + var targetBuffer = new TPixel[image0.Width * image0.Height]; + image0.GetPixelSpan().CopyTo(targetBuffer); - var managerOfExternalMemory = new TestMemoryManager(targetBuffer); + var managerOfExternalMemory = new TestMemoryManager(targetBuffer); - Memory externalMemory = managerOfExternalMemory.Memory; + Memory externalMemory = managerOfExternalMemory.Memory; - using var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height); - Memory internalMemory = image1.GetPixelMemory(); - Assert.Equal(targetBuffer.Length, internalMemory.Length); - Assert.True(Unsafe.AreSame(ref targetBuffer[0], ref internalMemory.Span[0])); + using (var image1 = Image.WrapMemory(externalMemory, image0.Width, image0.Height)) + { + Memory internalMemory = image1.GetPixelMemory(); + Assert.Equal(targetBuffer.Length, internalMemory.Length); + 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: - image0.ComparePixelBufferTo(externalMemory.Span); + // Make sure externalMemory works after destruction: + image0.ComparePixelBufferTo(externalMemory.Span); + } } } @@ -68,21 +75,24 @@ public void WhenMemoryIsConsumed(TestImageProvider provider) public void GetPixelRowMemory(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var targetBuffer = new TPixel[image.Width * image.Height]; - - // Act: - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) { - Memory rowMemory = image.GetPixelRowMemory(y); - rowMemory.Span.CopyTo(targetBuffer.AsSpan(image.Width * y)); - } + var targetBuffer = new TPixel[image.Width * image.Height]; - // Assert: - using Image image1 = provider.GetImage(); + // Act: + for (int y = 0; y < image.Height; y++) + { + Memory rowMemory = image.GetPixelRowMemory(y); + rowMemory.Span.CopyTo(targetBuffer.AsSpan(image.Width * y)); + } - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); + // Assert: + using (Image image1 = provider.GetImage()) + { + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); + } + } } [Theory] @@ -91,21 +101,24 @@ public void GetPixelRowMemory(TestImageProvider provider) public void GetPixelRowSpan(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var targetBuffer = new TPixel[image.Width * image.Height]; - - // Act: - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) { - Span rowMemory = image.GetPixelRowSpan(y); - rowMemory.CopyTo(targetBuffer.AsSpan(image.Width * y)); - } + var targetBuffer = new TPixel[image.Width * image.Height]; - // Assert: - using Image image1 = provider.GetImage(); + // Act: + for (int y = 0; y < image.Height; y++) + { + Span rowMemory = image.GetPixelRowSpan(y); + rowMemory.CopyTo(targetBuffer.AsSpan(image.Width * y)); + } - // We are using a copy of the original image for assertion - image1.ComparePixelBufferTo(targetBuffer); + // Assert: + using (Image image1 = provider.GetImage()) + { + // We are using a copy of the original image for assertion + image1.ComparePixelBufferTo(targetBuffer); + } + } } #pragma warning disable 0618 @@ -115,19 +128,21 @@ public void GetPixelRowSpan(TestImageProvider provider) public unsafe void DangerousGetPinnableReference_CopyToBuffer(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var targetBuffer = new TPixel[image.Width * image.Height]; - - ref byte source = ref Unsafe.As(ref targetBuffer[0]); - ref byte dest = ref Unsafe.As(ref image.DangerousGetPinnableReferenceToPixelBuffer()); - fixed (byte* targetPtr = &source) - fixed (byte* pixelBasePtr = &dest) + using (Image image = provider.GetImage()) { - uint dataSizeInBytes = (uint)(image.Width * image.Height * Unsafe.SizeOf()); - Unsafe.CopyBlock(targetPtr, pixelBasePtr, dataSizeInBytes); + var targetBuffer = new TPixel[image.Width * image.Height]; + + ref byte source = ref Unsafe.As(ref targetBuffer[0]); + ref byte dest = ref Unsafe.As(ref image.DangerousGetPinnableReferenceToPixelBuffer()); + fixed (byte* targetPtr = &source) + fixed (byte* pixelBasePtr = &dest) + { + uint dataSizeInBytes = (uint)(image.Width * image.Height * Unsafe.SizeOf()); + Unsafe.CopyBlock(targetPtr, pixelBasePtr, dataSizeInBytes); + } + + image.ComparePixelBufferTo(targetBuffer); } - - image.ComparePixelBufferTo(targetBuffer); } } } diff --git a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs index eb0015c52b..d47d5da8ef 100644 --- a/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Common/StreamExtensionsTests.cs @@ -15,43 +15,51 @@ public class StreamExtensionsTests [InlineData(-1)] public void Skip_CountZeroOrLower_PositionNotChanged(int count) { - using var memStream = new MemoryStream(5); - memStream.Position = 4; - memStream.Skip(count); + using (var memStream = new MemoryStream(5)) + { + memStream.Position = 4; + memStream.Skip(count); - Assert.Equal(4, memStream.Position); + Assert.Equal(4, memStream.Position); + } } [Fact] public void Skip_SeekableStream_SeekIsCalled() { - using var seekableStream = new SeekableStream(4); - seekableStream.Skip(4); + using (var seekableStream = new SeekableStream(4)) + { + seekableStream.Skip(4); - Assert.Equal(4, seekableStream.Offset); - Assert.Equal(SeekOrigin.Current, seekableStream.Loc); + Assert.Equal(4, seekableStream.Offset); + Assert.Equal(SeekOrigin.Current, seekableStream.Loc); + } } [Fact] public void Skip_NonSeekableStream_BytesAreRead() { - using var nonSeekableStream = new NonSeekableStream(); - nonSeekableStream.Skip(5); + using (var nonSeekableStream = new NonSeekableStream()) + { + nonSeekableStream.Skip(5); - Assert.Equal(3, nonSeekableStream.Counts.Count); + Assert.Equal(3, nonSeekableStream.Counts.Count); - Assert.Equal(5, nonSeekableStream.Counts[0]); - Assert.Equal(3, nonSeekableStream.Counts[1]); - Assert.Equal(1, nonSeekableStream.Counts[2]); + Assert.Equal(5, nonSeekableStream.Counts[0]); + Assert.Equal(3, nonSeekableStream.Counts[1]); + Assert.Equal(1, nonSeekableStream.Counts[2]); + } } [Fact] public void Skip_EofStream_NoExceptionIsThrown() { - using var eofStream = new EofStream(7); - eofStream.Skip(7); + using (var eofStream = new EofStream(7)) + { + eofStream.Skip(7); - Assert.Equal(0, eofStream.Position); + Assert.Equal(0, eofStream.Position); + } } private class SeekableStream : MemoryStream diff --git a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs index e1ad5a0a84..31e63a2fd7 100644 --- a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs @@ -33,22 +33,24 @@ public class DrawImageTests public void ImageBlendingMatchesSvgSpecExamples(TestImageProvider provider, PixelColorBlendingMode mode) where TPixel : struct, IPixel { - using Image background = provider.GetImage(); - using var source = Image.Load(TestFile.Create(TestImages.Png.Ducky).Bytes); - background.Mutate(x => x.DrawImage(source, mode, 1F)); - background.DebugSave( - provider, - new { mode = mode }, - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - - var comparer = ImageComparer.TolerantPercentage(0.01F); - background.CompareToReferenceOutput( - comparer, - provider, - new { mode = mode }, - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); + using (Image background = provider.GetImage()) + using (var source = Image.Load(TestFile.Create(TestImages.Png.Ducky).Bytes)) + { + background.Mutate(x => x.DrawImage(source, mode, 1F)); + background.DebugSave( + provider, + new { mode = mode }, + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + + var comparer = ImageComparer.TolerantPercentage(0.01F); + background.CompareToReferenceOutput( + comparer, + provider, + new { mode = mode }, + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + } } [Theory] @@ -70,26 +72,28 @@ public void WorksWithDifferentConfigurations( float opacity) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using var blend = Image.Load(TestFile.Create(brushImage).Bytes); - var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4); - var position = new Point(image.Width / 8, image.Height / 8); - blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic)); - image.Mutate(x => x.DrawImage(blend, position, mode, opacity)); - FormattableString testInfo = $"{System.IO.Path.GetFileNameWithoutExtension(brushImage)}-{mode}-{opacity}"; - - var encoder = new PngEncoder(); - - if (provider.PixelType == PixelTypes.Rgba64) + using (Image image = provider.GetImage()) + using (var blend = Image.Load(TestFile.Create(brushImage).Bytes)) { - encoder.BitDepth = PngBitDepth.Bit16; + var size = new Size(image.Width * 3 / 4, image.Height * 3 / 4); + var position = new Point(image.Width / 8, image.Height / 8); + blend.Mutate(x => x.Resize(size.Width, size.Height, KnownResamplers.Bicubic)); + image.Mutate(x => x.DrawImage(blend, position, mode, opacity)); + FormattableString testInfo = $"{System.IO.Path.GetFileNameWithoutExtension(brushImage)}-{mode}-{opacity}"; + + var encoder = new PngEncoder(); + + if (provider.PixelType == PixelTypes.Rgba64) + { + encoder.BitDepth = PngBitDepth.Bit16; + } + + image.DebugSave(provider, testInfo, encoder: encoder); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.01f), + provider, + testInfo); } - - image.DebugSave(provider, testInfo, encoder: encoder); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.01f), - provider, - testInfo); } [Theory] @@ -99,17 +103,19 @@ public void DrawImageOfDifferentPixelType(TestImageProvider prov { byte[] brushData = TestFile.Create(TestImages.Png.Ducky).Bytes; - using Image image = provider.GetImage(); - using Image brushImage = provider.PixelType == PixelTypes.Rgba32 - ? (Image)Image.Load(brushData) - : Image.Load(brushData); - image.Mutate(c => c.DrawImage(brushImage, 0.5f)); - - image.DebugSave(provider, appendSourceFileOrDescription: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.01f), - provider, - appendSourceFileOrDescription: false); + using (Image image = provider.GetImage()) + using (Image brushImage = provider.PixelType == PixelTypes.Rgba32 + ? (Image)Image.Load(brushData) + : Image.Load(brushData)) + { + image.Mutate(c => c.DrawImage(brushImage, 0.5f)); + + image.DebugSave(provider, appendSourceFileOrDescription: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.01f), + provider, + appendSourceFileOrDescription: false); + } } [Theory] @@ -119,23 +125,25 @@ public void DrawImageOfDifferentPixelType(TestImageProvider prov [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, -25, -30)] public void WorksWithDifferentLocations(TestImageProvider provider, int x, int y) { - using Image background = provider.GetImage(); - using var overlay = new Image(50, 50); - overlay.GetPixelSpan().Fill(Rgba32.Black); - - background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); - - background.DebugSave( - provider, - testOutputDetails: $"{x}_{y}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); - - background.CompareToReferenceOutput( - provider, - testOutputDetails: $"{x}_{y}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: false); + using (Image background = provider.GetImage()) + using (var overlay = new Image(50, 50)) + { + overlay.GetPixelSpan().Fill(Rgba32.Black); + + background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); + + background.DebugSave( + provider, + testOutputDetails: $"{x}_{y}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + + background.CompareToReferenceOutput( + provider, + testOutputDetails: $"{x}_{y}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + } } [Theory] @@ -143,27 +151,29 @@ public void WorksWithDifferentLocations(TestImageProvider provider, int public void DrawTransformed(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using var blend = Image.Load(TestFile.Create(TestImages.Bmp.Car).Bytes); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(45F) - .AppendScale(new SizeF(.25F, .25F)) - .AppendTranslation(new PointF(10, 10)); - - // Apply a background color so we can see the translation. - blend.Mutate(x => x.Transform(builder)); - blend.Mutate(x => x.BackgroundColor(Color.HotPink)); - - // Lets center the matrix so we can tell whether any cut-off issues we may have belong to the drawing processor - var position = new Point((image.Width - blend.Width) / 2, (image.Height - blend.Height) / 2); - image.Mutate(x => x.DrawImage(blend, position, .75F)); - - image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.002f), - provider, - appendSourceFileOrDescription: false, - appendPixelTypeToFileName: false); + using (Image image = provider.GetImage()) + using (var blend = Image.Load(TestFile.Create(TestImages.Bmp.Car).Bytes)) + { + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(45F) + .AppendScale(new SizeF(.25F, .25F)) + .AppendTranslation(new PointF(10, 10)); + + // Apply a background color so we can see the translation. + blend.Mutate(x => x.Transform(builder)); + blend.Mutate(x => x.BackgroundColor(Color.HotPink)); + + // Lets center the matrix so we can tell whether any cut-off issues we may have belong to the drawing processor + var position = new Point((image.Width - blend.Width) / 2, (image.Height - blend.Height) / 2); + image.Mutate(x => x.DrawImage(blend, position, .75F)); + + image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.002f), + provider, + appendSourceFileOrDescription: false, + appendPixelTypeToFileName: false); + } } [Theory] @@ -173,15 +183,17 @@ public void DrawTransformed(TestImageProvider provider) [WithSolidFilledImages(100, 100, 255, 255, 255, PixelTypes.Rgba32, -30, 130)] public void NonOverlappingImageThrows(TestImageProvider provider, int x, int y) { - using Image background = provider.GetImage(); - using var overlay = new Image(Configuration.Default, 10, 10, Rgba32.Black); - ImageProcessingException ex = Assert.Throws(Test); + using (Image background = provider.GetImage()) + using (var overlay = new Image(Configuration.Default, 10, 10, Rgba32.Black)) + { + ImageProcessingException ex = Assert.Throws(Test); - Assert.Contains("does not overlap", ex.ToString()); + Assert.Contains("does not overlap", ex.ToString()); - void Test() - { - background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); + void Test() + { + background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs index 9b98eca06e..fb3348be72 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpDecoderTests.cs @@ -37,11 +37,13 @@ public class BmpDecoderTests public void BmpDecoder_CanDecode_MiscellaneousBitmaps(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder())) { - image.CompareToOriginal(provider); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); + } } } @@ -50,9 +52,11 @@ public void BmpDecoder_CanDecode_MiscellaneousBitmaps(TestImageProvider< public void BmpDecoder_CanDecodeBitfields(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -61,9 +65,11 @@ public void BmpDecoder_CanDecodeBitfields(TestImageProvider prov public void BmpDecoder_CanDecode_Inverted(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -72,9 +78,11 @@ public void BmpDecoder_CanDecode_Inverted(TestImageProvider prov public void BmpDecoder_CanDecode_1Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); + } } [Theory] @@ -82,13 +90,15 @@ public void BmpDecoder_CanDecode_1Bit(TestImageProvider provider public void BmpDecoder_CanDecode_4Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder())) { - image.CompareToOriginal(provider); + image.DebugSave(provider); + + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); + } } } @@ -97,9 +107,11 @@ public void BmpDecoder_CanDecode_4Bit(TestImageProvider provider public void BmpDecoder_CanDecode_8Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -107,9 +119,11 @@ public void BmpDecoder_CanDecode_8Bit(TestImageProvider provider public void BmpDecoder_CanDecode_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -117,9 +131,11 @@ public void BmpDecoder_CanDecode_16Bit(TestImageProvider provide public void BmpDecoder_CanDecode_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -127,9 +143,11 @@ public void BmpDecoder_CanDecode_32Bit(TestImageProvider provide public void BmpDecoder_CanDecode_32BitV4Header_Fast(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -139,13 +157,15 @@ public void BmpDecoder_CanDecode_32BitV4Header_Fast(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); - image.DebugSave(provider); - - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) { - image.CompareToOriginal(provider); + image.DebugSave(provider); + + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); + } } } @@ -154,13 +174,15 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit_WithDelta(TestIma public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); - image.DebugSave(provider); - - // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) { - image.CompareToOriginal(provider); + image.DebugSave(provider); + + // The Magick Reference Decoder can not decode 4-Bit bitmaps, so only execute this on windows. + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); + } } } @@ -172,11 +194,13 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_4Bit(TestImageProvider public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRefDecoder(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); - image.DebugSave(provider); - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) { - image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider, new SystemDrawingReferenceDecoder()); + } } } @@ -186,9 +210,11 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_SystemDrawingRe public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecoder(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette }); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -197,9 +223,11 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit_WithDelta_MagickRefDecode public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette }); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.FirstColorOfPalette })) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -209,11 +237,13 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_8Bit(TestImageProvider public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black }); - image.DebugSave(provider); + using (Image image = provider.GetImage(new BmpDecoder { RleSkippedPixelHandling = RleSkippedPixelHandling.Black })) + { + image.DebugSave(provider); - // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. - // image.CompareToOriginal(provider); + // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. + // image.CompareToOriginal(provider); + } } [Theory] @@ -221,11 +251,13 @@ public void BmpDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvide public void BmpDecoder_CanDecodeAlphaBitfields(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); - // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. - // image.CompareToOriginal(provider); + // TODO: Neither System.Drawing nor MagickReferenceDecoder decode this file. + // image.CompareToOriginal(provider); + } } [Theory] @@ -233,9 +265,11 @@ public void BmpDecoder_CanDecodeAlphaBitfields(TestImageProvider public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -243,15 +277,17 @@ public void BmpDecoder_CanDecodeBitmap_WithAlphaChannel(TestImageProvide public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - - // Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel - // seems to be wrong. This bitmap has an alpha channel of two bits. In many cases this alpha channel has a value of 3, - // which should be remapped to 255 for RGBA32, but the magick decoder has a value of 191 set. - // The total difference without the alpha channel is still: 0.0204% - // 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()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + + // Choosing large tolerance of 6.1 here, because for some reason with the MagickReferenceDecoder the alpha channel + // seems to be wrong. This bitmap has an alpha channel of two bits. In many cases this alpha channel has a value of 3, + // which should be remapped to 255 for RGBA32, but the magick decoder has a value of 191 set. + // The total difference without the alpha channel is still: 0.0204% + // 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()); + } } [Theory] @@ -260,9 +296,11 @@ public void BmpDecoder_CanDecodeBitfields_WithUnusualBitmasks(TestImageP public void BmpDecoder_CanDecodeBmpv2(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -270,9 +308,11 @@ public void BmpDecoder_CanDecodeBmpv2(TestImageProvider provider public void BmpDecoder_CanDecodeBmpv3(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -280,9 +320,11 @@ public void BmpDecoder_CanDecodeBmpv3(TestImageProvider provider public void BmpDecoder_CanDecodeLessThanFullPalette(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -291,11 +333,13 @@ public void BmpDecoder_CanDecodeLessThanFullPalette(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - if (TestEnvironment.IsWindows) + using (Image image = provider.GetImage(new BmpDecoder())) { - image.CompareToOriginal(provider); + image.DebugSave(provider); + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider); + } } } @@ -331,9 +375,11 @@ public void BmpDecoder_ThrowsNotSupportedException_OnUnsupportedBitmaps( public void BmpDecoder_CanDecodeAdobeBmpv3(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -341,9 +387,11 @@ public void BmpDecoder_CanDecodeAdobeBmpv3(TestImageProvider pro public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, new MagickReferenceDecoder()); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -351,9 +399,11 @@ public void BmpDecoder_CanDecodeAdobeBmpv3_WithAlpha(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -362,9 +412,11 @@ public void BmpDecoder_CanDecodeBmpv4(TestImageProvider provider public void BmpDecoder_CanDecodeBmpv5(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -372,9 +424,11 @@ public void BmpDecoder_CanDecodeBmpv5(TestImageProvider provider public void BmpDecoder_RespectsFileHeaderOffset(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -382,9 +436,11 @@ public void BmpDecoder_RespectsFileHeaderOffset(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -392,9 +448,11 @@ public void BmpDecoder_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider); + } } [Theory] @@ -413,10 +471,12 @@ public void BmpDecoder_CanDecode4BytePerEntryPalette(TestImageProvider image = decoder.Decode(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new BmpDecoder(); + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } } [Theory] @@ -457,11 +523,13 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void BmpDecoder_CanDecode_Os2v2XShortHeader(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); - // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. - // image.CompareToOriginal(provider); + // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. + // image.CompareToOriginal(provider); + } } [Theory] @@ -469,13 +537,15 @@ public void BmpDecoder_CanDecode_Os2v2XShortHeader(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); - // TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it, - // but i think incorrectly. I have loaded the image with GIMP and exported as PNG. - // The results are the same as the image sharp implementation. - // image.CompareToOriginal(provider, new MagickReferenceDecoder()); + // TODO: System.Drawing can not decode this image. MagickReferenceDecoder can decode it, + // but i think incorrectly. I have loaded the image with GIMP and exported as PNG. + // The results are the same as the image sharp implementation. + // image.CompareToOriginal(provider, new MagickReferenceDecoder()); + } } [Theory] @@ -491,11 +561,13 @@ public void BmpDecoder_CanDecode_Os2v2Header(TestImageProvider p public void BmpDecoder_CanDecode_Os2BitmapArray(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new BmpDecoder()); - image.DebugSave(provider); + using (Image image = provider.GetImage(new BmpDecoder())) + { + image.DebugSave(provider); - // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. - // image.CompareToOriginal(provider); + // TODO: Neither System.Drawing or MagickReferenceDecoder can correctly decode this file. + // image.CompareToOriginal(provider); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs index 743248b5d4..55d31b5a38 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpEncoderTests.cs @@ -54,16 +54,22 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new BmpEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } + } } [Theory] @@ -73,15 +79,21 @@ public void Encode_PreserveBitsPerPixel(string imagePath, BmpBitsPerPixel bmpBit var options = new BmpEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - BmpMetadata meta = output.Metadata.GetBmpMetadata(); - - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + BmpMetadata meta = output.Metadata.GetBmpMetadata(); + + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + } + } + } } [Theory] @@ -180,16 +192,20 @@ public void Encode_8BitColor_WithWuQuantizer(TestImageProvider p return; } - using Image image = provider.GetImage(); - var encoder = new BmpEncoder + using (Image image = provider.GetImage()) { - BitsPerPixel = BmpBitsPerPixel.Pixel8, - Quantizer = new WuQuantizer(256) - }; - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); - referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); + var encoder = new BmpEncoder + { + BitsPerPixel = BmpBitsPerPixel.Pixel8, + Quantizer = new WuQuantizer(256) + }; + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) + { + referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); + } + } } [Theory] @@ -202,16 +218,20 @@ public void Encode_8BitColor_WithOctreeQuantizer(TestImageProvider image = provider.GetImage(); - var encoder = new BmpEncoder + using (Image image = provider.GetImage()) { - BitsPerPixel = BmpBitsPerPixel.Pixel8, - Quantizer = new OctreeQuantizer(256) - }; - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); - referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); + var encoder = new BmpEncoder + { + BitsPerPixel = BmpBitsPerPixel.Pixel8, + Quantizer = new OctreeQuantizer(256) + }; + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false); + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) + { + referenceImage.CompareToReferenceOutput(ImageComparer.TolerantPercentage(0.01f), provider, extension: "bmp", appendPixelTypeToFileName: false); + } + } } [Theory] @@ -227,18 +247,19 @@ private static void TestBmpEncoderCore( ImageComparer customComparer = null) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - - // 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) + using (Image image = provider.GetImage()) { - image.Mutate(c => c.MakeOpaque()); - } + // 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) + { + image.Mutate(c => c.MakeOpaque()); + } - var encoder = new BmpEncoder { BitsPerPixel = bitsPerPixel, SupportTransparency = supportTransparency }; + var encoder = new BmpEncoder { BitsPerPixel = bitsPerPixel, SupportTransparency = supportTransparency }; - // Does DebugSave & load reference CompareToReferenceInput(): - image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer); + // Does DebugSave & load reference CompareToReferenceInput(): + image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs index c0e04a6def..9818f9d41f 100644 --- a/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Bmp/BmpMetadataTests.cs @@ -36,12 +36,14 @@ public void CloneIsDeep() public void Identify_DetectsCorrectBitmapInfoHeaderType(string imagePath, BmpInfoHeaderType expectedInfoHeaderType) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - IImageInfo imageInfo = Image.Identify(stream); - Assert.NotNull(imageInfo); - BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata(); - Assert.NotNull(bitmapMetadata); - Assert.Equal(expectedInfoHeaderType, bitmapMetadata.InfoHeaderType); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + IImageInfo imageInfo = Image.Identify(stream); + Assert.NotNull(imageInfo); + BmpMetadata bitmapMetadata = imageInfo.Metadata.GetBmpMetadata(); + Assert.NotNull(bitmapMetadata); + Assert.Equal(expectedInfoHeaderType, bitmapMetadata.InfoHeaderType); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs index 61130d13f4..95389511bb 100644 --- a/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs +++ b/tests/ImageSharp.Tests/Formats/GeneralFormatTests.cs @@ -23,10 +23,12 @@ public class GeneralFormatTests : FileTestBase public void ResolutionShouldChange(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Metadata.VerticalResolution = 150; - image.Metadata.HorizontalResolution = 150; - image.DebugSave(provider); + using (Image image = provider.GetImage()) + { + image.Metadata.VerticalResolution = 150; + image.Metadata.HorizontalResolution = 150; + image.DebugSave(provider); + } } [Fact] @@ -36,9 +38,11 @@ public void ImageCanEncodeToString() foreach (TestFile file in Files) { - using Image image = file.CreateRgba32Image(); - string filename = path + "/" + file.FileNameWithoutExtension + ".txt"; - File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance)); + using (Image image = file.CreateRgba32Image()) + { + string filename = path + "/" + file.FileNameWithoutExtension + ".txt"; + File.WriteAllText(filename, image.ToBase64String(PngFormat.Instance)); + } } } @@ -49,8 +53,10 @@ public void DecodeThenEncodeImageFromStreamShouldSucceed() foreach (TestFile file in Files) { - using Image image = file.CreateRgba32Image(); - image.Save($"{path}/{file.FileName}"); + using (Image image = file.CreateRgba32Image()) + { + image.Save($"{path}/{file.FileName}"); + } } } @@ -94,25 +100,27 @@ public void ImageCanConvertFormat() foreach (TestFile file in Files) { - using Image image = file.CreateRgba32Image(); - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp")) + using (Image image = file.CreateRgba32Image()) { - image.SaveAsBmp(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.jpg")) - { - image.SaveAsJpeg(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.png")) - { - image.SaveAsPng(output); - } - - using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.gif")) - { - image.SaveAsGif(output); + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.bmp")) + { + image.SaveAsBmp(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.jpg")) + { + image.SaveAsJpeg(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.png")) + { + image.SaveAsPng(output); + } + + using (FileStream output = File.OpenWrite($"{path}/{file.FileNameWithoutExtension}.gif")) + { + image.SaveAsGif(output); + } } } } @@ -124,14 +132,19 @@ public void ImageShouldPreservePixelByteOrderWhenSerialized() foreach (TestFile file in Files) { - using var image = Image.Load(file.Bytes, out IImageFormat mimeType); - using var memoryStream = new MemoryStream(); - image.Save(memoryStream, mimeType); - memoryStream.Flush(); - byte[] serialized = memoryStream.ToArray(); - - using var image2 = Image.Load(serialized); - image2.Save($"{path}/{file.FileName}"); + byte[] serialized; + using (var image = Image.Load(file.Bytes, out IImageFormat mimeType)) + using (var memoryStream = new MemoryStream()) + { + image.Save(memoryStream, mimeType); + memoryStream.Flush(); + serialized = memoryStream.ToArray(); + } + + using (var image2 = Image.Load(serialized)) + { + image2.Save($"{path}/{file.FileName}"); + } } } @@ -157,21 +170,25 @@ public void ImageShouldPreservePixelByteOrderWhenSerialized() [InlineData(10, 100, "tga")] public void CanIdentifyImageLoadedFromBytes(int width, int height, string extension) { - using var image = Image.LoadPixelData(new Rgba32[width * height], width, height); - using var memoryStream = new MemoryStream(); - IImageFormat format = GetFormat(extension); - image.Save(memoryStream, format); - memoryStream.Position = 0; + using (var image = Image.LoadPixelData(new Rgba32[width * height], width, height)) + { + using (var memoryStream = new MemoryStream()) + { + IImageFormat format = GetFormat(extension); + image.Save(memoryStream, format); + memoryStream.Position = 0; - IImageInfo imageInfo = Image.Identify(memoryStream); + IImageInfo imageInfo = Image.Identify(memoryStream); - Assert.Equal(imageInfo.Width, width); - Assert.Equal(imageInfo.Height, height); - memoryStream.Position = 0; + Assert.Equal(imageInfo.Width, width); + Assert.Equal(imageInfo.Height, height); + memoryStream.Position = 0; - imageInfo = Image.Identify(memoryStream, out IImageFormat detectedFormat); + imageInfo = Image.Identify(memoryStream, out IImageFormat detectedFormat); - Assert.Equal(format, detectedFormat); + Assert.Equal(format, detectedFormat); + } + } } [Fact] @@ -179,11 +196,13 @@ public void IdentifyReturnsNullWithInvalidStream() { byte[] invalid = new byte[10]; - using var memoryStream = new MemoryStream(invalid); - IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format); + using (var memoryStream = new MemoryStream(invalid)) + { + IImageInfo imageInfo = Image.Identify(memoryStream, out IImageFormat format); - Assert.Null(imageInfo); - Assert.Null(format); + Assert.Null(imageInfo); + Assert.Null(format); + } } private static IImageFormat GetFormat(string format) diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs index ea6135ab10..99dc2d06da 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifDecoderTests.cs @@ -54,9 +54,11 @@ public class GifDecoderTests public void Decode_VerifyAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.DebugSaveMultiFrame(provider); - image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact); + using (Image image = provider.GetImage()) + { + image.DebugSaveMultiFrame(provider); + image.CompareToReferenceOutputMultiFrame(provider, ImageComparer.Exact); + } } [Fact] @@ -68,11 +70,15 @@ public unsafe void Decode_NonTerminatedFinalFrame() fixed (byte* data = testFile.Bytes.AsSpan(0, length)) { - using var stream = new UnmanagedMemoryStream(data, length); - var decoder = new GifDecoder(); - - using Image image = decoder.Decode(Configuration.Default, stream); - Assert.Equal((200, 200), (image.Width, image.Height)); + using (var stream = new UnmanagedMemoryStream(data, length)) + { + var decoder = new GifDecoder(); + + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + Assert.Equal((200, 200), (image.Width, image.Height)); + } + } } } @@ -81,9 +87,11 @@ public unsafe void Decode_NonTerminatedFinalFrame() public void GifDecoder_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.DebugSave(provider); - image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); + using (Image image = provider.GetImage()) + { + image.DebugSave(provider); + image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); + } } [Theory] @@ -96,10 +104,12 @@ public void Decode_VerifyRootFrameAndFrameCount(TestImageProvider image = provider.GetImage(); - Assert.Equal(expectedFrameCount, image.Frames.Count); - image.DebugSave(provider); - image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); + using (Image image = provider.GetImage()) + { + Assert.Equal(expectedFrameCount, image.Frames.Count); + image.DebugSave(provider); + image.CompareFirstFrameToReferenceOutput(ImageComparer.Exact, provider); + } } [Theory] @@ -107,8 +117,10 @@ public void Decode_VerifyRootFrameAndFrameCount(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First }); - Assert.Equal(1, image.Frames.Count); + using (Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.First })) + { + Assert.Equal(1, image.Frames.Count); + } } [Theory] @@ -116,8 +128,10 @@ public void CanDecodeJustOneFrame(TestImageProvider provider) public void CanDecodeAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All }); - Assert.True(image.Frames.Count > 1); + using (Image image = provider.GetImage(new GifDecoder { DecodingMode = FrameDecodingMode.All })) + { + Assert.True(image.Frames.Count > 1); + } } [Theory] @@ -128,21 +142,25 @@ public void CanDecodeAllFrames(TestImageProvider provider) public void DetectPixelSize(string imagePath, int expectedPixelSize) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + Assert.Equal(expectedPixelSize, Image.Identify(stream)?.PixelType?.BitsPerPixel); + } } [Fact] public void CanDecodeIntermingledImages() { - using var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes); - using var load = Image.Load(TestFile.Create(TestImages.Png.Icon).Bytes); - using var kumin2 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes); - for (int i = 0; i < kumin1.Frames.Count; i++) + using (var kumin1 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) + using (Image.Load(TestFile.Create(TestImages.Png.Icon).Bytes)) + using (var kumin2 = Image.Load(TestFile.Create(TestImages.Gif.Kumin).Bytes)) { - ImageFrame first = kumin1.Frames[i]; - ImageFrame second = kumin2.Frames[i]; - first.ComparePixelBufferTo(second.GetPixelSpan()); + for (int i = 0; i < kumin1.Frames.Count; i++) + { + ImageFrame first = kumin1.Frames[i]; + ImageFrame second = kumin2.Frames[i]; + first.ComparePixelBufferTo(second.GetPixelSpan()); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs index 711cd89908..fe1faa5aed 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs @@ -30,21 +30,25 @@ public class GifEncoderTests public void EncodeGeneratedPatterns(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var encoder = new GifEncoder + using (Image image = provider.GetImage()) { - // Use the palette quantizer without dithering to ensure results - // are consistent - Quantizer = new WebSafePaletteQuantizer(false) - }; - - // Always save as we need to compare the encoded output. - provider.Utility.SaveTestOutputFile(image, "gif", encoder); + var encoder = new GifEncoder + { + // Use the palette quantizer without dithering to ensure results + // are consistent + Quantizer = new WebSafePaletteQuantizer(false) + }; + + // Always save as we need to compare the encoded output. + provider.Utility.SaveTestOutputFile(image, "gif", encoder); + } // Compare encoded result string path = provider.Utility.GetTestOutputFileName("gif", null, true); - using var encoded = Image.Load(path); - encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif"); + using (var encoded = Image.Load(path)) + { + encoded.CompareToReferenceOutput(ValidatorComparer, provider, null, "gif"); + } } [Theory] @@ -54,16 +58,22 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new GifEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } + } } [Fact] @@ -73,15 +83,21 @@ public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten() var testFile = TestFile.Create(TestImages.Gif.Rings); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - GifMetadata metadata = output.Metadata.GetGifMetadata(); - Assert.Equal(1, metadata.Comments.Count); - Assert.Equal("ImageSharp", metadata.Comments[0]); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + GifMetadata metadata = output.Metadata.GetGifMetadata(); + Assert.Equal(1, metadata.Comments.Count); + Assert.Equal("ImageSharp", metadata.Comments[0]); + } + } + } } [Theory] @@ -89,65 +105,69 @@ public void Encode_IgnoreMetadataIsFalse_CommentsAreWritten() public void EncodeGlobalPaletteReturnsSmallerFile(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var encoder = new GifEncoder + using (Image image = provider.GetImage()) { - ColorTableMode = GifColorTableMode.Global, - Quantizer = new OctreeQuantizer(false) - }; + var encoder = new GifEncoder + { + ColorTableMode = GifColorTableMode.Global, + Quantizer = new OctreeQuantizer(false) + }; - // Always save as we need to compare the encoded output. - provider.Utility.SaveTestOutputFile(image, "gif", encoder, "global"); + // Always save as we need to compare the encoded output. + provider.Utility.SaveTestOutputFile(image, "gif", encoder, "global"); - encoder.ColorTableMode = GifColorTableMode.Local; - provider.Utility.SaveTestOutputFile(image, "gif", encoder, "local"); + encoder.ColorTableMode = GifColorTableMode.Local; + provider.Utility.SaveTestOutputFile(image, "gif", encoder, "local"); - var fileInfoGlobal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "global")); - var fileInfoLocal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "local")); + var fileInfoGlobal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "global")); + var fileInfoLocal = new FileInfo(provider.Utility.GetTestOutputFileName("gif", "local")); - Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length); + Assert.True(fileInfoGlobal.Length < fileInfoLocal.Length); + } } [Fact] public void NonMutatingEncodePreservesPaletteCount() { - using var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes); - using var outStream = new MemoryStream(); - inStream.Position = 0; - - var image = Image.Load(inStream); - GifMetadata metaData = image.Metadata.GetGifMetadata(); - GifFrameMetadata frameMetadata = image.Frames.RootFrame.Metadata.GetGifMetadata(); - GifColorTableMode colorMode = metaData.ColorTableMode; - var encoder = new GifEncoder + using (var inStream = new MemoryStream(TestFile.Create(TestImages.Gif.Leo).Bytes)) + using (var outStream = new MemoryStream()) { - ColorTableMode = colorMode, - Quantizer = new OctreeQuantizer(frameMetadata.ColorTableLength) - }; + inStream.Position = 0; - image.Save(outStream, encoder); - outStream.Position = 0; + var image = Image.Load(inStream); + GifMetadata metaData = image.Metadata.GetGifMetadata(); + GifFrameMetadata frameMetadata = image.Frames.RootFrame.Metadata.GetGifMetadata(); + GifColorTableMode colorMode = metaData.ColorTableMode; + var encoder = new GifEncoder + { + ColorTableMode = colorMode, + Quantizer = new OctreeQuantizer(frameMetadata.ColorTableLength) + }; - outStream.Position = 0; - var clone = Image.Load(outStream); + image.Save(outStream, encoder); + outStream.Position = 0; - GifMetadata cloneMetadata = clone.Metadata.GetGifMetadata(); - Assert.Equal(metaData.ColorTableMode, cloneMetadata.ColorTableMode); + outStream.Position = 0; + var clone = Image.Load(outStream); - // Gifiddle and Cyotek GifInfo say this image has 64 colors. - Assert.Equal(64, frameMetadata.ColorTableLength); + GifMetadata cloneMetadata = clone.Metadata.GetGifMetadata(); + Assert.Equal(metaData.ColorTableMode, cloneMetadata.ColorTableMode); - for (int i = 0; i < image.Frames.Count; i++) - { - GifFrameMetadata ifm = image.Frames[i].Metadata.GetGifMetadata(); - GifFrameMetadata cifm = clone.Frames[i].Metadata.GetGifMetadata(); + // Gifiddle and Cyotek GifInfo say this image has 64 colors. + Assert.Equal(64, frameMetadata.ColorTableLength); - Assert.Equal(ifm.ColorTableLength, cifm.ColorTableLength); - Assert.Equal(ifm.FrameDelay, cifm.FrameDelay); - } + for (int i = 0; i < image.Frames.Count; i++) + { + GifFrameMetadata ifm = image.Frames[i].Metadata.GetGifMetadata(); + GifFrameMetadata cifm = clone.Frames[i].Metadata.GetGifMetadata(); + + Assert.Equal(ifm.ColorTableLength, cifm.ColorTableLength); + Assert.Equal(ifm.FrameDelay, cifm.FrameDelay); + } - image.Dispose(); - clone.Dispose(); + image.Dispose(); + clone.Dispose(); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs index 578dca0ce0..ddb5608daf 100644 --- a/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Gif/GifMetadataTests.cs @@ -65,10 +65,12 @@ public void Decode_IgnoreMetadataIsFalse_CommentsAreRead() var testFile = TestFile.Create(TestImages.Gif.Rings); - using Image image = testFile.CreateRgba32Image(options); - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(1, metadata.Comments.Count); - Assert.Equal("ImageSharp", metadata.Comments[0]); + using (Image image = testFile.CreateRgba32Image(options)) + { + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(1, metadata.Comments.Count); + Assert.Equal("ImageSharp", metadata.Comments[0]); + } } [Fact] @@ -81,9 +83,11 @@ public void Decode_IgnoreMetadataIsTrue_CommentsAreIgnored() var testFile = TestFile.Create(TestImages.Gif.Rings); - using Image image = testFile.CreateRgba32Image(options); - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(0, metadata.Comments.Count); + using (Image image = testFile.CreateRgba32Image(options)) + { + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(0, metadata.Comments.Count); + } } [Fact] @@ -92,11 +96,13 @@ public void Decode_CanDecodeLargeTextComment() var options = new GifDecoder(); var testFile = TestFile.Create(TestImages.Gif.LargeComment); - using Image image = testFile.CreateRgba32Image(options); - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(2, metadata.Comments.Count); - Assert.Equal(new string('c', 349), metadata.Comments[0]); - Assert.Equal("ImageSharp", metadata.Comments[1]); + using (Image image = testFile.CreateRgba32Image(options)) + { + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(2, metadata.Comments.Count); + Assert.Equal(new string('c', 349), metadata.Comments[0]); + Assert.Equal("ImageSharp", metadata.Comments[1]); + } } [Fact] @@ -105,16 +111,20 @@ public void Encode_PreservesTextData() var decoder = new GifDecoder(); var testFile = TestFile.Create(TestImages.Gif.LargeComment); - using Image input = testFile.CreateRgba32Image(decoder); - using var memoryStream = new MemoryStream(); - input.Save(memoryStream, new GifEncoder()); - memoryStream.Position = 0; + using (Image input = testFile.CreateRgba32Image(decoder)) + using (var memoryStream = new MemoryStream()) + { + input.Save(memoryStream, new GifEncoder()); + memoryStream.Position = 0; - using Image image = decoder.Decode(Configuration.Default, memoryStream); - GifMetadata metadata = image.Metadata.GetGifMetadata(); - Assert.Equal(2, metadata.Comments.Count); - Assert.Equal(new string('c', 349), metadata.Comments[0]); - Assert.Equal("ImageSharp", metadata.Comments[1]); + using (Image image = decoder.Decode(Configuration.Default, memoryStream)) + { + GifMetadata metadata = image.Metadata.GetGifMetadata(); + Assert.Equal(2, metadata.Comments.Count); + Assert.Equal(new string('c', 349), metadata.Comments[0]); + Assert.Equal("ImageSharp", metadata.Comments[1]); + } + } } [Theory] @@ -122,13 +132,15 @@ public void Encode_PreservesTextData() public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new GifDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new GifDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } } [Theory] @@ -136,13 +148,17 @@ public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolut public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new GifDecoder(); - using Image image = decoder.Decode(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new GifDecoder(); + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } } [Theory] diff --git a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs index 54030955ae..d011a63301 100644 --- a/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs +++ b/tests/ImageSharp.Tests/Formats/ImageFormatManagerTests.cs @@ -128,10 +128,14 @@ public void AddFormatCallsConfig() public void DetectFormatAllocatesCleanBuffer() { byte[] jpegImage; - using var buffer = new MemoryStream(); - using var image = new Image(100, 100); - image.SaveAsJpeg(buffer); - jpegImage = buffer.ToArray(); + using (var buffer = new MemoryStream()) + { + using (var image = new Image(100, 100)) + { + image.SaveAsJpeg(buffer); + jpegImage = buffer.ToArray(); + } + } byte[] invalidImage = { 1, 2, 3 }; diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs index aa85ae1b23..ea2fc7ab80 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Block8x8FTests.CopyToBufferArea.cs @@ -41,17 +41,19 @@ public void Copy1x1Scale() { Block8x8F block = CreateRandomFloatBlock(0, 100); - using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(20, 20, AllocationOptions.Clean); - BufferArea area = buffer.GetArea(5, 10, 8, 8); - block.Copy1x1Scale(area); + using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(20, 20, AllocationOptions.Clean)) + { + BufferArea area = buffer.GetArea(5, 10, 8, 8); + block.Copy1x1Scale(area); - Assert.Equal(block[0, 0], buffer[5, 10]); - Assert.Equal(block[1, 0], buffer[6, 10]); - Assert.Equal(block[0, 1], buffer[5, 11]); - Assert.Equal(block[0, 7], buffer[5, 17]); - Assert.Equal(block[63], buffer[12, 17]); + Assert.Equal(block[0, 0], buffer[5, 10]); + Assert.Equal(block[1, 0], buffer[6, 10]); + Assert.Equal(block[0, 1], buffer[5, 11]); + Assert.Equal(block[0, 7], buffer[5, 17]); + Assert.Equal(block[63], buffer[12, 17]); - VerifyAllZeroOutsideSubArea(buffer, 5, 10); + VerifyAllZeroOutsideSubArea(buffer, 5, 10); + } } [Theory] @@ -67,25 +69,27 @@ public void CopyTo(int horizontalFactor, int verticalFactor) var start = new Point(50, 50); - using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(100, 100, AllocationOptions.Clean); - BufferArea area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor); - block.CopyTo(area, horizontalFactor, verticalFactor); - - for (int y = 0; y < 8 * verticalFactor; y++) + using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(100, 100, AllocationOptions.Clean)) { - for (int x = 0; x < 8 * horizontalFactor; x++) + BufferArea area = buffer.GetArea(start.X, start.Y, 8 * horizontalFactor, 8 * verticalFactor); + block.CopyTo(area, horizontalFactor, verticalFactor); + + for (int y = 0; y < 8 * verticalFactor; y++) { - int yy = y / verticalFactor; - int xx = x / horizontalFactor; + for (int x = 0; x < 8 * horizontalFactor; x++) + { + int yy = y / verticalFactor; + int xx = x / horizontalFactor; - float expected = block[xx, yy]; - float actual = area[x, y]; + float expected = block[xx, yy]; + float actual = area[x, y]; - Assert.Equal(expected, actual); + Assert.Equal(expected, actual); + } } - } - VerifyAllZeroOutsideSubArea(buffer, start.X, start.Y, horizontalFactor, verticalFactor); + VerifyAllZeroOutsideSubArea(buffer, start.X, start.Y, horizontalFactor, verticalFactor); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs b/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs index 4fb7757097..7c42af5961 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/GenericBlock8x8Tests.cs @@ -38,21 +38,23 @@ public static Image CreateTestImage() public void LoadAndStretchCorners_FromOrigo(TestImageProvider provider) where TPixel : struct, IPixel { - using Image s = provider.GetImage(); - var d = default(GenericBlock8x8); - d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0); - - TPixel a = s.Frames.RootFrame[0, 0]; - TPixel b = d[0, 0]; - - Assert.Equal(s[0, 0], d[0, 0]); - Assert.Equal(s[1, 0], d[1, 0]); - Assert.Equal(s[7, 0], d[7, 0]); - Assert.Equal(s[0, 1], d[0, 1]); - Assert.Equal(s[1, 1], d[1, 1]); - Assert.Equal(s[7, 0], d[7, 0]); - Assert.Equal(s[0, 7], d[0, 7]); - Assert.Equal(s[7, 7], d[7, 7]); + using (Image s = provider.GetImage()) + { + var d = default(GenericBlock8x8); + d.LoadAndStretchEdges(s.Frames.RootFrame, 0, 0); + + TPixel a = s.Frames.RootFrame[0, 0]; + TPixel b = d[0, 0]; + + Assert.Equal(s[0, 0], d[0, 0]); + Assert.Equal(s[1, 0], d[1, 0]); + Assert.Equal(s[7, 0], d[7, 0]); + Assert.Equal(s[0, 1], d[0, 1]); + Assert.Equal(s[1, 1], d[1, 1]); + Assert.Equal(s[7, 0], d[7, 0]); + Assert.Equal(s[0, 7], d[0, 7]); + Assert.Equal(s[7, 7], d[7, 7]); + } } [Theory] @@ -60,36 +62,38 @@ public void LoadAndStretchCorners_FromOrigo(TestImageProvider pr public void LoadAndStretchCorners_WithOffset(TestImageProvider provider) where TPixel : struct, IPixel { - using Image s = provider.GetImage(); - var d = default(GenericBlock8x8); - d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7); + using (Image s = provider.GetImage()) + { + var d = default(GenericBlock8x8); + d.LoadAndStretchEdges(s.Frames.RootFrame, 6, 7); - Assert.Equal(s[6, 7], d[0, 0]); - Assert.Equal(s[6, 8], d[0, 1]); - Assert.Equal(s[7, 8], d[1, 1]); + Assert.Equal(s[6, 7], d[0, 0]); + Assert.Equal(s[6, 8], d[0, 1]); + Assert.Equal(s[7, 8], d[1, 1]); - Assert.Equal(s[6, 9], d[0, 2]); - Assert.Equal(s[6, 9], d[0, 3]); - Assert.Equal(s[6, 9], d[0, 7]); + Assert.Equal(s[6, 9], d[0, 2]); + Assert.Equal(s[6, 9], d[0, 3]); + Assert.Equal(s[6, 9], d[0, 7]); - Assert.Equal(s[7, 9], d[1, 2]); - Assert.Equal(s[7, 9], d[1, 3]); - Assert.Equal(s[7, 9], d[1, 7]); + Assert.Equal(s[7, 9], d[1, 2]); + Assert.Equal(s[7, 9], d[1, 3]); + Assert.Equal(s[7, 9], d[1, 7]); - Assert.Equal(s[9, 9], d[3, 2]); - Assert.Equal(s[9, 9], d[3, 3]); - Assert.Equal(s[9, 9], d[3, 7]); + Assert.Equal(s[9, 9], d[3, 2]); + Assert.Equal(s[9, 9], d[3, 3]); + Assert.Equal(s[9, 9], d[3, 7]); - Assert.Equal(s[9, 7], d[3, 0]); - Assert.Equal(s[9, 7], d[4, 0]); - Assert.Equal(s[9, 7], d[7, 0]); + Assert.Equal(s[9, 7], d[3, 0]); + Assert.Equal(s[9, 7], d[4, 0]); + Assert.Equal(s[9, 7], d[7, 0]); - Assert.Equal(s[9, 9], d[3, 2]); - Assert.Equal(s[9, 9], d[4, 2]); - Assert.Equal(s[9, 9], d[7, 2]); + Assert.Equal(s[9, 9], d[3, 2]); + Assert.Equal(s[9, 9], d[4, 2]); + Assert.Equal(s[9, 9], d[7, 2]); - Assert.Equal(s[9, 9], d[4, 3]); - Assert.Equal(s[9, 9], d[7, 7]); + Assert.Equal(s[9, 9], d[4, 3]); + Assert.Equal(s[9, 9], d[7, 7]); + } } [Fact] diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs index 8bebd73043..c2fc320aff 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.Metadata.cs @@ -79,13 +79,17 @@ public void MetadataIsParsedCorrectly( public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new JpegDecoder(); - using Image image = decoder.Decode(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new JpegDecoder(); + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } } [Theory] @@ -93,13 +97,15 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new JpegDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new JpegDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } } [Theory] @@ -107,11 +113,13 @@ public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolut public void Identify_VerifyQuality(string imagePath, int quality) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new JpegDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - JpegMetadata meta = image.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new JpegDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + JpegMetadata meta = image.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); + } } [Theory] @@ -119,22 +127,28 @@ public void Identify_VerifyQuality(string imagePath, int quality) public void Decode_VerifyQuality(string imagePath, int quality) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new JpegDecoder(); - using Image image = decoder.Decode(Configuration.Default, stream); - JpegMetadata meta = image.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new JpegDecoder(); + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + JpegMetadata meta = image.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); + } + } } private static void TestImageInfo(string imagePath, IImageDecoder decoder, bool useIdentify, Action test) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - IImageInfo imageInfo = useIdentify + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + IImageInfo imageInfo = useIdentify ? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream) : decoder.Decode(Configuration.Default, stream); - test(imageInfo); + test(imageInfo); + } } private static void TestMetadataImpl( @@ -201,16 +215,18 @@ public void IgnoreMetadata_ControlsWhetherMetadataIsParsed(bool ignoreMetadata) // Snake.jpg has both Exif and ICC profiles defined: var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Snake); - using Image image = testFile.CreateRgba32Image(decoder); - if (ignoreMetadata) + using (Image image = testFile.CreateRgba32Image(decoder)) { - Assert.Null(image.Metadata.ExifProfile); - Assert.Null(image.Metadata.IccProfile); - } - else - { - Assert.NotNull(image.Metadata.ExifProfile); - Assert.NotNull(image.Metadata.IccProfile); + if (ignoreMetadata) + { + Assert.Null(image.Metadata.ExifProfile); + Assert.Null(image.Metadata.IccProfile); + } + else + { + Assert.NotNull(image.Metadata.ExifProfile); + Assert.NotNull(image.Metadata.IccProfile); + } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs index 4d8b512c8e..09e98b5c4b 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegDecoderTests.cs @@ -76,14 +76,16 @@ public JpegDecoderTests(ITestOutputHelper output) public void ParseStream_BasicPropertiesAreCorrect() { byte[] bytes = TestFile.Create(TestImages.Jpeg.Progressive.Progress).Bytes; - using var ms = new MemoryStream(bytes); - var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); - decoder.ParseStream(ms); - - // I don't know why these numbers are different. All I know is that the decoder works - // and spectral data is exactly correct also. - // VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31); - VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31); + using (var ms = new MemoryStream(bytes)) + { + var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); + decoder.ParseStream(ms); + + // I don't know why these numbers are different. All I know is that the decoder works + // and spectral data is exactly correct also. + // VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 43, 61, 22, 31, 22, 31); + VerifyJpeg.VerifyComponentSizes3(decoder.Frame.Components, 44, 62, 22, 31, 22, 31); + } } public const string DecodeBaselineJpegOutputName = "DecodeBaselineJpeg"; @@ -129,14 +131,16 @@ public void ValidateProgressivePdfJsOutput( var comparer = ImageComparer.Tolerant(0, 0); - using Image expectedImage = provider.GetReferenceOutputImage(appendPixelTypeToFileName: false); - using var pdfJsOriginalResult = Image.Load(pdfJsOriginalResultPath); - using var pdfJsPortResult = Image.Load(sourceBytes, JpegDecoder); - ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult); - ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult); + using (Image expectedImage = provider.GetReferenceOutputImage(appendPixelTypeToFileName: false)) + using (var pdfJsOriginalResult = Image.Load(pdfJsOriginalResultPath)) + using (var pdfJsPortResult = Image.Load(sourceBytes, JpegDecoder)) + { + ImageSimilarityReport originalReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsOriginalResult); + ImageSimilarityReport portReport = comparer.CompareImagesOrFrames(expectedImage, pdfJsPortResult); - this.Output.WriteLine($"Difference for PDF.js ORIGINAL: {originalReport.DifferencePercentageString}"); - this.Output.WriteLine($"Difference for PORT: {portReport.DifferencePercentageString}"); + this.Output.WriteLine($"Difference for PDF.js ORIGINAL: {originalReport.DifferencePercentageString}"); + this.Output.WriteLine($"Difference for PORT: {portReport.DifferencePercentageString}"); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs index 01a428b62b..f7acb9fca5 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegEncoderTests.cs @@ -47,14 +47,20 @@ public void Encode_PreserveQuality(string imagePath, int quality) var options = new JpegEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - JpegMetadata meta = output.Metadata.GetJpegMetadata(); - Assert.Equal(quality, meta.Quality); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + JpegMetadata meta = output.Metadata.GetJpegMetadata(); + Assert.Equal(quality, meta.Quality); + } + } + } } [Theory] @@ -102,21 +108,22 @@ private static void TestJpegEncoderCore( int quality = 100) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - - // There is no alpha in Jpeg! - image.Mutate(c => c.MakeOpaque()); - - var encoder = new JpegEncoder + using (Image image = provider.GetImage()) { - Subsample = subsample, - Quality = quality - }; - string info = $"{subsample}-Q{quality}"; - ImageComparer comparer = GetComparer(quality, subsample); + // There is no alpha in Jpeg! + image.Mutate(c => c.MakeOpaque()); - // Does DebugSave & load reference CompareToReferenceInput(): - image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png"); + var encoder = new JpegEncoder + { + Subsample = subsample, + Quality = quality + }; + string info = $"{subsample}-Q{quality}"; + ImageComparer comparer = GetComparer(quality, subsample); + + // Does DebugSave & load reference CompareToReferenceInput(): + image.VerifyEncoder(provider, "jpeg", info, encoder, comparer, referenceImageExtension: "png"); + } } [Fact] @@ -129,15 +136,17 @@ public void Quality_0_And_1_Are_Identical() var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); - using Image input = testFile.CreateRgba32Image(); - using var memStream0 = new MemoryStream(); - using var memStream1 = new MemoryStream(); - input.SaveAsJpeg(memStream0, options); + using (Image input = testFile.CreateRgba32Image()) + using (var memStream0 = new MemoryStream()) + using (var memStream1 = new MemoryStream()) + { + input.SaveAsJpeg(memStream0, options); - options.Quality = 1; - input.SaveAsJpeg(memStream1, options); + options.Quality = 1; + input.SaveAsJpeg(memStream1, options); - Assert.Equal(memStream0.ToArray(), memStream1.ToArray()); + Assert.Equal(memStream0.ToArray(), memStream1.ToArray()); + } } [Fact] @@ -150,15 +159,17 @@ public void Quality_0_And_100_Are_Not_Identical() var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Calliphora); - using Image input = testFile.CreateRgba32Image(); - using var memStream0 = new MemoryStream(); - using var memStream1 = new MemoryStream(); - input.SaveAsJpeg(memStream0, options); + using (Image input = testFile.CreateRgba32Image()) + using (var memStream0 = new MemoryStream()) + using (var memStream1 = new MemoryStream()) + { + input.SaveAsJpeg(memStream0, options); - options.Quality = 100; - input.SaveAsJpeg(memStream1, options); + options.Quality = 100; + input.SaveAsJpeg(memStream1, options); - Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray()); + Assert.NotEqual(memStream0.ToArray(), memStream1.ToArray()); + } } [Theory] @@ -168,16 +179,22 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new JpegEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs index e478621580..86128e0020 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegImagePostProcessorTests.cs @@ -34,8 +34,10 @@ public JpegImagePostProcessorTests(ITestOutputHelper output) private static void SaveBuffer(JpegComponentPostProcessor cp, TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f); - image.DebugSave(provider, $"-C{cp.Component.Index}-"); + using (Image image = cp.ColorBuffer.ToGrayscaleImage(1f / 255f)) + { + image.DebugSave(provider, $"-C{cp.Component.Index}-"); + } } [Theory] @@ -45,16 +47,18 @@ public void DoProcessorStep(TestImageProvider provider) where TPixel : struct, IPixel { string imageFile = provider.SourceFileOrDescription; - using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); - using var pp = new JpegImagePostProcessor(Configuration.Default, decoder); - using var imageFrame = new ImageFrame(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight); - pp.DoPostProcessorStep(imageFrame); + using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) + using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) + using (var imageFrame = new ImageFrame(Configuration.Default, decoder.ImageWidth, decoder.ImageHeight)) + { + pp.DoPostProcessorStep(imageFrame); - JpegComponentPostProcessor[] cp = pp.ComponentProcessors; + JpegComponentPostProcessor[] cp = pp.ComponentProcessors; - SaveBuffer(cp[0], provider); - SaveBuffer(cp[1], provider); - SaveBuffer(cp[2], provider); + SaveBuffer(cp[0], provider); + SaveBuffer(cp[1], provider); + SaveBuffer(cp[2], provider); + } } [Theory] @@ -63,26 +67,30 @@ public void PostProcess(TestImageProvider provider) where TPixel : struct, IPixel { string imageFile = provider.SourceFileOrDescription; - using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); - using var pp = new JpegImagePostProcessor(Configuration.Default, decoder); - using var image = new Image(decoder.ImageWidth, decoder.ImageHeight); - pp.PostProcess(image.Frames.RootFrame); + using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) + using (var pp = new JpegImagePostProcessor(Configuration.Default, decoder)) + using (var image = new Image(decoder.ImageWidth, decoder.ImageHeight)) + { + pp.PostProcess(image.Frames.RootFrame); - image.DebugSave(provider); + image.DebugSave(provider); - ImagingTestCaseUtility testUtil = provider.Utility; - testUtil.TestGroupName = nameof(JpegDecoderTests); - testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName; + ImagingTestCaseUtility testUtil = provider.Utility; + testUtil.TestGroupName = nameof(JpegDecoderTests); + testUtil.TestName = JpegDecoderTests.DecodeBaselineJpegOutputName; - using Image referenceImage = - provider.GetReferenceOutputImage(appendPixelTypeToFileName: false); - ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image); + using (Image referenceImage = + provider.GetReferenceOutputImage(appendPixelTypeToFileName: false)) + { + ImageSimilarityReport report = ImageComparer.Exact.CompareImagesOrFrames(referenceImage, image); - this.Output.WriteLine($"*** {imageFile} ***"); - this.Output.WriteLine($"Difference: {report.DifferencePercentageString}"); + this.Output.WriteLine($"*** {imageFile} ***"); + this.Output.WriteLine($"Difference: {report.DifferencePercentageString}"); - // ReSharper disable once PossibleInvalidOperationException - Assert.True(report.TotalNormalizedDifference.Value < 0.005f); + // ReSharper disable once PossibleInvalidOperationException + Assert.True(report.TotalNormalizedDifference.Value < 0.005f); + } + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs index c42483ca40..6e04610d5a 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/ParseStreamTests.cs @@ -31,24 +31,28 @@ public void ColorSpace_IsDeducedCorrectly(string imageFile, object expectedColor { var expectedColorSpace = (JpegColorSpace)expectedColorSpaceValue; - using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); - Assert.Equal(expectedColorSpace, decoder.ColorSpace); + using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) + { + Assert.Equal(expectedColorSpace, decoder.ColorSpace); + } } [Fact] public void ComponentScalingIsCorrect_1ChannelJpeg() { - using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400); - Assert.Equal(1, decoder.ComponentCount); - Assert.Equal(1, decoder.Components.Length); + using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(TestImages.Jpeg.Baseline.Jpeg400)) + { + Assert.Equal(1, decoder.ComponentCount); + Assert.Equal(1, decoder.Components.Length); - Size expectedSizeInBlocks = decoder.ImageSizeInPixels.DivideRoundUp(8); + Size expectedSizeInBlocks = decoder.ImageSizeInPixels.DivideRoundUp(8); - Assert.Equal(expectedSizeInBlocks, decoder.ImageSizeInMCU); + Assert.Equal(expectedSizeInBlocks, decoder.ImageSizeInMCU); - var uniform1 = new Size(1, 1); - JpegComponent c0 = decoder.Components[0]; - VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1); + var uniform1 = new Size(1, 1); + JpegComponent c0 = decoder.Components[0]; + VerifyJpeg.VerifyComponent(c0, expectedSizeInBlocks, uniform1, uniform1); + } } [Theory] @@ -99,30 +103,32 @@ public void ComponentScalingIsCorrect_MultiChannelJpeg( var fLuma = (Size)expectedLumaFactors; var fChroma = (Size)expectedChromaFactors; - using JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile); - Assert.Equal(componentCount, decoder.ComponentCount); - Assert.Equal(componentCount, decoder.Components.Length); + using (JpegDecoderCore decoder = JpegFixture.ParseJpegStream(imageFile)) + { + Assert.Equal(componentCount, decoder.ComponentCount); + Assert.Equal(componentCount, decoder.Components.Length); - JpegComponent c0 = decoder.Components[0]; - JpegComponent c1 = decoder.Components[1]; - JpegComponent c2 = decoder.Components[2]; + JpegComponent c0 = decoder.Components[0]; + JpegComponent c1 = decoder.Components[1]; + JpegComponent c2 = decoder.Components[2]; - var uniform1 = new Size(1, 1); + var uniform1 = new Size(1, 1); - Size expectedLumaSizeInBlocks = decoder.ImageSizeInMCU.MultiplyBy(fLuma); + Size expectedLumaSizeInBlocks = decoder.ImageSizeInMCU.MultiplyBy(fLuma); - Size divisor = fLuma.DivideBy(fChroma); + Size divisor = fLuma.DivideBy(fChroma); - Size expectedChromaSizeInBlocks = expectedLumaSizeInBlocks.DivideRoundUp(divisor); + Size expectedChromaSizeInBlocks = expectedLumaSizeInBlocks.DivideRoundUp(divisor); - VerifyJpeg.VerifyComponent(c0, expectedLumaSizeInBlocks, fLuma, uniform1); - VerifyJpeg.VerifyComponent(c1, expectedChromaSizeInBlocks, fChroma, divisor); - VerifyJpeg.VerifyComponent(c2, expectedChromaSizeInBlocks, fChroma, divisor); + VerifyJpeg.VerifyComponent(c0, expectedLumaSizeInBlocks, fLuma, uniform1); + VerifyJpeg.VerifyComponent(c1, expectedChromaSizeInBlocks, fChroma, divisor); + VerifyJpeg.VerifyComponent(c2, expectedChromaSizeInBlocks, fChroma, divisor); - if (componentCount == 4) - { - JpegComponent c3 = decoder.Components[2]; - VerifyJpeg.VerifyComponent(c3, expectedLumaSizeInBlocks, fLuma, uniform1); + if (componentCount == 4) + { + JpegComponent c3 = decoder.Components[2]; + VerifyJpeg.VerifyComponent(c3, expectedLumaSizeInBlocks, fLuma, uniform1); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs index d6e69925b2..8d7dda2fed 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/SpectralJpegTests.cs @@ -50,11 +50,13 @@ public void Decoder_ParseStream_SaveSpectralResult(TestImageProvider(TestImageProvider provider byte[] sourceBytes = TestFile.Create(provider.SourceFileOrDescription).Bytes; - using var ms = new MemoryStream(sourceBytes); - decoder.ParseStream(ms); - var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); + using (var ms = new MemoryStream(sourceBytes)) + { + decoder.ParseStream(ms); + var imageSharpData = LibJpegTools.SpectralData.LoadFromImageSharpDecoder(decoder); - this.VerifySpectralCorrectnessImpl(provider, imageSharpData); + this.VerifySpectralCorrectnessImpl(provider, imageSharpData); + } } private void VerifySpectralCorrectnessImpl( diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs index 9be449f122..b7cf6a8406 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/JpegFixture.cs @@ -192,10 +192,12 @@ internal void CompareBlocks(Span a, Span b, float tolerance) internal static JpegDecoderCore ParseJpegStream(string testFileName, bool metaDataOnly = false) { byte[] bytes = TestFile.Create(testFileName).Bytes; - using var ms = new MemoryStream(bytes); - var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); - decoder.ParseStream(ms, metaDataOnly); - return decoder; + using (var ms = new MemoryStream(bytes)) + { + var decoder = new JpegDecoderCore(Configuration.Default, new JpegDecoder()); + decoder.ParseStream(ms, metaDataOnly); + return decoder; + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs index e1d1e7f5d5..826335b652 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/LibJpegTools.cs @@ -98,38 +98,40 @@ public static SpectralData ExtractSpectralData(string inputFile) { RunDumpJpegCoeffsTool(testFile.FullPath, coeffFileFullPath); - using var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open); - using var rdr = new BinaryReader(dumpStream); - int componentCount = rdr.ReadInt16(); - var result = new ComponentData[componentCount]; - - for (int i = 0; i < componentCount; i++) + using (var dumpStream = new FileStream(coeffFileFullPath, FileMode.Open)) + using (var rdr = new BinaryReader(dumpStream)) { - int widthInBlocks = rdr.ReadInt16(); - int heightInBlocks = rdr.ReadInt16(); - var resultComponent = new ComponentData(widthInBlocks, heightInBlocks, i); - result[i] = resultComponent; - } + int componentCount = rdr.ReadInt16(); + var result = new ComponentData[componentCount]; - var buffer = new byte[64 * sizeof(short)]; + for (int i = 0; i < componentCount; i++) + { + int widthInBlocks = rdr.ReadInt16(); + int heightInBlocks = rdr.ReadInt16(); + var resultComponent = new ComponentData(widthInBlocks, heightInBlocks, i); + result[i] = resultComponent; + } - for (int i = 0; i < result.Length; i++) - { - ComponentData c = result[i]; + var buffer = new byte[64 * sizeof(short)]; - for (int y = 0; y < c.HeightInBlocks; y++) + for (int i = 0; i < result.Length; i++) { - for (int x = 0; x < c.WidthInBlocks; x++) + ComponentData c = result[i]; + + for (int y = 0; y < c.HeightInBlocks; y++) { - rdr.Read(buffer, 0, buffer.Length); + for (int x = 0; x < c.WidthInBlocks; x++) + { + rdr.Read(buffer, 0, buffer.Length); - short[] block = MemoryMarshal.Cast(buffer.AsSpan()).ToArray(); - c.MakeBlock(block, y, x); + short[] block = MemoryMarshal.Cast(buffer.AsSpan()).ToArray(); + c.MakeBlock(block, y, x); + } } } - } - return new SpectralData(result); + return new SpectralData(result); + } } finally { diff --git a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs index 27431a923b..9f22a7cb84 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/Utils/VerifyJpeg.cs @@ -58,9 +58,11 @@ internal static void SaveSpectralImage( output?.WriteLine("Min: " + comp.MinVal); output?.WriteLine("Max: " + comp.MaxVal); - using Image image = comp.CreateGrayScaleImage(); - string details = $"C{comp.Index}"; - image.DebugSave(provider, details, appendPixelTypeToFileName: false); + using (Image image = comp.CreateGrayScaleImage()) + { + string details = $"C{comp.Index}"; + image.DebugSave(provider, details, appendPixelTypeToFileName: false); + } } Image fullImage = data.TryCreateRGBSpectralImage(); diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs index ba93d6a7e0..ee4001c203 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs @@ -63,17 +63,19 @@ public void Decode_IncorrectCRCForCriticalChunk_ExceptionIsThrown(uint chunkType { string chunkName = GetChunkTypeName(chunkType); - using var memStream = new MemoryStream(); - WriteHeaderChunk(memStream); - WriteChunk(memStream, chunkName); - WriteDataChunk(memStream); + using (var memStream = new MemoryStream()) + { + WriteHeaderChunk(memStream); + WriteChunk(memStream, chunkName); + WriteDataChunk(memStream); - var decoder = new PngDecoder(); + var decoder = new PngDecoder(); - ImageFormatException exception = - Assert.Throws(() => decoder.Decode(null, memStream)); + ImageFormatException exception = + Assert.Throws(() => decoder.Decode(null, memStream)); - 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) diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs index a749b8af9d..a88962e5f8 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs @@ -87,20 +87,22 @@ public partial class PngDecoderTests public void Decode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - - // We don't have another x-plat reference decoder that can be compared for this image. - if (provider.Utility.SourceFileOrDescription == TestImages.Png.Bad.Issue1047_BadEndChunk) + using (Image image = provider.GetImage(new PngDecoder())) { - if (TestEnvironment.IsWindows) + image.DebugSave(provider); + + // We don't have another x-plat reference decoder that can be compared for this image. + if (provider.Utility.SourceFileOrDescription == TestImages.Png.Bad.Issue1047_BadEndChunk) { - image.CompareToOriginal(provider, ImageComparer.Exact, (IImageDecoder)SystemDrawingReferenceDecoder.Instance); + if (TestEnvironment.IsWindows) + { + image.CompareToOriginal(provider, ImageComparer.Exact, (IImageDecoder)SystemDrawingReferenceDecoder.Instance); + } + } + else + { + image.CompareToOriginal(provider, ImageComparer.Exact); } - } - else - { - image.CompareToOriginal(provider, ImageComparer.Exact); } } @@ -109,9 +111,11 @@ public void Decode(TestImageProvider provider) public void Decode_Interlaced_ImageIsCorrect(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -119,9 +123,11 @@ public void Decode_Interlaced_ImageIsCorrect(TestImageProvider p public void Decode_48Bpp(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -129,9 +135,11 @@ public void Decode_48Bpp(TestImageProvider provider) public void Decode_64Bpp(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -139,9 +147,11 @@ public void Decode_64Bpp(TestImageProvider provider) public void Decoder_L8bitInterlaced(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -149,9 +159,11 @@ public void Decoder_L8bitInterlaced(TestImageProvider provider) public void Decode_L16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -159,9 +171,11 @@ public void Decode_L16Bit(TestImageProvider provider) public void Decode_GrayAlpha16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -169,9 +183,11 @@ public void Decode_GrayAlpha16Bit(TestImageProvider provider) public void Decoder_CanDecodeGrey8bitWithAlpha(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -179,9 +195,11 @@ public void Decoder_CanDecodeGrey8bitWithAlpha(TestImageProvider public void Decoder_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } } [Theory] @@ -195,8 +213,10 @@ public void Decoder_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) System.Exception ex = Record.Exception( () => { - using Image image = provider.GetImage(new PngDecoder()); - image.DebugSave(provider); - image.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage(new PngDecoder())) + { + image.DebugSave(provider); + image.CompareToOriginal(provider, ImageComparer.Exact); + } }); Assert.Null(ex); } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs index 4562311b0a..f5b06eb6c3 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngEncoderTests.cs @@ -278,24 +278,26 @@ public void PaletteColorType_WuQuantizer(TestImageProvider provi public void WritesFileMarker(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using var ms = new MemoryStream(); - image.Save(ms, new PngEncoder()); - - byte[] data = ms.ToArray().Take(8).ToArray(); - byte[] expected = + using (Image image = provider.GetImage()) + using (var ms = new MemoryStream()) { - 0x89, // Set the high bit. - 0x50, // P - 0x4E, // N - 0x47, // G - 0x0D, // Line ending CRLF - 0x0A, // Line ending CRLF - 0x1A, // EOF - 0x0A // LF - }; - - Assert.Equal(expected, data); + image.Save(ms, new PngEncoder()); + + byte[] data = ms.ToArray().Take(8).ToArray(); + byte[] expected = + { + 0x89, // Set the high bit. + 0x50, // P + 0x4E, // N + 0x47, // G + 0x0D, // Line ending CRLF + 0x0A, // Line ending CRLF + 0x1A, // EOF + 0x0A // LF + }; + + Assert.Equal(expected, data); + } } [Theory] @@ -305,16 +307,22 @@ public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolut var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - - memStream.Position = 0; - using var output = Image.Load(memStream); - ImageMetadata meta = output.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + ImageMetadata meta = output.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } + } } [Theory] @@ -324,15 +332,21 @@ public void Encode_PreserveBits(string imagePath, PngBitDepth pngBitDepth) var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); - memStream.Position = 0; - using var output = Image.Load(memStream); - PngMetadata meta = output.Metadata.GetPngMetadata(); + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + PngMetadata meta = output.Metadata.GetPngMetadata(); - Assert.Equal(pngBitDepth, meta.BitDepth); + Assert.Equal(pngBitDepth, meta.BitDepth); + } + } + } } [Theory] @@ -342,45 +356,51 @@ public void Encode_PreserveTrns(string imagePath, PngBitDepth pngBitDepth, PngCo var options = new PngEncoder(); var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - PngMetadata inMeta = input.Metadata.GetPngMetadata(); - Assert.True(inMeta.HasTransparency); - - using var memStream = new MemoryStream(); - input.Save(memStream, options); - memStream.Position = 0; - using var output = Image.Load(memStream); - PngMetadata outMeta = output.Metadata.GetPngMetadata(); - Assert.True(outMeta.HasTransparency); - - switch (pngColorType) + using (Image input = testFile.CreateRgba32Image()) { - case PngColorType.Grayscale: - if (pngBitDepth.Equals(PngBitDepth.Bit16)) - { - Assert.True(outMeta.TransparentL16.HasValue); - Assert.Equal(inMeta.TransparentL16, outMeta.TransparentL16); - } - else - { - Assert.True(outMeta.TransparentL8.HasValue); - Assert.Equal(inMeta.TransparentL8, outMeta.TransparentL8); - } - - break; - case PngColorType.Rgb: - if (pngBitDepth.Equals(PngBitDepth.Bit16)) - { - Assert.True(outMeta.TransparentRgb48.HasValue); - Assert.Equal(inMeta.TransparentRgb48, outMeta.TransparentRgb48); - } - else + PngMetadata inMeta = input.Metadata.GetPngMetadata(); + Assert.True(inMeta.HasTransparency); + + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + memStream.Position = 0; + using (var output = Image.Load(memStream)) { - Assert.True(outMeta.TransparentRgb24.HasValue); - Assert.Equal(inMeta.TransparentRgb24, outMeta.TransparentRgb24); + PngMetadata outMeta = output.Metadata.GetPngMetadata(); + Assert.True(outMeta.HasTransparency); + + switch (pngColorType) + { + case PngColorType.Grayscale: + if (pngBitDepth.Equals(PngBitDepth.Bit16)) + { + Assert.True(outMeta.TransparentL16.HasValue); + Assert.Equal(inMeta.TransparentL16, outMeta.TransparentL16); + } + else + { + Assert.True(outMeta.TransparentL8.HasValue); + Assert.Equal(inMeta.TransparentL8, outMeta.TransparentL8); + } + + break; + case PngColorType.Rgb: + if (pngBitDepth.Equals(PngBitDepth.Bit16)) + { + Assert.True(outMeta.TransparentRgb48.HasValue); + Assert.Equal(inMeta.TransparentRgb48, outMeta.TransparentRgb48); + } + else + { + Assert.True(outMeta.TransparentRgb24.HasValue); + Assert.Equal(inMeta.TransparentRgb24, outMeta.TransparentRgb24); + } + + break; + } } - - break; + } } } @@ -400,37 +420,41 @@ private static void TestPngEncoderCore( bool appendPngBitDepth = false) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var encoder = new PngEncoder + using (Image image = provider.GetImage()) { - ColorType = pngColorType, - FilterMethod = pngFilterMethod, - CompressionLevel = compressionLevel, - BitDepth = bitDepth, - Quantizer = new WuQuantizer(paletteSize), - InterlaceMethod = interlaceMode - }; - - string pngColorTypeInfo = appendPngColorType ? pngColorType.ToString() : string.Empty; - string pngFilterMethodInfo = appendPngFilterMethod ? pngFilterMethod.ToString() : string.Empty; - string compressionLevelInfo = appendCompressionLevel ? $"_C{compressionLevel}" : string.Empty; - string paletteSizeInfo = appendPaletteSize ? $"_PaletteSize-{paletteSize}" : string.Empty; - string pngBitDepthInfo = appendPngBitDepth ? bitDepth.ToString() : string.Empty; - string pngInterlaceModeInfo = interlaceMode != PngInterlaceMode.None ? $"_{interlaceMode}" : string.Empty; - - string debugInfo = $"{pngColorTypeInfo}{pngFilterMethodInfo}{compressionLevelInfo}{paletteSizeInfo}{pngBitDepthInfo}{pngInterlaceModeInfo}"; - - string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "png", encoder, debugInfo, appendPixelType); - - // Compare to the Magick reference decoder. - IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); - - // We compare using both our decoder and the reference decoder as pixel transformation - // occurs within the encoder itself leaving the input image unaffected. - // This means we are benefiting from testing our decoder also. - using var imageSharpImage = Image.Load(actualOutputFile, new PngDecoder()); - using var referenceImage = Image.Load(actualOutputFile, referenceDecoder); - ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage); + var encoder = new PngEncoder + { + ColorType = pngColorType, + FilterMethod = pngFilterMethod, + CompressionLevel = compressionLevel, + BitDepth = bitDepth, + Quantizer = new WuQuantizer(paletteSize), + InterlaceMethod = interlaceMode + }; + + string pngColorTypeInfo = appendPngColorType ? pngColorType.ToString() : string.Empty; + string pngFilterMethodInfo = appendPngFilterMethod ? pngFilterMethod.ToString() : string.Empty; + string compressionLevelInfo = appendCompressionLevel ? $"_C{compressionLevel}" : string.Empty; + string paletteSizeInfo = appendPaletteSize ? $"_PaletteSize-{paletteSize}" : string.Empty; + string pngBitDepthInfo = appendPngBitDepth ? bitDepth.ToString() : string.Empty; + string pngInterlaceModeInfo = interlaceMode != PngInterlaceMode.None ? $"_{interlaceMode}" : string.Empty; + + string debugInfo = $"{pngColorTypeInfo}{pngFilterMethodInfo}{compressionLevelInfo}{paletteSizeInfo}{pngBitDepthInfo}{pngInterlaceModeInfo}"; + + string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "png", encoder, debugInfo, appendPixelType); + + // Compare to the Magick reference decoder. + IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile); + + // We compare using both our decoder and the reference decoder as pixel transformation + // occurs within the encoder itself leaving the input image unaffected. + // This means we are benefiting from testing our decoder also. + using (var imageSharpImage = Image.Load(actualOutputFile, new PngDecoder())) + using (var referenceImage = Image.Load(actualOutputFile, referenceDecoder)) + { + ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage); + } + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs index 7ebd4c1aab..fe25497247 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngMetadataTests.cs @@ -53,19 +53,21 @@ public void CloneIsDeep() public void Decoder_CanReadTextData(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - 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("Author") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); - 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")); + using (Image image = provider.GetImage(new PngDecoder())) + { + 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("Author") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); + 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")); + } } [Theory] @@ -74,24 +76,28 @@ public void Encoder_PreservesTextData(TestImageProvider provider where TPixel : struct, IPixel { var decoder = new PngDecoder(); - using Image input = provider.GetImage(decoder); - using var memoryStream = new MemoryStream(); - input.Save(memoryStream, new PngEncoder()); - - memoryStream.Position = 0; - using Image image = decoder.Decode(Configuration.Default, memoryStream); - 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("Author") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); - Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); - 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")); + using (Image input = provider.GetImage(decoder)) + using (var memoryStream = new MemoryStream()) + { + input.Save(memoryStream, new PngEncoder()); + + memoryStream.Position = 0; + using (Image image = decoder.Decode(Configuration.Default, memoryStream)) + { + 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("Author") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Copyright") && m.Value.Equals("ImageSharp")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Title") && m.Value.Equals("unittest")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("Description") && m.Value.Equals("compressed-text")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International") && m.Value.Equals("'e', mu'tlheghvam, ghaH yu'") && m.LanguageTag.Equals("x-klingon") && m.TranslatedKeyword.Equals("warning")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("International2") && m.Value.Equals("ИМАГЕШАРП") && m.LanguageTag.Equals("rus")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational") && m.Value.Equals("la plume de la mante") && m.LanguageTag.Equals("fra") && m.TranslatedKeyword.Equals("foobar")); + Assert.Contains(meta.TextData, m => m.Keyword.Equals("CompressedInternational2") && m.Value.Equals("這是一個考驗") && m.LanguageTag.Equals("chinese")); + 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")); + } + } } [Theory] @@ -99,14 +105,16 @@ public void Encoder_PreservesTextData(TestImageProvider provider public void Decoder_IgnoresInvalidTextData(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new PngDecoder()); - 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("trailing space")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("space")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("empty")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters")); - Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large")); + using (Image image = provider.GetImage(new PngDecoder())) + { + 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("trailing space")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("space")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("empty")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("invalid characters")); + Assert.DoesNotContain(meta.TextData, m => m.Value.Equals("too large")); + } } [Theory] @@ -115,27 +123,30 @@ public void Encode_UseCompression_WhenTextIsGreaterThenThreshold_Works(T where TPixel : struct, IPixel { var decoder = new PngDecoder(); - using Image input = provider.GetImage(decoder); - using var memoryStream = new MemoryStream(); - - // This will be a zTXt chunk. - var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty); - - // This will be a iTXt chunk. - var expectedTextNoneLatin = new PngTextData("large-text-non-latin", new string('Ф', 100), "language-tag", "translated-keyword"); - PngMetadata inputMetadata = input.Metadata.GetFormatMetadata(PngFormat.Instance); - inputMetadata.TextData.Add(expectedText); - inputMetadata.TextData.Add(expectedTextNoneLatin); - input.Save(memoryStream, new PngEncoder + using (Image input = provider.GetImage(decoder)) + using (var memoryStream = new MemoryStream()) { - TextCompressionThreshold = 50 - }); - - memoryStream.Position = 0; - using Image image = decoder.Decode(Configuration.Default, memoryStream); - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Contains(meta.TextData, m => m.Equals(expectedText)); - Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin)); + // This will be a zTXt chunk. + var expectedText = new PngTextData("large-text", new string('c', 100), string.Empty, string.Empty); + + // This will be a iTXt chunk. + var expectedTextNoneLatin = new PngTextData("large-text-non-latin", new string('Ф', 100), "language-tag", "translated-keyword"); + PngMetadata inputMetadata = input.Metadata.GetFormatMetadata(PngFormat.Instance); + inputMetadata.TextData.Add(expectedText); + inputMetadata.TextData.Add(expectedTextNoneLatin); + input.Save(memoryStream, new PngEncoder + { + TextCompressionThreshold = 50 + }); + + memoryStream.Position = 0; + using (Image image = decoder.Decode(Configuration.Default, memoryStream)) + { + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + Assert.Contains(meta.TextData, m => m.Equals(expectedText)); + Assert.Contains(meta.TextData, m => m.Equals(expectedTextNoneLatin)); + } + } } [Fact] @@ -148,13 +159,15 @@ public void Decode_IgnoreMetadataIsFalse_TextChunkIsRead() var testFile = TestFile.Create(TestImages.Png.Blur); - using Image image = testFile.CreateRgba32Image(options); - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + using (Image image = testFile.CreateRgba32Image(options)) + { + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Equal(1, meta.TextData.Count); - Assert.Equal("Software", meta.TextData[0].Keyword); - Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value); - Assert.Equal(0.4545d, meta.Gamma, precision: 4); + Assert.Equal(1, meta.TextData.Count); + Assert.Equal("Software", meta.TextData[0].Keyword); + Assert.Equal("paint.net 4.0.6", meta.TextData[0].Value); + Assert.Equal(0.4545d, meta.Gamma, precision: 4); + } } [Fact] @@ -167,9 +180,11 @@ public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored() var testFile = TestFile.Create(TestImages.Png.Blur); - using Image image = testFile.CreateRgba32Image(options); - PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); - Assert.Equal(0, meta.TextData.Count); + using (Image image = testFile.CreateRgba32Image(options)) + { + PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance); + Assert.Equal(0, meta.TextData.Count); + } } [Theory] @@ -177,13 +192,17 @@ public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored() public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new PngDecoder(); - using Image image = decoder.Decode(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new PngDecoder(); + using (Image image = decoder.Decode(Configuration.Default, stream)) + { + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } + } } [Theory] @@ -191,13 +210,15 @@ public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolutio public void Identify_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit) { var testFile = TestFile.Create(imagePath); - using var stream = new MemoryStream(testFile.Bytes, false); - var decoder = new PngDecoder(); - IImageInfo image = decoder.Identify(Configuration.Default, stream); - ImageMetadata meta = image.Metadata; - Assert.Equal(xResolution, meta.HorizontalResolution); - Assert.Equal(yResolution, meta.VerticalResolution); - Assert.Equal(resolutionUnit, meta.ResolutionUnits); + using (var stream = new MemoryStream(testFile.Bytes, false)) + { + var decoder = new PngDecoder(); + IImageInfo image = decoder.Identify(Configuration.Default, stream); + ImageMetadata meta = image.Metadata; + Assert.Equal(xResolution, meta.HorizontalResolution); + Assert.Equal(yResolution, meta.VerticalResolution); + Assert.Equal(resolutionUnit, meta.ResolutionUnits); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs index 645ee08bf5..0233e0a098 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngSmokeTests.cs @@ -18,16 +18,19 @@ public void GeneralTest(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? - using Image image = provider.GetImage(); - using var ms = new MemoryStream(); - - // image.Save(provider.Utility.GetTestOutputFileName("bmp")); - image.Save(ms, new PngEncoder()); - ms.Position = 0; - using var img2 = Image.Load(ms, new PngDecoder()); - ImageComparer.Tolerant().VerifySimilarity(image, img2); + using (Image image = provider.GetImage()) + using (var ms = new MemoryStream()) + { + // image.Save(provider.Utility.GetTestOutputFileName("bmp")); + image.Save(ms, new PngEncoder()); + ms.Position = 0; + using (var img2 = Image.Load(ms, new PngDecoder())) + { + 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 @@ -100,17 +103,20 @@ public void Resize(TestImageProvider provider) where TPixel : struct, IPixel { // does saving a file then reopening mean both files are identical??? - using Image image = provider.GetImage(); - using var ms = new MemoryStream(); - - // image.Save(provider.Utility.GetTestOutputFileName("png")); - image.Mutate(x => x.Resize(100, 100)); + using (Image image = provider.GetImage()) + using (var ms = new MemoryStream()) + { + // image.Save(provider.Utility.GetTestOutputFileName("png")); + image.Mutate(x => x.Resize(100, 100)); - // image.Save(provider.Utility.GetTestOutputFileName("png", "resize")); - image.Save(ms, new PngEncoder()); - ms.Position = 0; - using var img2 = Image.Load(ms, new PngDecoder()); - ImageComparer.Tolerant().VerifySimilarity(image, img2); + // image.Save(provider.Utility.GetTestOutputFileName("png", "resize")); + image.Save(ms, new PngEncoder()); + ms.Position = 0; + using (var img2 = Image.Load(ms, new PngDecoder())) + { + ImageComparer.Tolerant().VerifySimilarity(image, img2); + } + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs index df3ddc216c..1f8cbd6a9b 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaDecoderTests.cs @@ -18,9 +18,11 @@ public class TgaDecoderTests public void TgaDecoder_CanDecode_Uncompressed_MonoChrome(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -28,9 +30,11 @@ public void TgaDecoder_CanDecode_Uncompressed_MonoChrome(TestImageProvid public void TgaDecoder_CanDecode_Uncompressed_15Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -38,9 +42,11 @@ public void TgaDecoder_CanDecode_Uncompressed_15Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -48,9 +54,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_15Bit(TestImageProvide public void TgaDecoder_CanDecode_Uncompressed_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -58,9 +66,11 @@ public void TgaDecoder_CanDecode_Uncompressed_16Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -68,9 +78,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_WithPalette_16Bit(Test public void TgaDecoder_CanDecode_Uncompressed_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -78,9 +90,11 @@ public void TgaDecoder_CanDecode_Uncompressed_24Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -88,9 +102,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_WithTopLeftOrigin_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -98,9 +114,11 @@ public void TgaDecoder_CanDecode_Palette_WithTopLeftOrigin_24Bit(TestIma public void TgaDecoder_CanDecode_Uncompressed_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -108,9 +126,11 @@ public void TgaDecoder_CanDecode_Uncompressed_32Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -118,9 +138,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_MonoChrome(TestImagePr public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -128,9 +150,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_16Bit(TestImageProvide public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -138,9 +162,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_24Bit(TestImageProvide public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -148,9 +174,11 @@ public void TgaDecoder_CanDecode_RunLengthEncoded_32Bit(TestImageProvide public void TgaDecoder_CanDecode_WithPalette_16Bit(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } [Theory] @@ -158,9 +186,11 @@ public void TgaDecoder_CanDecode_WithPalette_16Bit(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(new TgaDecoder()); - image.DebugSave(provider); - TgaTestUtils.CompareWithReferenceDecoder(provider, image); + using (Image image = provider.GetImage(new TgaDecoder())) + { + image.DebugSave(provider); + TgaTestUtils.CompareWithReferenceDecoder(provider, image); + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs index 562088620a..26fe7cbdad 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaEncoderTests.cs @@ -37,14 +37,20 @@ public void Encode_PreserveBitsPerPixel(string imagePath, TgaBitsPerPixel bmpBit { var options = new TgaEncoder(); - var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - memStream.Position = 0; - using var output = Image.Load(memStream); - TgaMetadata meta = output.Metadata.GetTgaMetadata(); - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + TestFile testFile = TestFile.Create(imagePath); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + memStream.Position = 0; + using (Image output = Image.Load(memStream)) + { + TgaMetadata meta = output.Metadata.GetTgaMetadata(); + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + } + } + } } [Theory] @@ -56,14 +62,20 @@ public void Encode_WithCompression_PreserveBitsPerPixel(string imagePath, TgaBit Compression = TgaCompression.RunLength }; - var testFile = TestFile.Create(imagePath); - using Image input = testFile.CreateRgba32Image(); - using var memStream = new MemoryStream(); - input.Save(memStream, options); - memStream.Position = 0; - using var output = Image.Load(memStream); - TgaMetadata meta = output.Metadata.GetTgaMetadata(); - Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + TestFile testFile = TestFile.Create(imagePath); + using (Image input = testFile.CreateRgba32Image()) + { + using (var memStream = new MemoryStream()) + { + input.Save(memStream, options); + memStream.Position = 0; + using (var output = Image.Load(memStream)) + { + TgaMetadata meta = output.Metadata.GetTgaMetadata(); + Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel); + } + } + } } [Theory] @@ -118,14 +130,20 @@ private static void TestTgaEncoderCore( float compareTolerance = 0.01f) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; - - using var memStream = new MemoryStream(); - image.Save(memStream, encoder); - memStream.Position = 0; - using var encodedImage = (Image)Image.Load(memStream); - TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance); + using (Image image = provider.GetImage()) + { + var encoder = new TgaEncoder { BitsPerPixel = bitsPerPixel, Compression = compression }; + + using (var memStream = new MemoryStream()) + { + image.Save(memStream, encoder); + memStream.Position = 0; + using (var encodedImage = (Image)Image.Load(memStream)) + { + TgaTestUtils.CompareWithReferenceDecoder(provider, encodedImage, useExactComparer, compareTolerance); + } + } + } } } } diff --git a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs index 500de56066..090aecb797 100644 --- a/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs +++ b/tests/ImageSharp.Tests/Formats/Tga/TgaTestUtils.cs @@ -42,22 +42,24 @@ public static void CompareWithReferenceDecoder( public static Image DecodeWithMagick(Configuration configuration, FileInfo fileInfo) where TPixel : struct, IPixel { - using var magickImage = new MagickImage(fileInfo); - var result = new Image(configuration, magickImage.Width, magickImage.Height); - Span resultPixels = result.GetPixelSpan(); - - using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) + using (var magickImage = new MagickImage(fileInfo)) { - byte[] data = pixels.ToByteArray(PixelMapping.RGBA); + var result = new Image(configuration, magickImage.Width, magickImage.Height); + Span resultPixels = result.GetPixelSpan(); - PixelOperations.Instance.FromRgba32Bytes( - configuration, - data, - resultPixels, - resultPixels.Length); - } + using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) + { + byte[] data = pixels.ToByteArray(PixelMapping.RGBA); - return result; + PixelOperations.Instance.FromRgba32Bytes( + configuration, + data, + resultPixels, + resultPixels.Length); + } + + return result; + } } } } diff --git a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs index 2de4b6e322..5914aba400 100644 --- a/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs +++ b/tests/ImageSharp.Tests/Helpers/ParallelHelperTests.cs @@ -295,41 +295,43 @@ public void IterateRectangularBuffer( { MemoryAllocator memoryAllocator = Configuration.Default.MemoryAllocator; - using Buffer2D expected = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean); - using Buffer2D actual = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean); - var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight); - - void FillRow(int y, Buffer2D buffer) + using (Buffer2D expected = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean)) + using (Buffer2D actual = memoryAllocator.Allocate2D(bufferWidth, bufferHeight, AllocationOptions.Clean)) { - for (int x = rect.Left; x < rect.Right; x++) - { - buffer[x, y] = new Point(x, y); - } - } + var rect = new Rectangle(rectX, rectY, rectWidth, rectHeight); - // Fill Expected data: - for (int y = rectY; y < rect.Bottom; y++) - { - FillRow(y, expected); - } - - // Fill actual data using IterateRows: - var settings = new ParallelExecutionSettings(maxDegreeOfParallelism, memoryAllocator); - - ParallelHelper.IterateRows( - rect, - settings, - rows => + void FillRow(int y, Buffer2D buffer) { - this.output.WriteLine(rows.ToString()); - for (int y = rows.Min; y < rows.Max; y++) + for (int x = rect.Left; x < rect.Right; x++) { - FillRow(y, actual); + buffer[x, y] = new Point(x, y); } - }); + } + + // Fill Expected data: + for (int y = rectY; y < rect.Bottom; y++) + { + FillRow(y, expected); + } + + // Fill actual data using IterateRows: + var settings = new ParallelExecutionSettings(maxDegreeOfParallelism, memoryAllocator); - // Assert: - TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan()); + ParallelHelper.IterateRows( + rect, + settings, + rows => + { + this.output.WriteLine(rows.ToString()); + for (int y = rows.Min; y < rows.Max; y++) + { + FillRow(y, actual); + } + }); + + // Assert: + TestImageExtensions.CompareBuffers(expected.GetSpan(), actual.GetSpan()); + } } [Theory] diff --git a/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs b/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs index ff1010927c..0bb3f49d64 100644 --- a/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs +++ b/tests/ImageSharp.Tests/Helpers/RowIntervalTests.cs @@ -19,18 +19,20 @@ public class RowIntervalTests [InlineData(10, 20, 0, 1)] public void GetMultiRowSpan(int width, int height, int min, int max) { - using Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(width, height); - var rows = new RowInterval(min, max); + using (Buffer2D buffer = Configuration.Default.MemoryAllocator.Allocate2D(width, height)) + { + var rows = new RowInterval(min, max); - Span span = buffer.GetMultiRowSpan(rows); + Span span = buffer.GetMultiRowSpan(rows); - ref int expected0 = ref buffer.GetSpan()[min * width]; - int expectedLength = (max - min) * width; + ref int expected0 = ref buffer.GetSpan()[min * width]; + int expectedLength = (max - min) * width; - ref int actual0 = ref span[0]; + ref int actual0 = ref span[0]; - Assert.Equal(span.Length, expectedLength); - Assert.True(Unsafe.AreSame(ref expected0, ref actual0)); + Assert.Equal(span.Length, expectedLength); + Assert.True(Unsafe.AreSame(ref expected0, ref actual0)); + } } [Fact] diff --git a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs index 107fb28649..62e2048431 100644 --- a/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs +++ b/tests/ImageSharp.Tests/IO/DoubleBufferedStreamReaderTests.cs @@ -16,58 +16,64 @@ public class DoubleBufferedStreamReaderTests [Fact] public void DoubleBufferedStreamReaderCanReadSingleByteFromOrigin() { - using MemoryStream stream = this.CreateTestStream(); - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + using (MemoryStream stream = this.CreateTestStream()) + { + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - Assert.Equal(expected[0], reader.ReadByte()); + Assert.Equal(expected[0], reader.ReadByte()); - // We've read a whole chunk but increment by 1 in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - Assert.Equal(1, reader.Position); + // We've read a whole chunk but increment by 1 in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + Assert.Equal(1, reader.Position); + } } [Fact] public void DoubleBufferedStreamReaderCanReadSingleByteFromOffset() { - using MemoryStream stream = this.CreateTestStream(); - byte[] expected = stream.ToArray(); - const int offset = 5; - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - reader.Position = offset; + using (MemoryStream stream = this.CreateTestStream()) + { + byte[] expected = stream.ToArray(); + const int offset = 5; + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + reader.Position = offset; - Assert.Equal(expected[offset], reader.ReadByte()); + Assert.Equal(expected[offset], reader.ReadByte()); - // We've read a whole chunk but increment by 1 in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset); - Assert.Equal(offset + 1, reader.Position); + // We've read a whole chunk but increment by 1 in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength + offset); + Assert.Equal(offset + 1, reader.Position); + } } [Fact] public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly() { - using MemoryStream stream = this.CreateTestStream(); - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - - for (int i = 0; i < expected.Length; i++) + using (MemoryStream stream = this.CreateTestStream()) { - Assert.Equal(expected[i], reader.ReadByte()); - Assert.Equal(i + 1, reader.Position); + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - if (i < DoubleBufferedStreamReader.ChunkLength) + for (int i = 0; i < expected.Length; i++) { - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - } - else if (i >= DoubleBufferedStreamReader.ChunkLength && i < DoubleBufferedStreamReader.ChunkLength * 2) - { - // We should have advanced to the second chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); - } - else - { - // We should have advanced to the third chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); + Assert.Equal(expected[i], reader.ReadByte()); + Assert.Equal(i + 1, reader.Position); + + if (i < DoubleBufferedStreamReader.ChunkLength) + { + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + } + else if (i >= DoubleBufferedStreamReader.ChunkLength && i < DoubleBufferedStreamReader.ChunkLength * 2) + { + // We should have advanced to the second chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); + } + else + { + // We should have advanced to the third chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); + } } } } @@ -75,49 +81,53 @@ public void DoubleBufferedStreamReaderCanReadSubsequentSingleByteCorrectly() [Fact] public void DoubleBufferedStreamReaderCanReadMultipleBytesFromOrigin() { - using MemoryStream stream = this.CreateTestStream(); - var buffer = new byte[2]; - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - - Assert.Equal(2, reader.Read(buffer, 0, 2)); - Assert.Equal(expected[0], buffer[0]); - Assert.Equal(expected[1], buffer[1]); - - // We've read a whole chunk but increment by the buffer length in our reader. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - Assert.Equal(buffer.Length, reader.Position); + using (MemoryStream stream = this.CreateTestStream()) + { + var buffer = new byte[2]; + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); + + Assert.Equal(2, reader.Read(buffer, 0, 2)); + Assert.Equal(expected[0], buffer[0]); + Assert.Equal(expected[1], buffer[1]); + + // We've read a whole chunk but increment by the buffer length in our reader. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + Assert.Equal(buffer.Length, reader.Position); + } } [Fact] public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() { - using MemoryStream stream = this.CreateTestStream(); - var buffer = new byte[2]; - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); - - for (int i = 0, o = 0; i < expected.Length / 2; i++, o += 2) + using (MemoryStream stream = this.CreateTestStream()) { - Assert.Equal(2, reader.Read(buffer, 0, 2)); - Assert.Equal(expected[o], buffer[0]); - Assert.Equal(expected[o + 1], buffer[1]); - Assert.Equal(o + 2, reader.Position); + var buffer = new byte[2]; + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - int offset = i * 2; - if (offset < DoubleBufferedStreamReader.ChunkLength) + for (int i = 0, o = 0; i < expected.Length / 2; i++, o += 2) { - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); - } - else if (offset >= DoubleBufferedStreamReader.ChunkLength && offset < DoubleBufferedStreamReader.ChunkLength * 2) - { - // We should have advanced to the second chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); - } - else - { - // We should have advanced to the third chunk now. - Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); + Assert.Equal(2, reader.Read(buffer, 0, 2)); + Assert.Equal(expected[o], buffer[0]); + Assert.Equal(expected[o + 1], buffer[1]); + Assert.Equal(o + 2, reader.Position); + + int offset = i * 2; + if (offset < DoubleBufferedStreamReader.ChunkLength) + { + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength); + } + else if (offset >= DoubleBufferedStreamReader.ChunkLength && offset < DoubleBufferedStreamReader.ChunkLength * 2) + { + // We should have advanced to the second chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 2); + } + else + { + // We should have advanced to the third chunk now. + Assert.Equal(stream.Position, DoubleBufferedStreamReader.ChunkLength * 3); + } } } } @@ -125,31 +135,33 @@ public void DoubleBufferedStreamReaderCanReadSubsequentMultipleByteCorrectly() [Fact] public void DoubleBufferedStreamReaderCanSkip() { - using MemoryStream stream = this.CreateTestStream(); - byte[] expected = stream.ToArray(); - var reader = new DoubleBufferedStreamReader(this.allocator, stream); + using (MemoryStream stream = this.CreateTestStream()) + { + byte[] expected = stream.ToArray(); + var reader = new DoubleBufferedStreamReader(this.allocator, stream); - int skip = 50; - int plusOne = 1; - int skip2 = DoubleBufferedStreamReader.ChunkLength; + int skip = 50; + int plusOne = 1; + int skip2 = DoubleBufferedStreamReader.ChunkLength; - // Skip - reader.Skip(skip); - Assert.Equal(skip, reader.Position); - Assert.Equal(stream.Position, reader.Position); + // Skip + reader.Skip(skip); + Assert.Equal(skip, reader.Position); + Assert.Equal(stream.Position, reader.Position); - // Read - Assert.Equal(expected[skip], reader.ReadByte()); + // Read + Assert.Equal(expected[skip], reader.ReadByte()); - // Skip Again - reader.Skip(skip2); + // Skip Again + reader.Skip(skip2); - // First Skip + First Read + Second Skip - int position = skip + plusOne + skip2; + // First Skip + First Read + Second Skip + int position = skip + plusOne + skip2; - Assert.Equal(position, reader.Position); - Assert.Equal(stream.Position, reader.Position); - Assert.Equal(expected[position], reader.ReadByte()); + Assert.Equal(position, reader.Position); + Assert.Equal(stream.Position, reader.Position); + Assert.Equal(expected[position], reader.ReadByte()); + } } private MemoryStream CreateTestStream() diff --git a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs index fb3fdf2b0b..bc2eec79d1 100644 --- a/tests/ImageSharp.Tests/Image/ImageCloneTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageCloneTests.cs @@ -32,22 +32,24 @@ public void Clone_WhenDisposed_Throws() [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgra32(TestImageProvider provider) { - using Image image = provider.GetImage(); - using Image clone = image.CloneAs(); - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) + using (Image clone = image.CloneAs()) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) + for (int y = 0; y < image.Height; y++) { - Rgba32 expected = row[x]; - Bgra32 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - Assert.Equal(expected.A, actual.A); + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) + { + Rgba32 expected = row[x]; + Bgra32 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + Assert.Equal(expected.A, actual.A); + } } } } @@ -56,21 +58,23 @@ public void CloneAs_ToBgra32(TestImageProvider provider) [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToBgr24(TestImageProvider provider) { - using Image image = provider.GetImage(); - using Image clone = image.CloneAs(); - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) + using (Image clone = image.CloneAs()) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) + for (int y = 0; y < image.Height; y++) { - Rgba32 expected = row[x]; - Bgr24 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) + { + Rgba32 expected = row[x]; + Bgr24 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + } } } } @@ -79,22 +83,24 @@ public void CloneAs_ToBgr24(TestImageProvider provider) [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToArgb32(TestImageProvider provider) { - using Image image = provider.GetImage(); - using Image clone = image.CloneAs(); - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) + using (Image clone = image.CloneAs()) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) + for (int y = 0; y < image.Height; y++) { - Rgba32 expected = row[x]; - Argb32 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); - Assert.Equal(expected.A, actual.A); + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) + { + Rgba32 expected = row[x]; + Argb32 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + Assert.Equal(expected.A, actual.A); + } } } } @@ -103,21 +109,23 @@ public void CloneAs_ToArgb32(TestImageProvider provider) [WithTestPatternImages(9, 9, PixelTypes.Rgba32)] public void CloneAs_ToRgb24(TestImageProvider provider) { - using Image image = provider.GetImage(); - using Image clone = image.CloneAs(); - for (int y = 0; y < image.Height; y++) + using (Image image = provider.GetImage()) + using (Image clone = image.CloneAs()) { - Span row = image.GetPixelRowSpan(y); - Span rowClone = clone.GetPixelRowSpan(y); - - for (int x = 0; x < image.Width; x++) + for (int y = 0; y < image.Height; y++) { - Rgba32 expected = row[x]; - Rgb24 actual = rowClone[x]; - - Assert.Equal(expected.R, actual.R); - Assert.Equal(expected.G, actual.G); - Assert.Equal(expected.B, actual.B); + Span row = image.GetPixelRowSpan(y); + Span rowClone = clone.GetPixelRowSpan(y); + + for (int x = 0; x < image.Width; x++) + { + Rgba32 expected = row[x]; + Rgb24 actual = rowClone[x]; + + Assert.Equal(expected.R, actual.R); + Assert.Equal(expected.G, actual.G); + Assert.Equal(expected.B, actual.B); + } } } } diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs index 0ead18c765..ea1afa5b62 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.Generic.cs @@ -192,11 +192,15 @@ public void Dispose_DisposesAllInnerFrames() public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using Image img = provider.GetImage(); - img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway - using Image cloned = img.Frames.CloneFrame(0); - Assert.Equal(2, img.Frames.Count); - cloned.ComparePixelBufferTo(img.GetPixelSpan()); + using (Image img = provider.GetImage()) + { + img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway + using (Image cloned = img.Frames.CloneFrame(0)) + { + Assert.Equal(2, img.Frames.Count); + cloned.ComparePixelBufferTo(img.GetPixelSpan()); + } + } } [Theory] @@ -204,13 +208,17 @@ public void CloneFrame(TestImageProvider provider) public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using Image img = provider.GetImage(); - var sourcePixelData = img.GetPixelSpan().ToArray(); + using (Image img = provider.GetImage()) + { + var sourcePixelData = img.GetPixelSpan().ToArray(); - img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); - using Image cloned = img.Frames.ExportFrame(0); - Assert.Equal(1, img.Frames.Count); - cloned.ComparePixelBufferTo(sourcePixelData); + img.Frames.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); + using (Image cloned = img.Frames.ExportFrame(0)) + { + Assert.Equal(1, img.Frames.Count); + cloned.ComparePixelBufferTo(sourcePixelData); + } + } } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs index 92945f6f50..415c1af19f 100644 --- a/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs +++ b/tests/ImageSharp.Tests/Image/ImageFrameCollectionTests.NonGeneric.cs @@ -148,16 +148,20 @@ public void RootFrameIsFrameAtIndexZero() public void CloneFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using Image img = provider.GetImage(); - ImageFrameCollection nonGenericFrameCollection = img.Frames; + using (Image img = provider.GetImage()) + { + ImageFrameCollection nonGenericFrameCollection = img.Frames; - nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway - using Image cloned = nonGenericFrameCollection.CloneFrame(0); - Assert.Equal(2, img.Frames.Count); + nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); // add a frame anyway + using (Image cloned = nonGenericFrameCollection.CloneFrame(0)) + { + Assert.Equal(2, img.Frames.Count); - var expectedClone = (Image)cloned; + var expectedClone = (Image)cloned; - expectedClone.ComparePixelBufferTo(img.GetPixelSpan()); + expectedClone.ComparePixelBufferTo(img.GetPixelSpan()); + } + } } [Theory] @@ -165,17 +169,21 @@ public void CloneFrame(TestImageProvider provider) public void ExtractFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using Image img = provider.GetImage(); - var sourcePixelData = img.GetPixelSpan().ToArray(); + using (Image img = provider.GetImage()) + { + var sourcePixelData = img.GetPixelSpan().ToArray(); - ImageFrameCollection nonGenericFrameCollection = img.Frames; + ImageFrameCollection nonGenericFrameCollection = img.Frames; - nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); - using Image cloned = nonGenericFrameCollection.ExportFrame(0); - Assert.Equal(1, img.Frames.Count); + nonGenericFrameCollection.AddFrame(new ImageFrame(Configuration.Default, 10, 10)); + using (Image cloned = nonGenericFrameCollection.ExportFrame(0)) + { + Assert.Equal(1, img.Frames.Count); - var expectedClone = (Image)cloned; - expectedClone.ComparePixelBufferTo(sourcePixelData); + var expectedClone = (Image)cloned; + expectedClone.ComparePixelBufferTo(sourcePixelData); + } + } } [Fact] @@ -262,34 +270,39 @@ public void Contains_FalseIfNonMember() public void ConstructGif_FromDifferentPixelTypes(TestImageProvider provider) where TPixel : struct, IPixel { - using Image source = provider.GetImage(); - using var dest = new Image(source.GetConfiguration(), source.Width, source.Height); - - // Giphy.gif has 5 frames - ImportFrameAs(source.Frames, dest.Frames, 0); - ImportFrameAs(source.Frames, dest.Frames, 1); - ImportFrameAs(source.Frames, dest.Frames, 2); - ImportFrameAs(source.Frames, dest.Frames, 3); - ImportFrameAs(source.Frames, dest.Frames, 4); + using (Image source = provider.GetImage()) + using (var dest = new Image(source.GetConfiguration(), source.Width, source.Height)) + { + // Giphy.gif has 5 frames + ImportFrameAs(source.Frames, dest.Frames, 0); + ImportFrameAs(source.Frames, dest.Frames, 1); + ImportFrameAs(source.Frames, dest.Frames, 2); + ImportFrameAs(source.Frames, dest.Frames, 3); + ImportFrameAs(source.Frames, dest.Frames, 4); - // Drop the original empty root frame: - dest.Frames.RemoveFrame(0); + // Drop the original empty root frame: + dest.Frames.RemoveFrame(0); - dest.DebugSave(provider, appendSourceFileOrDescription: false, extension: "gif"); - dest.CompareToOriginal(provider); + dest.DebugSave(provider, appendSourceFileOrDescription: false, extension: "gif"); + dest.CompareToOriginal(provider); - for (int i = 0; i < 5; i++) - { - CompareGifMetadata(source.Frames[i], dest.Frames[i]); + for (int i = 0; i < 5; i++) + { + CompareGifMetadata(source.Frames[i], dest.Frames[i]); + } } } private static void ImportFrameAs(ImageFrameCollection source, ImageFrameCollection destination, int index) where TPixel : struct, IPixel { - using Image temp = source.CloneFrame(index); - using Image temp2 = temp.CloneAs(); - destination.AddFrame(temp2.Frames.RootFrame); + using (Image temp = source.CloneFrame(index)) + { + using (Image temp2 = temp.CloneAs()) + { + destination.AddFrame(temp2.Frames.RootFrame); + } + } } private static void CompareGifMetadata(ImageFrame a, ImageFrame b) diff --git a/tests/ImageSharp.Tests/Image/ImageRotationTests.cs b/tests/ImageSharp.Tests/Image/ImageRotationTests.cs index 6e17407ca1..28196c0da1 100644 --- a/tests/ImageSharp.Tests/Image/ImageRotationTests.cs +++ b/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. using SixLabors.ImageSharp.PixelFormats; @@ -47,10 +47,12 @@ public void RotateImageBy360Degrees() private static (Size original, Size rotated) Rotate(int angle) { var file = TestFile.Create(TestImages.Bmp.Car); - using var image = Image.Load(file.FullPath); - Size original = image.Size(); - image.Mutate(x => x.Rotate(angle)); - return (original, image.Size()); + using (var image = Image.Load(file.FullPath)) + { + Size original = image.Size(); + image.Mutate(x => x.Rotate(angle)); + return (original, image.Size()); + } } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs index c639f37cd2..dcf4dcfe84 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.DetectFormat.cs @@ -71,9 +71,11 @@ public void FromFileSystemPath_CustomConfiguration() [Fact] public void FromStream_GlobalConfiguration() { - using var stream = new MemoryStream(this.ActualImageBytes); - IImageFormat type = Image.DetectFormat(stream); - Assert.Equal(ExpectedGlobalFormat, type); + using (var stream = new MemoryStream(this.ActualImageBytes)) + { + IImageFormat type = Image.DetectFormat(stream); + Assert.Equal(ExpectedGlobalFormat, type); + } } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs b/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs index 7d75bd0b02..7a5fa87290 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.LoadPixelData.cs +++ b/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. using System; @@ -18,15 +18,17 @@ public void FromPixels(bool useSpan) { Rgba32[] data = { Rgba32.Black, Rgba32.White, Rgba32.White, Rgba32.Black, }; - using Image img = useSpan - ? Image.LoadPixelData(data.AsSpan(), 2, 2) - : Image.LoadPixelData(data, 2, 2); - Assert.NotNull(img); - Assert.Equal(Rgba32.Black, img[0, 0]); - Assert.Equal(Rgba32.White, img[0, 1]); + using (Image img = useSpan + ? Image.LoadPixelData(data.AsSpan(), 2, 2) + : Image.LoadPixelData(data, 2, 2)) + { + Assert.NotNull(img); + Assert.Equal(Rgba32.Black, img[0, 0]); + Assert.Equal(Rgba32.White, img[0, 1]); - Assert.Equal(Rgba32.White, img[1, 0]); - Assert.Equal(Rgba32.Black, img[1, 1]); + Assert.Equal(Rgba32.White, img[1, 0]); + Assert.Equal(Rgba32.Black, img[1, 1]); + } } [Theory] @@ -41,16 +43,18 @@ public void FromBytes(bool useSpan) 255, 255, 255, 255, // 1,0 0, 0, 0, 255, // 1,1 }; - using Image img = useSpan - ? Image.LoadPixelData(data.AsSpan(), 2, 2) - : Image.LoadPixelData(data, 2, 2); - Assert.NotNull(img); - Assert.Equal(Rgba32.Black, img[0, 0]); - Assert.Equal(Rgba32.White, img[0, 1]); + using (Image img = useSpan + ? Image.LoadPixelData(data.AsSpan(), 2, 2) + : Image.LoadPixelData(data, 2, 2)) + { + Assert.NotNull(img); + Assert.Equal(Rgba32.Black, img[0, 0]); + Assert.Equal(Rgba32.White, img[0, 1]); - Assert.Equal(Rgba32.White, img[1, 0]); - Assert.Equal(Rgba32.Black, img[1, 1]); + Assert.Equal(Rgba32.White, img[1, 0]); + Assert.Equal(Rgba32.Black, img[1, 1]); + } } } } -} +} \ No newline at end of file diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs index 006ec2226a..4c6b92100e 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FileSystemPath_UseDefaultConfiguration.cs @@ -25,45 +25,57 @@ private static void VerifyDecodedImage(Image img) [Fact] public void Path_Specific() { - using var img = Image.Load(this.Path); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Path)) + { + VerifyDecodedImage(img); + } } [Fact] public void Path_Agnostic() { - using var img = Image.Load(this.Path); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Path)) + { + VerifyDecodedImage(img); + } } [Fact] public void Path_Decoder_Specific() { - using var img = Image.Load(this.Path, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Path, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Fact] public void Path_Decoder_Agnostic() { - using var img = Image.Load(this.Path, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Path, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Fact] public void Path_OutFormat_Specific() { - using var img = Image.Load(this.Path, out IImageFormat format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = Image.Load(this.Path, out IImageFormat format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } [Fact] public void Path_OutFormat_Agnostic() { - using var img = Image.Load(this.Path, out IImageFormat format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = Image.Load(this.Path, out IImageFormat format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } [Fact] diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs index b7c4d27fa3..b8ed6e75b5 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromBytes_UseGlobalConfiguration.cs @@ -29,8 +29,10 @@ private static void VerifyDecodedImage(Image img) [InlineData(true)] public void Bytes_Specific(bool useSpan) { - using var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray); - VerifyDecodedImage(img); + using (var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray)) + { + VerifyDecodedImage(img); + } } [Theory] @@ -38,8 +40,10 @@ public void Bytes_Specific(bool useSpan) [InlineData(true)] public void Bytes_Agnostic(bool useSpan) { - using var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray); - VerifyDecodedImage(img); + using (var img = useSpan ? Image.Load(ByteSpan) : Image.Load(ByteArray)) + { + VerifyDecodedImage(img); + } } [Theory] @@ -47,8 +51,10 @@ public void Bytes_Agnostic(bool useSpan) [InlineData(true)] public void Bytes_Decoder_Specific(bool useSpan) { - using var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Theory] @@ -56,8 +62,10 @@ public void Bytes_Decoder_Specific(bool useSpan) [InlineData(true)] public void Bytes_Decoder_Agnostic(bool useSpan) { - using var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = useSpan ? Image.Load(ByteSpan, new BmpDecoder()) : Image.Load(ByteArray, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Theory] @@ -66,9 +74,11 @@ public void Bytes_Decoder_Agnostic(bool useSpan) public void Bytes_OutFormat_Specific(bool useSpan) { IImageFormat format; - using var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } [Theory] @@ -77,9 +87,11 @@ public void Bytes_OutFormat_Specific(bool useSpan) public void Bytes_OutFormat_Agnostic(bool useSpan) { IImageFormat format; - using var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = useSpan ? Image.Load(ByteSpan, out format) : Image.Load(ByteArray, out format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs index 74d4bf4db9..0c722b4d66 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Load_FromStream_UseDefaultConfiguration.cs @@ -28,45 +28,57 @@ private static void VerifyDecodedImage(Image img) [Fact] public void Stream_Specific() { - using var img = Image.Load(this.Stream); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Stream)) + { + VerifyDecodedImage(img); + } } [Fact] public void Stream_Agnostic() { - using var img = Image.Load(this.Stream); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Stream)) + { + VerifyDecodedImage(img); + } } [Fact] public void Stream_OutFormat_Specific() { - using var img = Image.Load(this.Stream, out IImageFormat format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = Image.Load(this.Stream, out IImageFormat format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } [Fact] public void Stream_Decoder_Specific() { - using var img = Image.Load(this.Stream, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Stream, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Fact] public void Stream_Decoder_Agnostic() { - using var img = Image.Load(this.Stream, new BmpDecoder()); - VerifyDecodedImage(img); + using (var img = Image.Load(this.Stream, new BmpDecoder())) + { + VerifyDecodedImage(img); + } } [Fact] public void Stream_OutFormat_Agnostic() { - using var img = Image.Load(this.Stream, out IImageFormat format); - VerifyDecodedImage(img); - Assert.IsType(format); + using (var img = Image.Load(this.Stream, out IImageFormat format)) + { + VerifyDecodedImage(img); + Assert.IsType(format); + } } public void Dispose() diff --git a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs index 597f32b666..dc65ecfef9 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.Save.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.Save.cs @@ -44,10 +44,12 @@ public void WhenExtensionIsUnknown_Throws() Assert.Throws( () => - { - using var image = new Image(10, 10); - image.Save(file); - }); + { + using (var image = new Image(10, 10)) + { + image.Save(file); + } + }); } [Fact] @@ -56,11 +58,15 @@ public void SetEncoding() string dir = TestEnvironment.CreateOutputDirectory(nameof(ImageTests)); string file = System.IO.Path.Combine(dir, "SetEncoding.dat"); - using var image = new Image(10, 10); - image.Save(file, new PngEncoder()); + using (var image = new Image(10, 10)) + { + image.Save(file, new PngEncoder()); + } - using var load = Image.Load(file, out var mime); - Assert.Equal("image/png", mime.DefaultMimeType); + using (Image.Load(file, out var mime)) + { + Assert.Equal("image/png", mime.DefaultMimeType); + } } [Fact] @@ -69,8 +75,10 @@ public void ThrowsWhenDisposed() var image = new Image(5, 5); image.Dispose(); IImageEncoder encoder = Mock.Of(); - using var stream = new MemoryStream(); - Assert.Throws(() => image.Save(stream, encoder)); + using (var stream = new MemoryStream()) + { + Assert.Throws(() => image.Save(stream, encoder)); + } } } } diff --git a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs index 047ad0fbce..0cf3071a0f 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs @@ -88,12 +88,14 @@ public void WrapMemory_CreatedImageIsCorrect() var array = new Rgba32[25]; var memory = new Memory(array); - using var image = Image.WrapMemory(cfg, memory, 5, 5, metaData); - ref Rgba32 pixel0 = ref image.GetPixelSpan()[0]; - Assert.True(Unsafe.AreSame(ref array[0], ref pixel0)); + using (var image = Image.WrapMemory(cfg, memory, 5, 5, metaData)) + { + ref Rgba32 pixel0 = ref image.GetPixelSpan()[0]; + Assert.True(Unsafe.AreSame(ref array[0], ref pixel0)); - Assert.Equal(cfg, image.GetConfiguration()); - Assert.Equal(metaData, image.Metadata); + Assert.Equal(cfg, image.GetConfiguration()); + Assert.Equal(metaData, image.Metadata); + } } [Fact] @@ -104,27 +106,33 @@ public void WrapSystemDrawingBitmap_WhenObserved() return; } - using var bmp = new Bitmap(51, 23); - using var memoryManager = new BitmapMemoryManager(bmp); - Memory memory = memoryManager.Memory; - Bgra32 bg = Color.Red; - Bgra32 fg = Color.Green; - - using var image = Image.WrapMemory(memory, bmp.Width, bmp.Height); - Assert.Equal(memory, image.GetPixelMemory()); - image.GetPixelSpan().Fill(bg); - for (var i = 10; i < 20; i++) + using (var bmp = new Bitmap(51, 23)) { - image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); - } - - Assert.False(memoryManager.IsDisposed); + using (var memoryManager = new BitmapMemoryManager(bmp)) + { + Memory memory = memoryManager.Memory; + Bgra32 bg = Color.Red; + Bgra32 fg = Color.Green; + + using (var image = Image.WrapMemory(memory, bmp.Width, bmp.Height)) + { + Assert.Equal(memory, image.GetPixelMemory()); + image.GetPixelSpan().Fill(bg); + for (var i = 10; i < 20; i++) + { + image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); + } + } + + Assert.False(memoryManager.IsDisposed); + } - string fn = System.IO.Path.Combine( - TestEnvironment.ActualOutputDirectoryFullPath, - $"{nameof(this.WrapSystemDrawingBitmap_WhenObserved)}.bmp"); + string fn = System.IO.Path.Combine( + TestEnvironment.ActualOutputDirectoryFullPath, + $"{nameof(this.WrapSystemDrawingBitmap_WhenObserved)}.bmp"); - bmp.Save(fn, ImageFormat.Bmp); + bmp.Save(fn, ImageFormat.Bmp); + } } [Fact] @@ -135,29 +143,31 @@ public void WrapSystemDrawingBitmap_WhenOwned() return; } - using var bmp = new Bitmap(51, 23); - var memoryManager = new BitmapMemoryManager(bmp); - Bgra32 bg = Color.Red; - Bgra32 fg = Color.Green; - - using (var image = Image.WrapMemory(memoryManager, bmp.Width, bmp.Height)) + using (var bmp = new Bitmap(51, 23)) { - Assert.Equal(memoryManager.Memory, image.GetPixelMemory()); + var memoryManager = new BitmapMemoryManager(bmp); + Bgra32 bg = Color.Red; + Bgra32 fg = Color.Green; - image.GetPixelSpan().Fill(bg); - for (var i = 10; i < 20; i++) + using (var image = Image.WrapMemory(memoryManager, bmp.Width, bmp.Height)) { - image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); + Assert.Equal(memoryManager.Memory, image.GetPixelMemory()); + + image.GetPixelSpan().Fill(bg); + for (var i = 10; i < 20; i++) + { + image.GetPixelRowSpan(i).Slice(10, 10).Fill(fg); + } } - } - Assert.True(memoryManager.IsDisposed); + Assert.True(memoryManager.IsDisposed); - string fn = System.IO.Path.Combine( - TestEnvironment.ActualOutputDirectoryFullPath, - $"{nameof(this.WrapSystemDrawingBitmap_WhenOwned)}.bmp"); + string fn = System.IO.Path.Combine( + TestEnvironment.ActualOutputDirectoryFullPath, + $"{nameof(this.WrapSystemDrawingBitmap_WhenOwned)}.bmp"); - bmp.Save(fn, ImageFormat.Bmp); + bmp.Save(fn, ImageFormat.Bmp); + } } private static bool ShouldSkipBitmapTest => diff --git a/tests/ImageSharp.Tests/Image/ImageTests.cs b/tests/ImageSharp.Tests/Image/ImageTests.cs index d1f6dae114..99bdfceccb 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.cs @@ -21,13 +21,15 @@ public class Constructor [Fact] public void Width_Height() { - using var image = new Image(11, 23); - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(default(Rgba32)); + using (var image = new Image(11, 23)) + { + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(default(Rgba32)); - Assert.Equal(Configuration.Default, image.GetConfiguration()); + Assert.Equal(Configuration.Default, image.GetConfiguration()); + } } [Fact] @@ -35,13 +37,15 @@ public void Configuration_Width_Height() { Configuration configuration = Configuration.Default.Clone(); - using var image = new Image(configuration, 11, 23); - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(default(Rgba32)); + using (var image = new Image(configuration, 11, 23)) + { + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(default(Rgba32)); - Assert.Equal(configuration, image.GetConfiguration()); + Assert.Equal(configuration, image.GetConfiguration()); + } } [Fact] @@ -50,13 +54,15 @@ public void Configuration_Width_Height_BackgroundColor() Configuration configuration = Configuration.Default.Clone(); Rgba32 color = Rgba32.Aquamarine; - using var image = new Image(configuration, 11, 23, color); - Assert.Equal(11, image.Width); - Assert.Equal(23, image.Height); - Assert.Equal(11 * 23, image.GetPixelSpan().Length); - image.ComparePixelBufferTo(color); + using (var image = new Image(configuration, 11, 23, color)) + { + Assert.Equal(11, image.Width); + Assert.Equal(23, image.Height); + Assert.Equal(11 * 23, image.GetPixelSpan().Length); + image.ComparePixelBufferTo(color); - Assert.Equal(configuration, image.GetConfiguration()); + Assert.Equal(configuration, image.GetConfiguration()); + } } [Fact] @@ -68,13 +74,15 @@ public void CreateUninitialized() configuration.MemoryAllocator = new TestMemoryAllocator(dirtyValue); var metadata = new ImageMetadata(); - using var image = Image.CreateUninitialized(configuration, 21, 22, metadata); - Assert.Equal(21, image.Width); - Assert.Equal(22, image.Height); - Assert.Same(configuration, image.GetConfiguration()); - Assert.Same(metadata, image.Metadata); + using (var image = Image.CreateUninitialized(configuration, 21, 22, metadata)) + { + Assert.Equal(21, image.Width); + Assert.Equal(22, image.Height); + Assert.Same(configuration, image.GetConfiguration()); + Assert.Same(metadata, image.Metadata); - Assert.Equal(dirtyValue, image[5, 5].PackedValue); + Assert.Equal(dirtyValue, image[5, 5].PackedValue); + } } } } diff --git a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs index 159b458848..02b59825b7 100644 --- a/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs +++ b/tests/ImageSharp.Tests/Memory/Buffer2DTests.cs @@ -35,20 +35,24 @@ public static void SpanPointsTo(Span span, IMemoryOwner buffer, int buf [InlineData(1025, 17)] public void Construct(int width, int height) { - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); - Assert.Equal(width, buffer.Width); - Assert.Equal(height, buffer.Height); - Assert.Equal(width * height, buffer.GetMemory().Length); + using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + { + Assert.Equal(width, buffer.Width); + Assert.Equal(height, buffer.Height); + Assert.Equal(width * height, buffer.GetMemory().Length); + } } [Fact] public void CreateClean() { - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean); - Span span = buffer.GetSpan(); - for (int j = 0; j < span.Length; j++) + using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(42, 42, AllocationOptions.Clean)) { - Assert.Equal(0, span[j]); + Span span = buffer.GetSpan(); + for (int j = 0; j < span.Length; j++) + { + Assert.Equal(0, span[j]); + } } } @@ -58,12 +62,14 @@ public void CreateClean() [InlineData(17, 42, 41)] public void GetRowSpanY(int width, int height, int y) { - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); - Span span = buffer.GetRowSpan(y); + using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + { + Span span = buffer.GetRowSpan(y); - // Assert.Equal(width * y, span.Start); - Assert.Equal(width, span.Length); - Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y); + // Assert.Equal(width * y, span.Start); + Assert.Equal(width, span.Length); + Assert.SpanPointsTo(span, buffer.MemorySource.MemoryOwner, width * y); + } } [Theory] @@ -72,31 +78,35 @@ public void GetRowSpanY(int width, int height, int y) [InlineData(99, 88, 98, 87)] public void Indexer(int width, int height, int x, int y) { - using Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height); - Span span = buffer.MemorySource.GetSpan(); + using (Buffer2D buffer = this.MemoryAllocator.Allocate2D(width, height)) + { + Span span = buffer.MemorySource.GetSpan(); - ref TestStructs.Foo actual = ref buffer[x, y]; + ref TestStructs.Foo actual = ref buffer[x, y]; - ref TestStructs.Foo expected = ref span[(y * width) + x]; + ref TestStructs.Foo expected = ref span[(y * width) + x]; - Assert.True(Unsafe.AreSame(ref expected, ref actual)); + Assert.True(Unsafe.AreSame(ref expected, ref actual)); + } } [Fact] public void SwapOrCopyContent() { - using Buffer2D a = this.MemoryAllocator.Allocate2D(10, 5); - using Buffer2D b = this.MemoryAllocator.Allocate2D(3, 7); - IMemoryOwner aa = a.MemorySource.MemoryOwner; - IMemoryOwner bb = b.MemorySource.MemoryOwner; + using (Buffer2D a = this.MemoryAllocator.Allocate2D(10, 5)) + using (Buffer2D b = this.MemoryAllocator.Allocate2D(3, 7)) + { + IMemoryOwner aa = a.MemorySource.MemoryOwner; + IMemoryOwner bb = b.MemorySource.MemoryOwner; - Buffer2D.SwapOrCopyContent(a, b); + Buffer2D.SwapOrCopyContent(a, b); - Assert.Equal(bb, a.MemorySource.MemoryOwner); - Assert.Equal(aa, b.MemorySource.MemoryOwner); + Assert.Equal(bb, a.MemorySource.MemoryOwner); + Assert.Equal(aa, b.MemorySource.MemoryOwner); - Assert.Equal(new Size(3, 7), a.Size()); - Assert.Equal(new Size(10, 5), b.Size()); + Assert.Equal(new Size(3, 7), a.Size()); + Assert.Equal(new Size(10, 5), b.Size()); + } } [Theory] @@ -109,19 +119,21 @@ public void SwapOrCopyContent() public void CopyColumns(int width, int height, int startIndex, int destIndex, int columnCount) { var rnd = new Random(123); - using Buffer2D b = this.MemoryAllocator.Allocate2D(width, height); - rnd.RandomFill(b.GetSpan(), 0, 1); + using (Buffer2D b = this.MemoryAllocator.Allocate2D(width, height)) + { + rnd.RandomFill(b.GetSpan(), 0, 1); - b.CopyColumns(startIndex, destIndex, columnCount); + b.CopyColumns(startIndex, destIndex, columnCount); - for (int y = 0; y < b.Height; y++) - { - Span row = b.GetRowSpan(y); + for (int y = 0; y < b.Height; y++) + { + Span row = b.GetRowSpan(y); - Span s = row.Slice(startIndex, columnCount); - Span d = row.Slice(destIndex, columnCount); + Span s = row.Slice(startIndex, columnCount); + Span d = row.Slice(destIndex, columnCount); - Xunit.Assert.True(s.SequenceEqual(d)); + Xunit.Assert.True(s.SequenceEqual(d)); + } } } @@ -129,20 +141,22 @@ public void CopyColumns(int width, int height, int startIndex, int destIndex, in public void CopyColumns_InvokeMultipleTimes() { var rnd = new Random(123); - using Buffer2D b = this.MemoryAllocator.Allocate2D(100, 100); - rnd.RandomFill(b.GetSpan(), 0, 1); + using (Buffer2D b = this.MemoryAllocator.Allocate2D(100, 100)) + { + rnd.RandomFill(b.GetSpan(), 0, 1); - b.CopyColumns(0, 50, 22); - b.CopyColumns(0, 50, 22); + b.CopyColumns(0, 50, 22); + b.CopyColumns(0, 50, 22); - for (int y = 0; y < b.Height; y++) - { - Span row = b.GetRowSpan(y); + for (int y = 0; y < b.Height; y++) + { + Span row = b.GetRowSpan(y); - Span s = row.Slice(0, 22); - Span d = row.Slice(50, 22); + Span s = row.Slice(0, 22); + Span d = row.Slice(50, 22); - Xunit.Assert.True(s.SequenceEqual(d)); + Xunit.Assert.True(s.SequenceEqual(d)); + } } } } diff --git a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs index 72e6305c74..9f523156f5 100644 --- a/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs +++ b/tests/ImageSharp.Tests/Memory/BufferAreaTests.cs @@ -12,12 +12,14 @@ public class BufferAreaTests [Fact] public void Construct() { - using var buffer = Configuration.Default.MemoryAllocator.Allocate2D(10, 20); - var rectangle = new Rectangle(3, 2, 5, 6); - var area = new BufferArea(buffer, rectangle); + using (var buffer = Configuration.Default.MemoryAllocator.Allocate2D(10, 20)) + { + var rectangle = new Rectangle(3, 2, 5, 6); + var area = new BufferArea(buffer, rectangle); - Assert.Equal(buffer, area.DestinationBuffer); - Assert.Equal(rectangle, area.Rectangle); + Assert.Equal(buffer, area.DestinationBuffer); + Assert.Equal(rectangle, area.Rectangle); + } } private static Buffer2D CreateTestBuffer(int w, int h) @@ -39,14 +41,16 @@ private static Buffer2D CreateTestBuffer(int w, int h) [InlineData(5, 4, 3, 2)] public void Indexer(int rx, int ry, int x, int y) { - using Buffer2D buffer = CreateTestBuffer(20, 30); - var r = new Rectangle(rx, ry, 5, 6); + using (Buffer2D buffer = CreateTestBuffer(20, 30)) + { + var r = new Rectangle(rx, ry, 5, 6); - BufferArea area = buffer.GetArea(r); + BufferArea area = buffer.GetArea(r); - int value = area[x, y]; - int expected = ((ry + y) * 100) + rx + x; - Assert.Equal(expected, value); + int value = area[x, y]; + int expected = ((ry + y) * 100) + rx + x; + Assert.Equal(expected, value); + } } [Theory] @@ -54,79 +58,89 @@ public void Indexer(int rx, int ry, int x, int y) [InlineData(5, 4, 3, 6, 5)] public void GetRowSpan(int rx, int ry, int y, int w, int h) { - using Buffer2D buffer = CreateTestBuffer(20, 30); - var r = new Rectangle(rx, ry, w, h); + using (Buffer2D buffer = CreateTestBuffer(20, 30)) + { + var r = new Rectangle(rx, ry, w, h); - BufferArea area = buffer.GetArea(r); + BufferArea area = buffer.GetArea(r); - Span span = area.GetRowSpan(y); + Span span = area.GetRowSpan(y); - Assert.Equal(w, span.Length); + Assert.Equal(w, span.Length); - for (int i = 0; i < w; i++) - { - int expected = ((ry + y) * 100) + rx + i; - int value = span[i]; + for (int i = 0; i < w; i++) + { + int expected = ((ry + y) * 100) + rx + i; + int value = span[i]; - Assert.Equal(expected, value); + Assert.Equal(expected, value); + } } } [Fact] public void GetSubArea() { - using Buffer2D buffer = CreateTestBuffer(20, 30); - BufferArea area0 = buffer.GetArea(6, 8, 10, 10); + using (Buffer2D buffer = CreateTestBuffer(20, 30)) + { + BufferArea area0 = buffer.GetArea(6, 8, 10, 10); - BufferArea area1 = area0.GetSubArea(4, 4, 5, 5); + BufferArea area1 = area0.GetSubArea(4, 4, 5, 5); - var expectedRect = new Rectangle(10, 12, 5, 5); + var expectedRect = new Rectangle(10, 12, 5, 5); - Assert.Equal(buffer, area1.DestinationBuffer); - Assert.Equal(expectedRect, area1.Rectangle); + Assert.Equal(buffer, area1.DestinationBuffer); + Assert.Equal(expectedRect, area1.Rectangle); - int value00 = (12 * 100) + 10; - Assert.Equal(value00, area1[0, 0]); + int value00 = (12 * 100) + 10; + Assert.Equal(value00, area1[0, 0]); + } } [Fact] public void DangerousGetPinnableReference() { - using Buffer2D buffer = CreateTestBuffer(20, 30); - BufferArea area0 = buffer.GetArea(6, 8, 10, 10); + using (Buffer2D buffer = CreateTestBuffer(20, 30)) + { + BufferArea area0 = buffer.GetArea(6, 8, 10, 10); - ref int r = ref area0.GetReferenceToOrigin(); + ref int r = ref area0.GetReferenceToOrigin(); - int expected = buffer[6, 8]; - Assert.Equal(expected, r); + int expected = buffer[6, 8]; + Assert.Equal(expected, r); + } } [Fact] public void Clear_FullArea() { - using Buffer2D buffer = CreateTestBuffer(22, 13); - buffer.GetArea().Clear(); - Span fullSpan = buffer.GetSpan(); - Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length])); + using (Buffer2D buffer = CreateTestBuffer(22, 13)) + { + buffer.GetArea().Clear(); + Span fullSpan = buffer.GetSpan(); + Assert.True(fullSpan.SequenceEqual(new int[fullSpan.Length])); + } } [Fact] public void Clear_SubArea() { - using Buffer2D buffer = CreateTestBuffer(20, 30); - BufferArea area = buffer.GetArea(5, 5, 10, 10); - area.Clear(); + using (Buffer2D buffer = CreateTestBuffer(20, 30)) + { + BufferArea area = buffer.GetArea(5, 5, 10, 10); + area.Clear(); - Assert.NotEqual(0, buffer[4, 4]); - Assert.NotEqual(0, buffer[15, 15]); + Assert.NotEqual(0, buffer[4, 4]); + Assert.NotEqual(0, buffer[15, 15]); - Assert.Equal(0, buffer[5, 5]); - Assert.Equal(0, buffer[14, 14]); + Assert.Equal(0, buffer[5, 5]); + Assert.Equal(0, buffer[14, 14]); - for (int y = area.Rectangle.Y; y < area.Rectangle.Bottom; y++) - { - Span span = buffer.GetRowSpan(y).Slice(area.Rectangle.X, area.Width); - Assert.True(span.SequenceEqual(new int[area.Width])); + for (int y = area.Rectangle.Y; y < area.Rectangle.Bottom; y++) + { + Span span = buffer.GetRowSpan(y).Slice(area.Rectangle.X, area.Width); + Assert.True(span.SequenceEqual(new int[area.Width])); + } } } } diff --git a/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs b/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs index 8f8cb016a5..60d791e91e 100644 --- a/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs +++ b/tests/ImageSharp.Tests/Metadata/ImageMetadataTests.cs @@ -90,15 +90,17 @@ public void SyncProfiles() exifProfile.SetValue(ExifTag.XResolution, new Rational(200)); exifProfile.SetValue(ExifTag.YResolution, new Rational(300)); - using var image = new Image(1, 1); - image.Metadata.ExifProfile = exifProfile; - image.Metadata.HorizontalResolution = 400; - image.Metadata.VerticalResolution = 500; + using (var image = new Image(1, 1)) + { + image.Metadata.ExifProfile = exifProfile; + image.Metadata.HorizontalResolution = 400; + image.Metadata.VerticalResolution = 500; - image.Metadata.SyncProfiles(); + image.Metadata.SyncProfiles(); - Assert.Equal(400, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); - Assert.Equal(500, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); + Assert.Equal(400, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.XResolution).Value).ToDouble()); + Assert.Equal(500, ((Rational)image.Metadata.ExifProfile.GetValue(ExifTag.YResolution).Value).ToDouble()); + } } } } diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs index d14f1027c9..79bf765455 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs @@ -92,40 +92,42 @@ public void ConstructorCopy() [InlineData(TestImageWriteFormat.Png)] public void WriteFraction(TestImageWriteFormat imageFormat) { - using var memStream = new MemoryStream(); - double exposureTime = 1.0 / 1600; + using (var memStream = new MemoryStream()) + { + double exposureTime = 1.0 / 1600; - ExifProfile profile = GetExifProfile(); + ExifProfile profile = GetExifProfile(); - profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime)); + profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime)); - var image = new Image(1, 1); - image.Metadata.ExifProfile = profile; + var image = new Image(1, 1); + image.Metadata.ExifProfile = profile; - image = WriteAndRead(image, imageFormat); + image = WriteAndRead(image, imageFormat); - profile = image.Metadata.ExifProfile; - Assert.NotNull(profile); + profile = image.Metadata.ExifProfile; + Assert.NotNull(profile); - IExifValue value = profile.GetValue(ExifTag.ExposureTime); - Assert.NotNull(value); - Assert.NotEqual(exposureTime, value.Value.ToDouble()); + IExifValue value = profile.GetValue(ExifTag.ExposureTime); + Assert.NotNull(value); + Assert.NotEqual(exposureTime, value.Value.ToDouble()); - memStream.Position = 0; - profile = GetExifProfile(); + memStream.Position = 0; + profile = GetExifProfile(); - profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime, true)); - image.Metadata.ExifProfile = profile; + profile.SetValue(ExifTag.ExposureTime, new Rational(exposureTime, true)); + image.Metadata.ExifProfile = profile; - image = WriteAndRead(image, imageFormat); + image = WriteAndRead(image, imageFormat); - profile = image.Metadata.ExifProfile; - Assert.NotNull(profile); + profile = image.Metadata.ExifProfile; + Assert.NotNull(profile); - value = profile.GetValue(ExifTag.ExposureTime); - Assert.Equal(exposureTime, value.Value.ToDouble()); + value = profile.GetValue(ExifTag.ExposureTime); + Assert.Equal(exposureTime, value.Value.ToDouble()); - image.Dispose(); + image.Dispose(); + } } [Theory] @@ -449,22 +451,26 @@ private static Image WriteAndRead(Image image, TestImageWriteFor private static Image WriteAndReadJpeg(Image image) { - using var memStream = new MemoryStream(); - image.SaveAsJpeg(memStream); - image.Dispose(); + using (var memStream = new MemoryStream()) + { + image.SaveAsJpeg(memStream); + image.Dispose(); - memStream.Position = 0; - return Image.Load(memStream); + memStream.Position = 0; + return Image.Load(memStream); + } } private static Image WriteAndReadPng(Image image) { - using var memStream = new MemoryStream(); - image.SaveAsPng(memStream); - image.Dispose(); + using (var memStream = new MemoryStream()) + { + image.SaveAsPng(memStream); + image.Dispose(); - memStream.Position = 0; - return Image.Load(memStream); + memStream.Position = 0; + return Image.Load(memStream); + } } private static void TestProfile(ExifProfile profile) diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs index 47b5dbbd2e..7f52fb6cae 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifValueTests.cs @@ -13,8 +13,10 @@ public class ExifValueTests public ExifValueTests() { - using Image image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image(); - this.profile = image.Metadata.ExifProfile; + using (Image image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image()) + { + this.profile = image.Metadata.ExifProfile; + } } private IExifValue GetExifValue() diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs index d57abb4996..a91ea09776 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelBlenders/PorterDuffCompositorTests.cs @@ -33,24 +33,28 @@ public class PorterDuffCompositorTests public void PorterDuffOutputIsCorrect(TestImageProvider provider, PixelAlphaCompositionMode mode) { var srcFile = TestFile.Create(TestImages.Png.PDSrc); - using Image src = srcFile.CreateRgba32Image(); - using Image dest = provider.GetImage(); - var options = new GraphicsOptions + using (Image src = srcFile.CreateRgba32Image()) + using (Image dest = provider.GetImage()) { - Antialias = false, - AlphaCompositionMode = mode - }; + var options = new GraphicsOptions + { + Antialias = false, + AlphaCompositionMode = mode + }; + + using (Image res = dest.Clone(x => x.DrawImage(src, options))) + { + string combinedMode = mode.ToString(); - using Image res = dest.Clone(x => x.DrawImage(src, options)); - string combinedMode = mode.ToString(); + if (combinedMode != "Src" && combinedMode.StartsWith("Src")) + { + combinedMode = combinedMode.Substring(3); + } - if (combinedMode != "Src" && combinedMode.StartsWith("Src")) - { - combinedMode = combinedMode.Substring(3); + res.DebugSave(provider, combinedMode); + res.CompareToReferenceOutput(provider, combinedMode); + } } - - res.DebugSave(provider, combinedMode); - res.CompareToReferenceOutput(provider, combinedMode); } } } diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs index 98a657950d..1ecbaf3615 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.Rgba32OperationsTests.cs +++ b/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. using System.Buffers; @@ -30,15 +30,17 @@ public void Benchmark_ToVector4() const int times = 200000; const int count = 1024; - using IMemoryOwner source = Configuration.Default.MemoryAllocator.Allocate(count); - using IMemoryOwner dest = Configuration.Default.MemoryAllocator.Allocate(count); - this.Measure( - times, - () => PixelOperations.Instance.ToVector4( - this.Configuration, - source.GetSpan(), - dest.GetSpan())); + using (IMemoryOwner source = Configuration.Default.MemoryAllocator.Allocate(count)) + using (IMemoryOwner dest = Configuration.Default.MemoryAllocator.Allocate(count)) + { + this.Measure( + times, + () => PixelOperations.Instance.ToVector4( + this.Configuration, + source.GetSpan(), + dest.GetSpan())); + } } } } -} +} \ No newline at end of file diff --git a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs index b572baa834..40b8122793 100644 --- a/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs +++ b/tests/ImageSharp.Tests/PixelFormats/PixelOperations/PixelOperationsTests.cs @@ -997,9 +997,11 @@ internal static void TestOperation( where TSource : struct where TDest : struct { - using var buffers = new TestBuffers(source, expected); - action(buffers.SourceBuffer, buffers.ActualDestBuffer); - buffers.Verify(); + using (var buffers = new TestBuffers(source, expected)) + { + action(buffers.SourceBuffer, buffers.ActualDestBuffer); + buffers.Verify(); + } } internal static Vector4[] CreateVector4TestData(int length, RefAction vectorModifier = null) diff --git a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs index d543d03934..b07545a364 100644 --- a/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs +++ b/tests/ImageSharp.Tests/Processing/Normalization/HistogramEqualizationTests.cs @@ -32,18 +32,19 @@ public void HistogramEqualizationTest(int luminanceLevels) 70, 87, 69, 68, 65, 73, 78, 90 }; - using var image = new Image(8, 8); - for (int y = 0; y < 8; y++) + using (var image = new Image(8, 8)) { - for (int x = 0; x < 8; x++) + for (int y = 0; y < 8; y++) { - byte luminance = pixels[(y * 8) + x]; - image[x, y] = new Rgba32(luminance, luminance, luminance); + for (int x = 0; x < 8; x++) + { + byte luminance = pixels[(y * 8) + x]; + image[x, y] = new Rgba32(luminance, luminance, luminance); + } } - } - var expected = new byte[] - { + var expected = new byte[] + { 0, 12, 53, 32, 146, 53, 174, 53, 57, 32, 12, 227, 219, 202, 32, 154, 65, 85, 93, 239, 251, 227, 65, 158, @@ -52,23 +53,24 @@ public void HistogramEqualizationTest(int luminanceLevels) 117, 190, 36, 190, 178, 93, 20, 170, 130, 202, 73, 20, 12, 53, 85, 194, 146, 206, 130, 117, 85, 166, 182, 215 - }; + }; - // Act - image.Mutate(x => x.HistogramEqualization(new HistogramEqualizationOptions - { - LuminanceLevels = luminanceLevels - })); + // Act + image.Mutate(x => x.HistogramEqualization(new HistogramEqualizationOptions + { + LuminanceLevels = luminanceLevels + })); - // Assert - for (int y = 0; y < 8; y++) - { - for (int x = 0; x < 8; x++) + // Assert + for (int y = 0; y < 8; y++) { - Rgba32 actual = image[x, y]; - Assert.Equal(expected[(y * 8) + x], actual.R); - Assert.Equal(expected[(y * 8) + x], actual.G); - Assert.Equal(expected[(y * 8) + x], actual.B); + for (int x = 0; x < 8; x++) + { + Rgba32 actual = image[x, y]; + Assert.Equal(expected[(y * 8) + x], actual.R); + Assert.Equal(expected[(y * 8) + x], actual.G); + Assert.Equal(expected[(y * 8) + x], actual.B); + } } } } @@ -78,17 +80,19 @@ public void HistogramEqualizationTest(int luminanceLevels) public void Adaptive_SlidingWindow_15Tiles_WithClipping(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new HistogramEqualizationOptions + using (Image image = provider.GetImage()) { - Method = HistogramEqualizationMethod.AdaptiveSlidingWindow, - LuminanceLevels = 256, - ClipHistogram = true, - NumberOfTiles = 15 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + var options = new HistogramEqualizationOptions + { + Method = HistogramEqualizationMethod.AdaptiveSlidingWindow, + LuminanceLevels = 256, + ClipHistogram = true, + NumberOfTiles = 15 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -96,17 +100,19 @@ public void Adaptive_SlidingWindow_15Tiles_WithClipping(TestImageProvide public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new HistogramEqualizationOptions + using (Image image = provider.GetImage()) { - Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, - LuminanceLevels = 256, - ClipHistogram = true, - NumberOfTiles = 10 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + var options = new HistogramEqualizationOptions + { + Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, + LuminanceLevels = 256, + ClipHistogram = true, + NumberOfTiles = 10 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } /// @@ -121,18 +127,20 @@ public void Adaptive_TileInterpolation_10Tiles_WithClipping(TestImagePro public void Issue984(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new HistogramEqualizationOptions() + using (Image image = provider.GetImage()) { - Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, - LuminanceLevels = 256, - ClipHistogram = true, - ClipLimit = 5, - NumberOfTiles = 10 - }; - image.Mutate(x => x.HistogramEqualization(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + var options = new HistogramEqualizationOptions() + { + Method = HistogramEqualizationMethod.AdaptiveTileInterpolation, + LuminanceLevels = 256, + ClipHistogram = true, + ClipLimit = 5, + NumberOfTiles = 10 + }; + image.Mutate(x => x.HistogramEqualization(options)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs index 4f69e55b6f..7d9e0f04b4 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryDitherTests.cs @@ -51,9 +51,11 @@ public class BinaryDitherTests public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider provider, string name, IOrderedDither ditherer) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.BinaryDither(ditherer)); - image.DebugSave(provider, name); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.BinaryDither(ditherer)); + image.DebugSave(provider, name); + } } [Theory] @@ -62,9 +64,11 @@ public void BinaryDitherFilter_WorksWithAllDitherers(TestImageProvider(TestImageProvider provider, string name, IErrorDiffuser diffuser) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.BinaryDiffuse(diffuser, .5F)); - image.DebugSave(provider, name); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.BinaryDiffuse(diffuser, .5F)); + image.DebugSave(provider, name); + } } [Theory] @@ -72,9 +76,11 @@ public void DiffusionFilter_WorksWithAllErrorDiffusers(TestImageProvider public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.BinaryDither(DefaultDitherer)); - image.DebugSave(provider); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.BinaryDither(DefaultDitherer)); + image.DebugSave(provider); + } } [Theory] @@ -82,9 +88,11 @@ public void BinaryDitherFilter_ShouldNotDependOnSinglePixelType(TestImag public void DiffusionFilter_ShouldNotDependOnSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f)); - image.DebugSave(provider); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, 0.5f)); + image.DebugSave(provider); + } } [Theory] @@ -92,14 +100,16 @@ public void DiffusionFilter_ShouldNotDependOnSinglePixelType(TestImagePr public void ApplyDitherFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { - using Image source = provider.GetImage(); - using Image image = source.Clone(); - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using (Image source = provider.GetImage()) + using (Image image = source.Clone()) + { + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds)); - image.DebugSave(provider); + image.Mutate(x => x.BinaryDither(DefaultDitherer, bounds)); + image.DebugSave(provider); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + } } [Theory] @@ -107,14 +117,16 @@ public void ApplyDitherFilterInBox(TestImageProvider provider) public void ApplyDiffusionFilterInBox(TestImageProvider provider) where TPixel : struct, IPixel { - using Image source = provider.GetImage(); - using Image image = source.Clone(); - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using (Image source = provider.GetImage()) + using (Image image = source.Clone()) + { + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds)); - image.DebugSave(provider); + image.Mutate(x => x.BinaryDiffuse(DefaultErrorDiffuser, .5F, bounds)); + image.DebugSave(provider); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs index 047e5fdc1b..54ff77f935 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Binarization/BinaryThresholdTest.cs @@ -30,9 +30,11 @@ public static readonly TheoryData BinaryThresholdValues public void ImageShouldApplyBinaryThresholdFilter(TestImageProvider provider, float value) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.BinaryThreshold(value)); - image.DebugSave(provider, value); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.BinaryThreshold(value)); + image.DebugSave(provider, value); + } } [Theory] @@ -40,14 +42,16 @@ public void ImageShouldApplyBinaryThresholdFilter(TestImageProvider(TestImageProvider provider, float value) where TPixel : struct, IPixel { - using Image source = provider.GetImage(); - using var image = source.Clone(); - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using (Image source = provider.GetImage()) + using (var image = source.Clone()) + { + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.BinaryThreshold(value, bounds)); - image.DebugSave(provider, value); + image.Mutate(x => x.BinaryThreshold(value, bounds)); + image.DebugSave(provider, value); - ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + ImageComparer.Tolerant().VerifySimilarityIgnoreRegion(source, image, bounds); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs index b68278747b..fcd9eb3cdd 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs @@ -60,19 +60,23 @@ public void VerifyComplexComponents() } // Make sure the kernel components are the same - using var image = new Image(1, 1); - Configuration configuration = image.GetConfiguration(); - var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); - using var processor = (BokehBlurProcessor)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds()); - Assert.Equal(components.Count, processor.Kernels.Count); - foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) + using (var image = new Image(1, 1)) { - Span spanA = a.AsSpan(), spanB = b.AsSpan(); - Assert.Equal(spanA.Length, spanB.Length); - for (int i = 0; i < spanA.Length; i++) + Configuration configuration = image.GetConfiguration(); + var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); + using (var processor = (BokehBlurProcessor)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds())) { - Assert.True(Math.Abs(Math.Abs(spanA[i].Real) - Math.Abs(spanB[i].Real)) < 0.0001f); - Assert.True(Math.Abs(Math.Abs(spanA[i].Imaginary) - Math.Abs(spanB[i].Imaginary)) < 0.0001f); + Assert.Equal(components.Count, processor.Kernels.Count); + foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) + { + Span spanA = a.AsSpan(), spanB = b.AsSpan(); + Assert.Equal(spanA.Length, spanB.Length); + for (int i = 0; i < spanA.Length; i++) + { + Assert.True(Math.Abs(Math.Abs(spanA[i].Real) - Math.Abs(spanB[i].Real)) < 0.0001f); + Assert.True(Math.Abs(Math.Abs(spanA[i].Imaginary) - Math.Abs(spanB[i].Imaginary)) < 0.0001f); + } + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs index 80cd4158c9..a1f34856e5 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Convolution/DetectEdgesTest.cs @@ -56,10 +56,12 @@ public void DetectEdges_WorksOnWrappedMemoryImage(TestImageProvider(TestImageProvider provider, EdgeDetectionOperators detector) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.DetectEdges(detector)); - image.DebugSave(provider, detector.ToString()); - image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString()); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.DetectEdges(detector)); + image.DebugSave(provider, detector.ToString()); + image.CompareToReferenceOutput(ValidatorComparer, provider, detector.ToString()); + } } [Theory] @@ -67,10 +69,12 @@ public void DetectEdges_WorksWithAllFilters(TestImageProvider pr public void DetectEdges_IsNotBoundToSinglePixelType(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.DetectEdges()); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.DetectEdges()); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -78,9 +82,11 @@ public void DetectEdges_IsNotBoundToSinglePixelType(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.DetectEdges()); - image.DebugSave(provider, extension: "gif"); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.DetectEdges()); + image.DebugSave(provider, extension: "gif"); + } } [Theory] @@ -88,12 +94,14 @@ public void DetectEdges_IsAppliedToAllFrames(TestImageProvider p public void DetectEdges_InBox(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); + using (Image image = provider.GetImage()) + { + var bounds = new Rectangle(10, 10, image.Width / 2, image.Height / 2); - image.Mutate(x => x.DetectEdges(bounds)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.Mutate(x => x.DetectEdges(bounds)); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs index 8cca265477..68852a939a 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/AutoOrientTests.cs @@ -44,13 +44,15 @@ public static readonly TheoryData InvalidOrientationValues public void AutoOrient_WorksForAllExifOrientations(TestImageProvider provider, ushort orientation) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Metadata.ExifProfile = new ExifProfile(); - image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation); + using (Image image = provider.GetImage()) + { + image.Metadata.ExifProfile = new ExifProfile(); + image.Metadata.ExifProfile.SetValue(ExifTag.Orientation, orientation); - image.Mutate(x => x.AutoOrient()); - image.DebugSave(provider, orientation, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false); + image.Mutate(x => x.AutoOrient()); + image.DebugSave(provider, orientation, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, orientation, appendPixelTypeToFileName: false); + } } [Theory] @@ -78,12 +80,14 @@ public void AutoOrient_WorksWithCorruptExifData(TestImageProvider image = provider.GetImage(); - using Image reference = image.Clone(); - image.Metadata.ExifProfile = new ExifProfile(bytes); - image.Mutate(x => x.AutoOrient()); - image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false); - ImageComparer.Exact.VerifySimilarity(image, reference); + using (Image image = provider.GetImage()) + using (Image reference = image.Clone()) + { + image.Metadata.ExifProfile = new ExifProfile(bytes); + image.Mutate(x => x.AutoOrient()); + image.DebugSave(provider, $"{dataType}-{orientationCode}", appendPixelTypeToFileName: false); + ImageComparer.Exact.VerifySimilarity(image, reference); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs index edaccb7534..dbaff43f0c 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/PadTest.cs @@ -19,16 +19,18 @@ public class PadTest public void ImageShouldPad(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50)); - image.DebugSave(provider); - - // Check pixels are empty - for (int y = 0; y < 25; y++) + using (Image image = provider.GetImage()) { - for (int x = 0; x < 25; x++) + image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50)); + image.DebugSave(provider); + + // Check pixels are empty + for (int y = 0; y < 25; y++) { - Assert.Equal(default, image[x, y]); + for (int x = 0; x < 25; x++) + { + Assert.Equal(default, image[x, y]); + } } } } @@ -40,16 +42,18 @@ public void ImageShouldPadWithBackgroundColor(TestImageProvider { var color = Color.Red; TPixel expected = color.ToPixel(); - using Image image = provider.GetImage(); - image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color)); - image.DebugSave(provider); - - // Check pixels are filled - for (int y = 0; y < 25; y++) + using (Image image = provider.GetImage()) { - for (int x = 0; x < 25; x++) + image.Mutate(x => x.Pad(image.Width + 50, image.Height + 50, color)); + image.DebugSave(provider); + + // Check pixels are filled + for (int y = 0; y < 25; y++) { - Assert.Equal(expected, image[x, y]); + for (int x = 0; x < 25; x++) + { + Assert.Equal(expected, image[x, y]); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs index 4e5ffbfab2..fa23962517 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs +++ b/tests/ImageSharp.Tests/Processing/Processors/Transforms/ResizeTests.cs @@ -5,14 +5,12 @@ using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; - using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors.Transforms; using SixLabors.ImageSharp.Tests.Memory; using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; - using Xunit; // ReSharper disable InconsistentNaming @@ -44,13 +42,15 @@ public void Resize_PixelAgnostic() { string filePath = TestFile.GetInputFileFullPath(TestImages.Jpeg.Baseline.Calliphora); - using var image = Image.Load(filePath); - image.Mutate(x => x.Resize(image.Size() / 2)); - string path = System.IO.Path.Combine( - TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)), - nameof(this.Resize_PixelAgnostic) + ".png"); + using (var image = Image.Load(filePath)) + { + image.Mutate(x => x.Resize(image.Size() / 2)); + string path = System.IO.Path.Combine( + TestEnvironment.CreateOutputDirectory(nameof(ResizeTests)), + nameof(this.Resize_PixelAgnostic) + ".png"); - image.Save(path); + image.Save(path); + } } [Theory(Skip = "Debug only, enable manually")] @@ -67,9 +67,11 @@ public void LargeImage(TestImageProvider provider, int destSize, provider.Configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInKilobytes * 1024; - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(destSize, destSize)); - image.DebugSave(provider, appendPixelTypeToFileName: false); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(destSize, destSize)); + image.DebugSave(provider, appendPixelTypeToFileName: false); + } } [Theory] @@ -83,12 +85,14 @@ public void Resize_BasicSmall(TestImageProvider provider, int wN // [WithBasicTestPatternImages(15, 12, PixelTypes.Rgba32, 2, 3, 1, 2)] means: // resizing: (15, 12) -> (10, 6) // kernel dimensions: (3, 4) - using Image image = provider.GetImage(); - var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); - image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); - FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})"; - image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false); + using (Image image = provider.GetImage()) + { + var destSize = new Size(image.Width * wN / wD, image.Height * hN / hD); + image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); + FormattableString outputInfo = $"({wN}÷{wD},{hN}÷{hD})"; + image.DebugSave(provider, outputInfo, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, outputInfo, appendPixelTypeToFileName: false); + } } private static readonly int SizeOfVector4 = Unsafe.SizeOf(); @@ -106,43 +110,47 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( int workingBufferLimitInRows) where TPixel : struct, IPixel { - using Image image0 = provider.GetImage(); - Size destSize = image0.Size() / 4; - - var configuration = Configuration.CreateDefaultInstance(); - - int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4; - var allocator = new TestMemoryAllocator(); - configuration.MemoryAllocator = allocator; - configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes; - - var verticalKernelMap = ResizeKernelMap.Calculate( - KnownResamplers.Bicubic, - destSize.Height, - image0.Height, - Configuration.Default.MemoryAllocator); - int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4; - verticalKernelMap.Dispose(); - - using Image image = image0.Clone(configuration); - image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); - - image.DebugSave( - provider, - testOutputDetails: workingBufferLimitInRows, - appendPixelTypeToFileName: false); - image.CompareToReferenceOutput( - ImageComparer.TolerantPercentage(0.001f), - provider, - testOutputDetails: workingBufferLimitInRows, - appendPixelTypeToFileName: false); + using (Image image0 = provider.GetImage()) + { + Size destSize = image0.Size() / 4; - Assert.NotEmpty(allocator.AllocationLog); + var configuration = Configuration.CreateDefaultInstance(); - int maxAllocationSize = allocator.AllocationLog.Where( - e => e.ElementType == typeof(Vector4)).Max(e => e.LengthInBytes); + int workingBufferSizeHintInBytes = workingBufferLimitInRows * destSize.Width * SizeOfVector4; + var allocator = new TestMemoryAllocator(); + configuration.MemoryAllocator = allocator; + configuration.WorkingBufferSizeHintInBytes = workingBufferSizeHintInBytes; - Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes)); + var verticalKernelMap = ResizeKernelMap.Calculate( + KnownResamplers.Bicubic, + destSize.Height, + image0.Height, + Configuration.Default.MemoryAllocator); + int minimumWorkerAllocationInBytes = verticalKernelMap.MaxDiameter * 2 * destSize.Width * SizeOfVector4; + verticalKernelMap.Dispose(); + + using (Image image = image0.Clone(configuration)) + { + image.Mutate(x => x.Resize(destSize, KnownResamplers.Bicubic, false)); + + image.DebugSave( + provider, + testOutputDetails: workingBufferLimitInRows, + appendPixelTypeToFileName: false); + image.CompareToReferenceOutput( + ImageComparer.TolerantPercentage(0.001f), + provider, + testOutputDetails: workingBufferLimitInRows, + appendPixelTypeToFileName: false); + + Assert.NotEmpty(allocator.AllocationLog); + + int maxAllocationSize = allocator.AllocationLog.Where( + e => e.ElementType == typeof(Vector4)).Max(e => e.LengthInBytes); + + Assert.True(maxAllocationSize <= Math.Max(workingBufferSizeHintInBytes, minimumWorkerAllocationInBytes)); + } + } } [Theory] @@ -150,11 +158,13 @@ public void WorkingBufferSizeHintInBytes_IsAppliedCorrectly( public void Resize_Compand(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(image.Size() / 2, true)); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(image.Size() / 2, true)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -177,11 +187,13 @@ public void Resize_DoesNotBleedAlphaPixels(TestImageProvider pro public void Resize_IsAppliedToAllFrames(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic)); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2, KnownResamplers.Bicubic)); - // Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :( - image.DebugSave(provider, extension: "gif"); + // Comparer fights decoder with gif-s. Could not use CompareToReferenceOutput here :( + image.DebugSave(provider, extension: "gif"); + } } [Theory] @@ -197,12 +209,16 @@ public void Resize_IsNotBoundToSinglePixelType(TestImageProvider public void Resize_ThrowsForWrappedMemoryImage(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image0 = provider.GetImage(); - var mmg = TestMemoryManager.CreateAsCopyOf(image0.GetPixelSpan()); + using (Image image0 = provider.GetImage()) + { + var mmg = TestMemoryManager.CreateAsCopyOf(image0.GetPixelSpan()); - using var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height); - Assert.ThrowsAny( - () => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); }); + using (var image1 = Image.WrapMemory(mmg.Memory, image0.Width, image0.Height)) + { + Assert.ThrowsAny( + () => { image1.Mutate(x => x.Resize(image0.Width / 2, image0.Height / 2, true)); }); + } + } } [Theory] @@ -275,31 +291,31 @@ public void Resize_WorksWithAllResamplers( provider.RunValidatingProcessorTest( ctx => + { + SizeF newSize; + string destSizeInfo; + if (ratio.HasValue) { - SizeF newSize; - string destSizeInfo; - if (ratio.HasValue) - { - newSize = ctx.GetCurrentSize() * ratio.Value; - destSizeInfo = ratio.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); - } - else + newSize = ctx.GetCurrentSize() * ratio.Value; + destSizeInfo = ratio.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + else + { + if (!specificDestWidth.HasValue || !specificDestHeight.HasValue) { - if (!specificDestWidth.HasValue || !specificDestHeight.HasValue) - { - throw new InvalidOperationException( - "invalid dimensional input for Resize_WorksWithAllResamplers!"); - } - - newSize = new SizeF(specificDestWidth.Value, specificDestHeight.Value); - destSizeInfo = $"{newSize.Width}x{newSize.Height}"; + throw new InvalidOperationException( + "invalid dimensional input for Resize_WorksWithAllResamplers!"); } - FormattableString testOutputDetails = $"{samplerName}-{destSizeInfo}"; + newSize = new SizeF(specificDestWidth.Value, specificDestHeight.Value); + destSizeInfo = $"{newSize.Width}x{newSize.Height}"; + } + + FormattableString testOutputDetails = $"{samplerName}-{destSizeInfo}"; - ctx.Resize((Size)newSize, sampler, false); - return testOutputDetails; - }, + ctx.Resize((Size)newSize, sampler, false); + return testOutputDetails; + }, comparer, appendPixelTypeToFileName: false); } @@ -309,25 +325,27 @@ public void Resize_WorksWithAllResamplers( public void ResizeFromSourceRectangle(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var sourceRectangle = new Rectangle( - image.Width / 8, - image.Height / 8, - image.Width / 4, - image.Height / 4); - var destRectangle = new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2); - - image.Mutate( - x => x.Resize( - image.Width, - image.Height, - KnownResamplers.Bicubic, - sourceRectangle, - destRectangle, - false)); - - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + using (Image image = provider.GetImage()) + { + var sourceRectangle = new Rectangle( + image.Width / 8, + image.Height / 8, + image.Width / 4, + image.Height / 4); + var destRectangle = new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2); + + image.Mutate( + x => x.Resize( + image.Width, + image.Height, + KnownResamplers.Bicubic, + sourceRectangle, + destRectangle, + false)); + + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -335,11 +353,13 @@ public void ResizeFromSourceRectangle(TestImageProvider provider public void ResizeHeightAndKeepAspect(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(0, image.Height / 3, false)); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(0, image.Height / 3, false)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -347,10 +367,12 @@ public void ResizeHeightAndKeepAspect(TestImageProvider provider public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(0, 5)); - Assert.Equal(1, image.Width); - Assert.Equal(5, image.Height); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(0, 5)); + Assert.Equal(1, image.Width); + Assert.Equal(5, image.Height); + } } [Theory] @@ -358,11 +380,13 @@ public void ResizeHeightCannotKeepAspectKeepsOnePixel(TestImageProvider< public void ResizeWidthAndKeepAspect(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(image.Width / 3, 0, false)); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(image.Width / 3, 0, false)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -370,10 +394,12 @@ public void ResizeWidthAndKeepAspect(TestImageProvider provider) public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.Resize(5, 0)); - Assert.Equal(5, image.Width); - Assert.Equal(1, image.Height); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.Resize(5, 0)); + Assert.Equal(5, image.Width); + Assert.Equal(1, image.Height); + } } [Theory] @@ -381,17 +407,19 @@ public void ResizeWidthCannotKeepAspectKeepsOnePixel(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions + using (Image image = provider.GetImage()) { - Size = new Size(image.Width + 200, image.Height + 200), - Mode = ResizeMode.BoxPad - }; + var options = new ResizeOptions + { + Size = new Size(image.Width + 200, image.Height + 200), + Mode = ResizeMode.BoxPad + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -399,13 +427,15 @@ public void ResizeWithBoxPadMode(TestImageProvider provider) public void ResizeWithCropHeightMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) }; + using (Image image = provider.GetImage()) + { + var options = new ResizeOptions { Size = new Size(image.Width, image.Height / 2) }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -413,13 +443,15 @@ public void ResizeWithCropHeightMode(TestImageProvider provider) public void ResizeWithCropWidthMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) }; + using (Image image = provider.GetImage()) + { + var options = new ResizeOptions { Size = new Size(image.Width / 2, image.Height) }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -427,17 +459,19 @@ public void ResizeWithCropWidthMode(TestImageProvider provider) public void CanResizeLargeImageWithCropMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions + using (Image image = provider.GetImage()) { - Size = new Size(480, 600), - Mode = ResizeMode.Crop - }; + var options = new ResizeOptions + { + Size = new Size(480, 600), + Mode = ResizeMode.Crop + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -445,13 +479,15 @@ public void CanResizeLargeImageWithCropMode(TestImageProvider pr public void ResizeWithMaxMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max }; + using (Image image = provider.GetImage()) + { + var options = new ResizeOptions { Size = new Size(300, 300), Mode = ResizeMode.Max }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -459,19 +495,21 @@ public void ResizeWithMaxMode(TestImageProvider provider) public void ResizeWithMinMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions + using (Image image = provider.GetImage()) { - Size = new Size( - (int)Math.Round(image.Width * .75F), - (int)Math.Round(image.Height * .95F)), - Mode = ResizeMode.Min - }; - - image.Mutate(x => x.Resize(options)); - - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + var options = new ResizeOptions + { + Size = new Size( + (int)Math.Round(image.Width * .75F), + (int)Math.Round(image.Height * .95F)), + Mode = ResizeMode.Min + }; + + image.Mutate(x => x.Resize(options)); + + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -479,17 +517,19 @@ public void ResizeWithMinMode(TestImageProvider provider) public void ResizeWithPadMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions + using (Image image = provider.GetImage()) { - Size = new Size(image.Width + 200, image.Height), - Mode = ResizeMode.Pad - }; + var options = new ResizeOptions + { + Size = new Size(image.Width + 200, image.Height), + Mode = ResizeMode.Pad + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -497,17 +537,19 @@ public void ResizeWithPadMode(TestImageProvider provider) public void ResizeWithStretchMode(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - var options = new ResizeOptions + using (Image image = provider.GetImage()) { - Size = new Size(image.Width / 2, image.Height), - Mode = ResizeMode.Stretch - }; + var options = new ResizeOptions + { + Size = new Size(image.Width / 2, image.Height), + Mode = ResizeMode.Stretch + }; - image.Mutate(x => x.Resize(options)); + image.Mutate(x => x.Resize(options)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -523,10 +565,11 @@ public void CanResizeExifIssueImages(TestImageProvider provider) return; } - using Image image = provider.GetImage(); - - // Don't bother saving, we're testing the EXIF metadata updates. - image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2)); + using (Image image = provider.GetImage()) + { + // Don't bother saving, we're testing the EXIF metadata updates. + image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2)); + } } } } diff --git a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs b/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs index a1c03a3d3b..1e08836c13 100644 --- a/tests/ImageSharp.Tests/Processing/Processors/Transforms/RotateFlipTests.cs +++ b/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. using SixLabors.ImageSharp.PixelFormats; @@ -29,9 +29,11 @@ public static readonly TheoryData RotateFlipValues public void RotateFlip(TestImageProvider provider, RotateMode rotateType, FlipMode flipType) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.Mutate(x => x.RotateFlip(rotateType, flipType)); - image.DebugSave(provider, string.Join("_", rotateType, flipType)); + using (Image image = provider.GetImage()) + { + image.Mutate(x => x.RotateFlip(rotateType, flipType)); + image.DebugSave(provider, string.Join("_", rotateType, flipType)); + } } } -} +} \ No newline at end of file diff --git a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs index 016a77fd0c..399f1665ff 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/AffineTransformTests.cs @@ -80,14 +80,16 @@ public void Transform_DoesNotCreateEdgeArtifacts(TestImageProvider { IResampler resampler = GetResampler(resamplerName); - using Image image = provider.GetImage(); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(30); + using (Image image = provider.GetImage()) + { + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(30); - image.Mutate(c => c.Transform(builder, resampler)); - image.DebugSave(provider, resamplerName); + image.Mutate(c => c.Transform(builder, resampler)); + image.DebugSave(provider, resamplerName); - VerifyAllPixelsAreWhiteOrTransparent(image); + VerifyAllPixelsAreWhiteOrTransparent(image); + } } [Theory] @@ -101,20 +103,22 @@ public void Transform_RotateScaleTranslate( float ty) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.DebugSave(provider, $"_original"); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(angleDeg) - .AppendScale(new SizeF(sx, sy)) - .AppendTranslation(new PointF(tx, ty)); + using (Image image = provider.GetImage()) + { + image.DebugSave(provider, $"_original"); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(angleDeg) + .AppendScale(new SizeF(sx, sy)) + .AppendTranslation(new PointF(tx, ty)); - this.PrintMatrix(builder.BuildMatrix(image.Size())); + this.PrintMatrix(builder.BuildMatrix(image.Size())); - image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); + image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); - FormattableString testOutputDetails = $"R({angleDeg})_S({sx},{sy})_T({tx},{ty})"; - image.DebugSave(provider, testOutputDetails); - image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); + FormattableString testOutputDetails = $"R({angleDeg})_S({sx},{sy})_T({tx},{ty})"; + image.DebugSave(provider, testOutputDetails); + image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); + } } [Theory] @@ -122,16 +126,18 @@ public void Transform_RotateScaleTranslate( public void Transform_RotateScale_ManuallyCentered(TestImageProvider provider, float angleDeg, float s) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(angleDeg) - .AppendScale(new SizeF(s, s)); + using (Image image = provider.GetImage()) + { + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(angleDeg) + .AppendScale(new SizeF(s, s)); - image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); + image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic)); - FormattableString testOutputDetails = $"R({angleDeg})_S({s})"; - image.DebugSave(provider, testOutputDetails); - image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); + FormattableString testOutputDetails = $"R({angleDeg})_S({s})"; + image.DebugSave(provider, testOutputDetails); + image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails); + } } public static readonly TheoryData Transform_IntoRectangle_Data = @@ -156,15 +162,17 @@ public void Transform_FromSourceRectangle1(TestImageProvider pro { var rectangle = new Rectangle(48, 0, 48, 24); - using Image image = provider.GetImage(); - image.DebugSave(provider, $"_original"); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendScale(new SizeF(2, 1.5F)); + using (Image image = provider.GetImage()) + { + image.DebugSave(provider, $"_original"); + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendScale(new SizeF(2, 1.5F)); - image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); + image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -174,14 +182,16 @@ public void Transform_FromSourceRectangle2(TestImageProvider pro { var rectangle = new Rectangle(0, 24, 48, 24); - using Image image = provider.GetImage(); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendScale(new SizeF(1F, 2F)); + using (Image image = provider.GetImage()) + { + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendScale(new SizeF(1F, 2F)); - image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); + image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline)); - image.DebugSave(provider); - image.CompareToReferenceOutput(ValidatorComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(ValidatorComparer, provider); + } } [Theory] @@ -190,15 +200,17 @@ public void Transform_WithSampler(TestImageProvider provider, st where TPixel : struct, IPixel { IResampler sampler = GetResampler(resamplerName); - using Image image = provider.GetImage(); - AffineTransformBuilder builder = new AffineTransformBuilder() - .AppendRotationDegrees(50) - .AppendScale(new SizeF(.6F, .6F)); + using (Image image = provider.GetImage()) + { + AffineTransformBuilder builder = new AffineTransformBuilder() + .AppendRotationDegrees(50) + .AppendScale(new SizeF(.6F, .6F)); - image.Mutate(i => i.Transform(builder, sampler)); + image.Mutate(i => i.Transform(builder, sampler)); - image.DebugSave(provider, resamplerName); - image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); + image.DebugSave(provider, resamplerName); + image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); + } } private static IResampler GetResampler(string name) diff --git a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs index 8b0cc02b1f..ad592f9712 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/ProjectiveTransformTests.cs @@ -64,14 +64,16 @@ public void Transform_WithSampler(TestImageProvider provider, st where TPixel : struct, IPixel { IResampler sampler = GetResampler(resamplerName); - using Image image = provider.GetImage(); - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() - .AppendTaper(TaperSide.Right, TaperCorner.Both, .5F); + using (Image image = provider.GetImage()) + { + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + .AppendTaper(TaperSide.Right, TaperCorner.Both, .5F); - image.Mutate(i => i.Transform(builder, sampler)); + image.Mutate(i => i.Transform(builder, sampler)); - image.DebugSave(provider, resamplerName); - image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); + image.DebugSave(provider, resamplerName); + image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName); + } } [Theory] @@ -79,15 +81,17 @@ public void Transform_WithSampler(TestImageProvider provider, st public void Transform_WithTaperMatrix(TestImageProvider provider, TaperSide taperSide, TaperCorner taperCorner) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() - .AppendTaper(taperSide, taperCorner, .5F); + using (Image image = provider.GetImage()) + { + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + .AppendTaper(taperSide, taperCorner, .5F); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - FormattableString testOutputDetails = $"{taperSide}-{taperCorner}"; - image.DebugSave(provider, testOutputDetails); - image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails); + FormattableString testOutputDetails = $"{taperSide}-{taperCorner}"; + image.DebugSave(provider, testOutputDetails); + image.CompareFirstFrameToReferenceOutput(TolerantComparer, provider, testOutputDetails); + } } [Theory] @@ -100,17 +104,19 @@ public void RawTransformMatchesDocumentedExample(TestImageProvider image = provider.GetImage(); - Matrix4x4 matrix = Matrix4x4.Identity; - matrix.M14 = 0.01F; + using (Image image = provider.GetImage()) + { + Matrix4x4 matrix = Matrix4x4.Identity; + matrix.M14 = 0.01F; - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() .AppendMatrix(matrix); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - image.DebugSave(provider); - image.CompareToReferenceOutput(TolerantComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(TolerantComparer, provider); + } } [Theory] @@ -120,22 +126,24 @@ public void PerspectiveTransformMatchesCSS(TestImageProvider pro { // https://jsfiddle.net/dFrHS/545/ // https://github.com/SixLabors/ImageSharp/issues/787 - using Image image = provider.GetImage(); + using (Image image = provider.GetImage()) + { #pragma warning disable SA1117 // Parameters should be on same line or separate lines - var matrix = new Matrix4x4( - 0.260987f, -0.434909f, 0, -0.0022184f, - 0.373196f, 0.949882f, 0, -0.000312129f, - 0, 0, 1, 0, - 52, 165, 0, 1); + var matrix = new Matrix4x4( + 0.260987f, -0.434909f, 0, -0.0022184f, + 0.373196f, 0.949882f, 0, -0.000312129f, + 0, 0, 1, 0, + 52, 165, 0, 1); #pragma warning restore SA1117 // Parameters should be on same line or separate lines - ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() + ProjectiveTransformBuilder builder = new ProjectiveTransformBuilder() .AppendMatrix(matrix); - image.Mutate(i => i.Transform(builder)); + image.Mutate(i => i.Transform(builder)); - image.DebugSave(provider); - image.CompareToReferenceOutput(TolerantComparer, provider); + image.DebugSave(provider); + image.CompareToReferenceOutput(TolerantComparer, provider); + } } private static IResampler GetResampler(string name) diff --git a/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs b/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs index d964a7d15e..9f8034fa37 100644 --- a/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs +++ b/tests/ImageSharp.Tests/Processing/Transforms/TransformsHelpersTest.cs @@ -15,19 +15,21 @@ public void HelperCanChangeExifDataType() { int xy = 1; - using var img = new Image(xy, xy); - var profile = new ExifProfile(); - img.Metadata.ExifProfile = profile; - profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue); - profile.SetValue(ExifTag.PixelYDimension, xy + ushort.MaxValue); + using (var img = new Image(xy, xy)) + { + var profile = new ExifProfile(); + img.Metadata.ExifProfile = profile; + profile.SetValue(ExifTag.PixelXDimension, xy + ushort.MaxValue); + profile.SetValue(ExifTag.PixelYDimension, xy + ushort.MaxValue); - Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelXDimension).DataType); - Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelYDimension).DataType); + Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelXDimension).DataType); + Assert.Equal(ExifDataType.Long, profile.GetValue(ExifTag.PixelYDimension).DataType); - TransformProcessorHelpers.UpdateDimensionalMetadata(img); + TransformProcessorHelpers.UpdateDimensionalMetadata(img); - Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelXDimension).DataType); - Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelYDimension).DataType); + Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelXDimension).DataType); + Assert.Equal(ExifDataType.Short, profile.GetValue(ExifTag.PixelYDimension).DataType); + } } } } diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs index df61d06ade..858607a02f 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/LoadResizeSaveProfilingBenchmarks.cs @@ -26,19 +26,21 @@ public void LoadResizeSave(string imagePath) byte[] imageBytes = TestFile.Create(imagePath).Bytes; - using var ms = new MemoryStream(); - this.Measure( - 30, - () => - { - using (var image = Image.Load(configuration, imageBytes)) - { - image.Mutate(x => x.Resize(image.Size() / 4)); - image.SaveAsJpeg(ms); - } - - ms.Seek(0, SeekOrigin.Begin); - }); + using (var ms = new MemoryStream()) + { + this.Measure( + 30, + () => + { + using (var image = Image.Load(configuration, imageBytes)) + { + image.Mutate(x => x.Resize(image.Size() / 4)); + image.SaveAsJpeg(ms); + } + + ms.Seek(0, SeekOrigin.Begin); + }); + } } } } diff --git a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs index c38e3234cf..ba5eb532b2 100644 --- a/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs +++ b/tests/ImageSharp.Tests/ProfilingBenchmarks/ResizeProfilingBenchmarks.cs @@ -29,10 +29,12 @@ public void ResizeBicubic(int width, int height) this.Measure( this.ExecutionCount, () => - { - using var image = new Image(this.configuration, width, height); - image.Mutate(x => x.Resize(width / 5, height / 5)); - }); + { + using (var image = new Image(this.configuration, width, height)) + { + image.Mutate(x => x.Resize(width / 5, height / 5)); + } + }); } } } diff --git a/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs b/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs index ddf2a5752d..7750017095 100644 --- a/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs +++ b/tests/ImageSharp.Tests/Quantization/QuantizedImageTests.cs @@ -41,18 +41,20 @@ public void OctreeQuantizerYieldsCorrectTransparentPixel( bool dither) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - Assert.True(image[0, 0].Equals(default(TPixel))); + using (Image image = provider.GetImage()) + { + Assert.True(image[0, 0].Equals(default(TPixel))); - var quantizer = new OctreeQuantizer(dither); + var quantizer = new OctreeQuantizer(dither); - foreach (ImageFrame frame in image.Frames) - { - IQuantizedFrame quantized = - quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); + foreach (ImageFrame frame in image.Frames) + { + IQuantizedFrame quantized = + quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); - int index = this.GetTransparentIndex(quantized); - Assert.Equal(index, quantized.GetPixelSpan()[0]); + int index = this.GetTransparentIndex(quantized); + Assert.Equal(index, quantized.GetPixelSpan()[0]); + } } } @@ -62,18 +64,20 @@ public void OctreeQuantizerYieldsCorrectTransparentPixel( public void WuQuantizerYieldsCorrectTransparentPixel(TestImageProvider provider, bool dither) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - Assert.True(image[0, 0].Equals(default(TPixel))); + using (Image image = provider.GetImage()) + { + Assert.True(image[0, 0].Equals(default(TPixel))); - var quantizer = new WuQuantizer(dither); + var quantizer = new WuQuantizer(dither); - foreach (ImageFrame frame in image.Frames) - { - IQuantizedFrame quantized = - quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); + foreach (ImageFrame frame in image.Frames) + { + IQuantizedFrame quantized = + quantizer.CreateFrameQuantizer(this.Configuration).QuantizeFrame(frame); - int index = this.GetTransparentIndex(quantized); - Assert.Equal(index, quantized.GetPixelSpan()[0]); + int index = this.GetTransparentIndex(quantized); + Assert.Equal(index, quantized.GetPixelSpan()[0]); + } } } diff --git a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs index 32c5586b57..1b0253147a 100644 --- a/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs +++ b/tests/ImageSharp.Tests/Quantization/WuQuantizerTests.cs @@ -17,13 +17,15 @@ public void SinglePixelOpaque() Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); - using var image = new Image(config, 1, 1, Rgba32.Black); - using IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0]); - Assert.Equal(1, result.Palette.Length); - Assert.Equal(1, result.GetPixelSpan().Length); + using (var image = new Image(config, 1, 1, Rgba32.Black)) + using (IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0])) + { + Assert.Equal(1, result.Palette.Length); + Assert.Equal(1, result.GetPixelSpan().Length); - Assert.Equal(Rgba32.Black, result.Palette.Span[0]); - Assert.Equal(0, result.GetPixelSpan()[0]); + Assert.Equal(Rgba32.Black, result.Palette.Span[0]); + Assert.Equal(0, result.GetPixelSpan()[0]); + } } [Fact] @@ -32,13 +34,15 @@ public void SinglePixelTransparent() Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); - using var image = new Image(config, 1, 1, default(Rgba32)); - using IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0]); - Assert.Equal(1, result.Palette.Length); - Assert.Equal(1, result.GetPixelSpan().Length); + using (var image = new Image(config, 1, 1, default(Rgba32))) + using (IQuantizedFrame result = quantizer.CreateFrameQuantizer(config).QuantizeFrame(image.Frames[0])) + { + Assert.Equal(1, result.Palette.Length); + Assert.Equal(1, result.GetPixelSpan().Length); - Assert.Equal(default, result.Palette.Span[0]); - Assert.Equal(0, result.GetPixelSpan()[0]); + Assert.Equal(default, result.Palette.Span[0]); + Assert.Equal(0, result.GetPixelSpan()[0]); + } } [Fact] @@ -59,42 +63,46 @@ public void SinglePixelTransparent() [Fact] public void Palette256() { - using var image = new Image(1, 256); - for (int i = 0; i < 256; i++) + using (var image = new Image(1, 256)) { - byte r = (byte)((i % 4) * 85); - byte g = (byte)(((i / 4) % 4) * 85); - byte b = (byte)(((i / 16) % 4) * 85); - byte a = (byte)((i / 64) * 85); - - image[0, i] = new Rgba32(r, g, b, a); - } - - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); - using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); - using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); - Assert.Equal(256, result.Palette.Length); - Assert.Equal(256, result.GetPixelSpan().Length); - - var actualImage = new Image(1, 256); + for (int i = 0; i < 256; i++) + { + byte r = (byte)((i % 4) * 85); + byte g = (byte)(((i / 4) % 4) * 85); + byte b = (byte)(((i / 16) % 4) * 85); + byte a = (byte)((i / 64) * 85); - ReadOnlySpan paletteSpan = result.Palette.Span; - int paletteCount = result.Palette.Length - 1; - for (int y = 0; y < actualImage.Height; y++) - { - Span row = actualImage.GetPixelRowSpan(y); - ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); - int yy = y * actualImage.Width; + image[0, i] = new Rgba32(r, g, b, a); + } - for (int x = 0; x < actualImage.Width; x++) + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); + using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) + using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) { - int i = x + yy; - row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; + Assert.Equal(256, result.Palette.Length); + Assert.Equal(256, result.GetPixelSpan().Length); + + var actualImage = new Image(1, 256); + + ReadOnlySpan paletteSpan = result.Palette.Span; + int paletteCount = result.Palette.Length - 1; + for (int y = 0; y < actualImage.Height; y++) + { + Span row = actualImage.GetPixelRowSpan(y); + ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); + int yy = y * actualImage.Width; + + for (int x = 0; x < actualImage.Width; x++) + { + int i = x + yy; + row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; + } + } + + Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); } } - - Assert.True(image.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); } [Theory] @@ -103,55 +111,63 @@ public void LowVariance(TestImageProvider provider) where TPixel : struct, IPixel { // See https://github.com/SixLabors/ImageSharp/issues/866 - using Image image = provider.GetImage(); - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); - using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); - using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); - Assert.Equal(48, result.Palette.Length); + using (Image image = provider.GetImage()) + { + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); + using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) + using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) + { + Assert.Equal(48, result.Palette.Length); + } + } } private static void TestScale(Func pixelBuilder) { - using var image = new Image(1, 256); - using var expectedImage = new Image(1, 256); - using var actualImage = new Image(1, 256); - for (int i = 0; i < 256; i++) + using (var image = new Image(1, 256)) + using (var expectedImage = new Image(1, 256)) + using (var actualImage = new Image(1, 256)) { - byte c = (byte)i; - image[0, i] = pixelBuilder.Invoke(c); - } - - for (int i = 0; i < 256; i++) - { - byte c = (byte)((i & ~7) + 4); - expectedImage[0, i] = pixelBuilder.Invoke(c); - } - - Configuration config = Configuration.Default; - var quantizer = new WuQuantizer(false); + for (int i = 0; i < 256; i++) + { + byte c = (byte)i; + image[0, i] = pixelBuilder.Invoke(c); + } - using IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config); - using IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0]); - Assert.Equal(4 * 8, result.Palette.Length); - Assert.Equal(256, result.GetPixelSpan().Length); + for (int i = 0; i < 256; i++) + { + byte c = (byte)((i & ~7) + 4); + expectedImage[0, i] = pixelBuilder.Invoke(c); + } - ReadOnlySpan paletteSpan = result.Palette.Span; - int paletteCount = result.Palette.Length - 1; - for (int y = 0; y < actualImage.Height; y++) - { - Span row = actualImage.GetPixelRowSpan(y); - ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); - int yy = y * actualImage.Width; + Configuration config = Configuration.Default; + var quantizer = new WuQuantizer(false); - for (int x = 0; x < actualImage.Width; x++) + using (IFrameQuantizer frameQuantizer = quantizer.CreateFrameQuantizer(config)) + using (IQuantizedFrame result = frameQuantizer.QuantizeFrame(image.Frames[0])) { - int i = x + yy; - row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; + Assert.Equal(4 * 8, result.Palette.Length); + Assert.Equal(256, result.GetPixelSpan().Length); + + ReadOnlySpan paletteSpan = result.Palette.Span; + int paletteCount = result.Palette.Length - 1; + for (int y = 0; y < actualImage.Height; y++) + { + Span row = actualImage.GetPixelRowSpan(y); + ReadOnlySpan quantizedPixelSpan = result.GetPixelSpan(); + int yy = y * actualImage.Width; + + for (int x = 0; x < actualImage.Width; x++) + { + int i = x + yy; + row[x] = paletteSpan[Math.Min(paletteCount, quantizedPixelSpan[i])]; + } + } } - } - Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); + Assert.True(expectedImage.GetPixelSpan().SequenceEqual(actualImage.GetPixelSpan())); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs index afd66e8ce4..cce0c87126 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ImagingTestCaseUtility.cs @@ -223,10 +223,14 @@ public string[] SaveTestOutputFileMultiFrame( for (int i = 0; i < image.Frames.Count; i++) { - using Image frameImage = image.Frames.CloneFrame(i); - string filePath = files[i]; - using FileStream stream = File.OpenWrite(filePath); - frameImage.Save(stream, encoder); + using (Image frameImage = image.Frames.CloneFrame(i)) + { + string filePath = files[i]; + using (FileStream stream = File.OpenWrite(filePath)) + { + frameImage.Save(stream, encoder); + } + } } return files; diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs index 413717d362..58afd48a7e 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/MagickReferenceDecoder.cs @@ -20,38 +20,42 @@ public class MagickReferenceDecoder : IImageDecoder public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - using var magickImage = new MagickImage(stream); - var result = new Image(configuration, magickImage.Width, magickImage.Height); - Span resultPixels = result.GetPixelSpan(); - - using IPixelCollection pixels = magickImage.GetPixelsUnsafe(); - if (magickImage.Depth == 8) - { - byte[] data = pixels.ToByteArray(PixelMapping.RGBA); - - PixelOperations.Instance.FromRgba32Bytes( - configuration, - data, - resultPixels, - resultPixels.Length); - } - else if (magickImage.Depth == 16) + using (var magickImage = new MagickImage(stream)) { - ushort[] data = pixels.ToShortArray(PixelMapping.RGBA); - Span bytes = MemoryMarshal.Cast(data.AsSpan()); - - PixelOperations.Instance.FromRgba64Bytes( - configuration, - bytes, - resultPixels, - resultPixels.Length); + var result = new Image(configuration, magickImage.Width, magickImage.Height); + Span resultPixels = result.GetPixelSpan(); + + using (IPixelCollection pixels = magickImage.GetPixelsUnsafe()) + { + if (magickImage.Depth == 8) + { + byte[] data = pixels.ToByteArray(PixelMapping.RGBA); + + PixelOperations.Instance.FromRgba32Bytes( + configuration, + data, + resultPixels, + resultPixels.Length); + } + else if (magickImage.Depth == 16) + { + ushort[] data = pixels.ToShortArray(PixelMapping.RGBA); + Span bytes = MemoryMarshal.Cast(data.AsSpan()); + + PixelOperations.Instance.FromRgba64Bytes( + configuration, + bytes, + resultPixels, + resultPixels.Length); + } + else + { + throw new InvalidOperationException(); + } + } + + return result; } - else - { - throw new InvalidOperationException(); - } - - return result; } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs index baeb785222..590233420c 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingBridge.cs @@ -49,20 +49,22 @@ internal static unsafe Image From32bppArgbSystemDrawingBitmap(Bi Configuration configuration = image.GetConfiguration(); - using IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w); - fixed (Bgra32* destPtr = &workBuffer.GetReference()) + using (IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w)) { - for (int y = 0; y < h; y++) + fixed (Bgra32* destPtr = &workBuffer.GetReference()) { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - - byte* sourcePtr = sourcePtrBase + (data.Stride * y); - - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); - PixelOperations.Instance.FromBgra32( - configuration, - workBuffer.GetSpan().Slice(0, w), - row); + for (int y = 0; y < h; y++) + { + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + + byte* sourcePtr = sourcePtrBase + (data.Stride * y); + + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + PixelOperations.Instance.FromBgra32( + configuration, + workBuffer.GetSpan().Slice(0, w), + row); + } } } } @@ -106,17 +108,19 @@ internal static unsafe Image From24bppRgbSystemDrawingBitmap(Bit Configuration configuration = image.GetConfiguration(); - using IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w); - fixed (Bgr24* destPtr = &workBuffer.GetReference()) + using (IMemoryOwner workBuffer = Configuration.Default.MemoryAllocator.Allocate(w)) { - for (int y = 0; y < h; y++) + fixed (Bgr24* destPtr = &workBuffer.GetReference()) { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + for (int y = 0; y < h; y++) + { + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - byte* sourcePtr = sourcePtrBase + (data.Stride * y); + byte* sourcePtr = sourcePtrBase + (data.Stride * y); - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); - PixelOperations.Instance.FromBgr24(configuration, workBuffer.GetSpan().Slice(0, w), row); + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + PixelOperations.Instance.FromBgr24(configuration, workBuffer.GetSpan().Slice(0, w), row); + } } } } @@ -145,16 +149,18 @@ internal static unsafe Bitmap To32bppArgbSystemDrawingBitmap(Image workBuffer = image.GetConfiguration().MemoryAllocator.Allocate(w); - fixed (Bgra32* sourcePtr = &workBuffer.GetReference()) + using (IMemoryOwner workBuffer = image.GetConfiguration().MemoryAllocator.Allocate(w)) { - for (int y = 0; y < h; y++) + fixed (Bgra32* sourcePtr = &workBuffer.GetReference()) { - Span row = image.Frames.RootFrame.GetPixelRowSpan(y); - PixelOperations.Instance.ToBgra32(configuration, row, workBuffer.GetSpan()); - byte* destPtr = destPtrBase + (data.Stride * y); - - Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + for (int y = 0; y < h; y++) + { + Span row = image.Frames.RootFrame.GetPixelRowSpan(y); + PixelOperations.Instance.ToBgra32(configuration, row, workBuffer.GetSpan()); + byte* destPtr = destPtrBase + (data.Stride * y); + + Buffer.MemoryCopy(sourcePtr, destPtr, destRowByteCount, sourceRowByteCount); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs index dcd1c2bbbf..286ab9caee 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs +++ b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceDecoder.cs @@ -16,32 +16,40 @@ public class SystemDrawingReferenceDecoder : IImageDecoder, IImageInfoDetector public Image Decode(Configuration configuration, Stream stream) where TPixel : struct, IPixel { - using var sourceBitmap = new System.Drawing.Bitmap(stream); - if (sourceBitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) + using (var sourceBitmap = new System.Drawing.Bitmap(stream)) { - return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sourceBitmap); + if (sourceBitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) + { + return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sourceBitmap); + } + + using (var convertedBitmap = new System.Drawing.Bitmap( + sourceBitmap.Width, + sourceBitmap.Height, + System.Drawing.Imaging.PixelFormat.Format32bppArgb)) + { + using (var g = System.Drawing.Graphics.FromImage(convertedBitmap)) + { + g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + + g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height); + } + + return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(convertedBitmap); + } } - - using var convertedBitmap = new System.Drawing.Bitmap( - sourceBitmap.Width, - sourceBitmap.Height, - System.Drawing.Imaging.PixelFormat.Format32bppArgb); - using var g = System.Drawing.Graphics.FromImage(convertedBitmap); - g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; - - g.DrawImage(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height); - - return SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(convertedBitmap); } public IImageInfo Identify(Configuration configuration, Stream stream) { - using var sourceBitmap = new System.Drawing.Bitmap(stream); - var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat)); - return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata()); + using (var sourceBitmap = new System.Drawing.Bitmap(stream)) + { + var pixelType = new PixelTypeInfo(System.Drawing.Image.GetPixelFormatSize(sourceBitmap.PixelFormat)); + return new ImageInfo(pixelType, sourceBitmap.Width, sourceBitmap.Height, new ImageMetadata()); + } } public Image Decode(Configuration configuration, Stream stream) => this.Decode(configuration, stream); diff --git a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs b/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs index bfad7414ea..46dae17a11 100644 --- a/tests/ImageSharp.Tests/TestUtilities/ReferenceCodecs/SystemDrawingReferenceEncoder.cs +++ b/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. using System.Drawing.Imaging; @@ -25,8 +25,10 @@ public SystemDrawingReferenceEncoder(ImageFormat imageFormat) public void Encode(Image image, Stream stream) where TPixel : struct, IPixel { - using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image); - sdBitmap.Save(stream, this.imageFormat); + using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image)) + { + sdBitmap.Save(stream, this.imageFormat); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs index d8a611ca84..70d39024e4 100644 --- a/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs +++ b/tests/ImageSharp.Tests/TestUtilities/TestImageExtensions.cs @@ -286,17 +286,19 @@ public static Image CompareFirstFrameToReferenceOutput( bool appendSourceFileOrDescription = true) where TPixel : struct, IPixel { - using var firstFrameOnlyImage = new Image(image.Width, image.Height); - using Image referenceImage = GetReferenceOutputImage( + using (var firstFrameOnlyImage = new Image(image.Width, image.Height)) + using (Image referenceImage = GetReferenceOutputImage( provider, testOutputDetails, extension, appendPixelTypeToFileName, - appendSourceFileOrDescription); - firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame); - firstFrameOnlyImage.Frames.RemoveFrame(0); + appendSourceFileOrDescription)) + { + firstFrameOnlyImage.Frames.AddFrame(image.Frames.RootFrame); + firstFrameOnlyImage.Frames.RemoveFrame(0); - comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage); + comparer.VerifySimilarity(referenceImage, firstFrameOnlyImage); + } return image; } @@ -402,11 +404,13 @@ public static IEnumerable GetReferenceOutputSimilarityRep bool appendPixelTypeToFileName = true) where TPixel : struct, IPixel { - using Image referenceImage = provider.GetReferenceOutputImage( + using (Image referenceImage = provider.GetReferenceOutputImage( testOutputDetails, extension, - appendPixelTypeToFileName); - return comparer.CompareImages(referenceImage, image); + appendPixelTypeToFileName)) + { + return comparer.CompareImages(referenceImage, image); + } } public static Image ComparePixelBufferTo( @@ -551,21 +555,23 @@ internal static void VerifyOperation( bool appendSourceFileOrDescription = true) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - operation(image); - - image.DebugSave( - provider, - testOutputDetails, - appendPixelTypeToFileName: appendPixelTypeToFileName, - appendSourceFileOrDescription: appendSourceFileOrDescription); - - image.CompareToReferenceOutput( - comparer, - provider, - testOutputDetails, - appendPixelTypeToFileName: appendPixelTypeToFileName, - appendSourceFileOrDescription: appendSourceFileOrDescription); + using (Image image = provider.GetImage()) + { + operation(image); + + image.DebugSave( + provider, + testOutputDetails, + appendPixelTypeToFileName: appendPixelTypeToFileName, + appendSourceFileOrDescription: appendSourceFileOrDescription); + + image.CompareToReferenceOutput( + comparer, + provider, + testOutputDetails, + appendPixelTypeToFileName: appendPixelTypeToFileName, + appendSourceFileOrDescription: appendSourceFileOrDescription); + } } /// @@ -653,9 +659,11 @@ internal static void VerifyEncoder( referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile); - using var actualImage = Image.Load(actualOutputFile, referenceDecoder); - ImageComparer comparer = customComparer ?? ImageComparer.Exact; - comparer.VerifySimilarity(actualImage, image); + using (var actualImage = Image.Load(actualOutputFile, referenceDecoder)) + { + ImageComparer comparer = customComparer ?? ImageComparer.Exact; + comparer.VerifySimilarity(actualImage, image); + } } internal static Image ToGrayscaleImage(this Buffer2D buffer, float scale) diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs index de7b5f84a5..24c4d1b476 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/ImageComparerTests.cs @@ -33,10 +33,14 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( int pixelThreshold) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold); - comparer.VerifySimilarity(image, clone); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + var comparer = ImageComparer.Tolerant(imageThreshold, pixelThreshold); + comparer.VerifySimilarity(image, clone); + } + } } [Theory] @@ -44,12 +48,16 @@ public void TolerantImageComparer_ApprovesPerfectSimilarity( public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); - var comparer = ImageComparer.Tolerant(); - comparer.VerifySimilarity(image, clone); + var comparer = ImageComparer.Tolerant(); + comparer.VerifySimilarity(image, clone); + } + } } [Theory] @@ -57,18 +65,22 @@ public void TolerantImageComparer_ApprovesSimilarityBelowTolerance(TestI public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - byte perChannelChange = 20; - ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + byte perChannelChange = 20; + ImagingTestCaseUtility.ModifyPixel(clone, 3, 1, perChannelChange); - var comparer = ImageComparer.Tolerant(); + var comparer = ImageComparer.Tolerant(); - ImageDifferenceIsOverThresholdException ex = Assert.ThrowsAny( - () => comparer.VerifySimilarity(image, clone)); + ImageDifferenceIsOverThresholdException ex = Assert.ThrowsAny( + () => comparer.VerifySimilarity(image, clone)); - PixelDifference diff = ex.Reports.Single().Differences.Single(); - Assert.Equal(new Point(3, 1), diff.Position); + PixelDifference diff = ex.Reports.Single().Differences.Single(); + Assert.Equal(new Point(3, 1), diff.Position); + } + } } [Theory] @@ -76,14 +88,18 @@ public void TolerantImageComparer_DoesNotApproveSimilarityAboveTolerance public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); - ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1); - ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1); - - var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3); - comparer.VerifySimilarity(image, clone); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + ImagingTestCaseUtility.ModifyPixel(clone, 0, 0, 1); + ImagingTestCaseUtility.ModifyPixel(clone, 1, 0, 1); + ImagingTestCaseUtility.ModifyPixel(clone, 2, 0, 1); + + var comparer = ImageComparer.Tolerant(perPixelManhattanThreshold: 257 * 3); + comparer.VerifySimilarity(image, clone); + } + } } [Theory] @@ -92,15 +108,19 @@ public void TolerantImageComparer_TestPerPixelThreshold(TestImageProvide public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider provider, int w, int h) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(ctx => ctx.Resize(w, h)); - ImageDimensionsMismatchException ex = Assert.ThrowsAny( - () => + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone(ctx => ctx.Resize(w, h))) { - ImageComparer comparer = Mock.Of(); - comparer.VerifySimilarity(image, clone); - }); - this.Output.WriteLine(ex.Message); + ImageDimensionsMismatchException ex = Assert.ThrowsAny( + () => + { + ImageComparer comparer = Mock.Of(); + comparer.VerifySimilarity(image, clone); + }); + this.Output.WriteLine(ex.Message); + } + } } [Theory] @@ -108,14 +128,18 @@ public void VerifySimilarity_ThrowsOnSizeMismatch(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + ImagingTestCaseUtility.ModifyPixel(clone.Frames[0], 42, 43, 1); - IEnumerable reports = ImageComparer.Exact.CompareImages(image, clone); + IEnumerable reports = ImageComparer.Exact.CompareImages(image, clone); - PixelDifference difference = reports.Single().Differences.Single(); - Assert.Equal(new Point(42, 43), difference.Position); + PixelDifference difference = reports.Single().Differences.Single(); + Assert.Equal(new Point(42, 43), difference.Position); + } + } } [Theory] diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs index 4d7981fb03..e9843b2b72 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/MagickReferenceCodecTests.cs @@ -39,15 +39,17 @@ public void MagickDecode_8BitDepthImage_IsEquivalentTo_SystemDrawingResult(path, magickDecoder); - using var sdImage = Image.Load(path, sdDecoder); - ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); + using (var mImage = Image.Load(path, magickDecoder)) + using (var sdImage = Image.Load(path, sdDecoder)) + { + ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); - mImage.DebugSave(dummyProvider); + mImage.DebugSave(dummyProvider); - if (TestEnvironment.IsWindows) - { - Assert.True(report.IsEmpty); + if (TestEnvironment.IsWindows) + { + Assert.True(report.IsEmpty); + } } } @@ -68,15 +70,17 @@ public void MagickDecode_16BitDepthImage_IsApproximatelyEquivalentTo_SystemDrawi // 1020 == 4 * 255 (Equivalent to manhattan distance of 1+1+1+1=4 in Rgba32 space) var comparer = ImageComparer.TolerantPercentage(1, 1020); - using var mImage = Image.Load(path, magickDecoder); - using var sdImage = Image.Load(path, sdDecoder); - ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); + using (var mImage = Image.Load(path, magickDecoder)) + using (var sdImage = Image.Load(path, sdDecoder)) + { + ImageSimilarityReport report = comparer.CompareImagesOrFrames(mImage, sdImage); - mImage.DebugSave(dummyProvider); + mImage.DebugSave(dummyProvider); - if (TestEnvironment.IsWindows) - { - Assert.True(report.IsEmpty); + if (TestEnvironment.IsWindows) + { + Assert.True(report.IsEmpty); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs index 98f02f6ebd..4a02d280e5 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/SystemDrawingReferenceCodecTests.cs @@ -26,10 +26,14 @@ public SystemDrawingReferenceCodecTests(ITestOutputHelper output) public void To32bppArgbSystemDrawingBitmap(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image); - string fileName = provider.Utility.GetTestOutputFileName("png"); - sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); + using (Image image = provider.GetImage()) + { + using (System.Drawing.Bitmap sdBitmap = SystemDrawingBridge.To32bppArgbSystemDrawingBitmap(image)) + { + string fileName = provider.Utility.GetTestOutputFileName("png"); + sdBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); + } + } } [Theory] @@ -39,22 +43,28 @@ public void From32bppArgbSystemDrawingBitmap(TestImageProvider d { string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); - using var sdBitmap = new System.Drawing.Bitmap(path); - using Image image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap); - image.DebugSave(dummyProvider); + using (var sdBitmap = new System.Drawing.Bitmap(path)) + { + using (Image image = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap)) + { + image.DebugSave(dummyProvider); + } + } } private static string SavePng(TestImageProvider provider, PngColorType pngColorType) where TPixel : struct, IPixel { - using Image sourceImage = provider.GetImage(); - if (pngColorType != PngColorType.RgbWithAlpha) + using (Image sourceImage = provider.GetImage()) { - sourceImage.Mutate(c => c.MakeOpaque()); - } + if (pngColorType != PngColorType.RgbWithAlpha) + { + sourceImage.Mutate(c => c.MakeOpaque()); + } - var encoder = new PngEncoder { ColorType = pngColorType }; - return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder); + var encoder = new PngEncoder { ColorType = pngColorType }; + return provider.Utility.SaveTestOutputFile(sourceImage, "png", encoder); + } } [Theory] @@ -69,11 +79,15 @@ public void From32bppArgbSystemDrawingBitmap2(TestImageProvider string path = SavePng(provider, PngColorType.RgbWithAlpha); - using var sdBitmap = new System.Drawing.Bitmap(path); - using Image original = provider.GetImage(); - using Image resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap); - ImageComparer comparer = ImageComparer.Exact; - comparer.VerifySimilarity(original, resaved); + using (var sdBitmap = new System.Drawing.Bitmap(path)) + { + using (Image original = provider.GetImage()) + using (Image resaved = SystemDrawingBridge.From32bppArgbSystemDrawingBitmap(sdBitmap)) + { + ImageComparer comparer = ImageComparer.Exact; + comparer.VerifySimilarity(original, resaved); + } + } } [Theory] @@ -83,11 +97,17 @@ public void From24bppRgbSystemDrawingBitmap(TestImageProvider pr { string path = SavePng(provider, PngColorType.Rgb); - using Image original = provider.GetImage(); - using var sdBitmap = new System.Drawing.Bitmap(path); - using Image resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap(sdBitmap); - ImageComparer comparer = ImageComparer.Exact; - comparer.VerifySimilarity(original, resaved); + using (Image original = provider.GetImage()) + { + using (var sdBitmap = new System.Drawing.Bitmap(path)) + { + using (Image resaved = SystemDrawingBridge.From24bppRgbSystemDrawingBitmap(sdBitmap)) + { + ImageComparer comparer = ImageComparer.Exact; + comparer.VerifySimilarity(original, resaved); + } + } + } } [Theory] @@ -96,8 +116,10 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv where TPixel : struct, IPixel { string path = TestFile.GetInputFileFullPath(TestImages.Png.Splash); - using var image = Image.Load(path, SystemDrawingReferenceDecoder.Instance); - image.DebugSave(dummyProvider); + using (var image = Image.Load(path, SystemDrawingReferenceDecoder.Instance)) + { + image.DebugSave(dummyProvider); + } } [Theory] @@ -105,8 +127,10 @@ public void OpenWithReferenceDecoder(TestImageProvider dummyProv public void SaveWithReferenceEncoder(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png); + using (Image image = provider.GetImage()) + { + provider.Utility.SaveTestOutputFile(image, "png", SystemDrawingReferenceEncoder.Png); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs index e4043b4b5d..adb51e723f 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageExtensionsTests.cs @@ -20,8 +20,10 @@ public void CompareToReferenceOutput_WhenReferenceOutputMatches_ShouldNotThrow provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.CompareToReferenceOutput(provider); + using (Image image = provider.GetImage()) + { + image.CompareToReferenceOutput(provider); + } } [Theory] @@ -30,8 +32,10 @@ public void CompareToReferenceOutput_WhenReferenceOutputDoesNotMatch_Throws provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); + using (Image image = provider.GetImage()) + { + Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); + } } [Theory] @@ -40,9 +44,11 @@ public void CompareToReferenceOutput_DoNotAppendPixelType( TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - image.DebugSave(provider, appendPixelTypeToFileName: false); - image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false); + using (Image image = provider.GetImage()) + { + image.DebugSave(provider, appendPixelTypeToFileName: false); + image.CompareToReferenceOutput(provider, appendPixelTypeToFileName: false); + } } [Theory] @@ -50,8 +56,10 @@ public void CompareToReferenceOutput_DoNotAppendPixelType( public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); + using (Image image = provider.GetImage()) + { + Assert.ThrowsAny(() => image.CompareToReferenceOutput(provider)); + } } [Theory] @@ -59,9 +67,13 @@ public void CompareToReferenceOutput_WhenReferenceFileMissing_Throws(Tes public void CompareToOriginal_WhenSimilar(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - using Image clone = image.Clone(); - clone.CompareToOriginal(provider, ImageComparer.Exact); + using (Image image = provider.GetImage()) + { + using (Image clone = image.Clone()) + { + clone.CompareToOriginal(provider, ImageComparer.Exact); + } + } } [Theory] @@ -69,13 +81,15 @@ public void CompareToOriginal_WhenSimilar(TestImageProvider prov public void CompareToOriginal_WhenDifferent_Throws(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1); - - Assert.ThrowsAny(() => + using (Image image = provider.GetImage()) { - image.CompareToOriginal(provider, ImageComparer.Exact); - }); + ImagingTestCaseUtility.ModifyPixel(image, 3, 1, 1); + + Assert.ThrowsAny(() => + { + image.CompareToOriginal(provider, ImageComparer.Exact); + }); + } } [Theory] @@ -83,11 +97,13 @@ public void CompareToOriginal_WhenDifferent_Throws(TestImageProvider(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - Assert.ThrowsAny(() => + using (Image image = provider.GetImage()) { - image.CompareToOriginal(provider, Mock.Of()); - }); + Assert.ThrowsAny(() => + { + image.CompareToOriginal(provider, Mock.Of()); + }); + } } } } diff --git a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs index a33b0750b1..bcd5e844a8 100644 --- a/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs +++ b/tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs @@ -179,14 +179,16 @@ public void PixelType_PropertyValueIsCorrect(TestImageProvider p public void SaveTestOutputFileMultiFrame(TestImageProvider provider) where TPixel : struct, IPixel { - using Image image = provider.GetImage(); - string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image); - - Assert.True(files.Length > 2); - foreach (string path in files) + using (Image image = provider.GetImage()) { - this.Output.WriteLine(path); - Assert.True(File.Exists(path)); + string[] files = provider.Utility.SaveTestOutputFileMultiFrame(image); + + Assert.True(files.Length > 2); + foreach (string path in files) + { + this.Output.WriteLine(path); + Assert.True(File.Exists(path)); + } } } @@ -197,8 +199,10 @@ public void SaveTestOutputFileMultiFrame(TestImageProvider provi public void Use_WithBasicTestPatternImages(TestImageProvider provider) where TPixel : struct, IPixel { - using Image img = provider.GetImage(); - img.DebugSave(provider); + using (Image img = provider.GetImage()) + { + img.DebugSave(provider); + } } [Theory] @@ -234,13 +238,15 @@ public void Use_WithFileAttribute(TestImageProvider provider, in where TPixel : struct, IPixel { Assert.NotNull(provider.Utility.SourceFileOrDescription); - using Image img = provider.GetImage(); - Assert.True(img.Width * img.Height > 0); + using (Image img = provider.GetImage()) + { + Assert.True(img.Width * img.Height > 0); - Assert.Equal(123, yo); + Assert.Equal(123, yo); - string fn = provider.Utility.GetTestOutputFileName("jpg"); - this.Output.WriteLine(fn); + string fn = provider.Utility.GetTestOutputFileName("jpg"); + this.Output.WriteLine(fn); + } } [Theory] @@ -257,8 +263,10 @@ public void Use_WithFileCollection(TestImageProvider provider) where TPixel : struct, IPixel { Assert.NotNull(provider.Utility.SourceFileOrDescription); - using Image image = provider.GetImage(); - provider.Utility.SaveTestOutputFile(image, "png"); + using (Image image = provider.GetImage()) + { + provider.Utility.SaveTestOutputFile(image, "png"); + } } [Theory] @@ -326,10 +334,12 @@ private static void EnsureCustomConfigurationIsApplied(TestImageProvider var customConfiguration = Configuration.CreateDefaultInstance(); provider.Configuration = customConfiguration; - using Image image2 = provider.GetImage(); - using Image image3 = provider.GetImage(); - Assert.Same(customConfiguration, image2.GetConfiguration()); - Assert.Same(customConfiguration, image3.GetConfiguration()); + using (Image image2 = provider.GetImage()) + using (Image image3 = provider.GetImage()) + { + Assert.Same(customConfiguration, image2.GetConfiguration()); + Assert.Same(customConfiguration, image3.GetConfiguration()); + } } } From 1f3311bc22ea1619771d66e654539ab312f32913 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Sun, 2 Feb 2020 14:32:10 +1100 Subject: [PATCH 15/15] Add more rule exemptions and prevent blanket using recommendations --- .editorconfig | 7 +++++-- .gitattributes | 4 ++-- shared-infrastructure | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.editorconfig b/.editorconfig index b0d0662bf8..06e6982472 100644 --- a/.editorconfig +++ b/.editorconfig @@ -339,6 +339,7 @@ csharp_space_between_square_brackets = false # warn when using var for built-in types, # warn when using var when the type is not apparent, and # warn when not using var when the type is apparent +# warn when using simplified "using" declaration ############################################################################### [*.cs] csharp_prefer_braces = true:silent @@ -367,6 +368,8 @@ csharp_style_throw_expression = true:suggestion csharp_style_unused_value_expression_statement_preference = discard_variable:silent csharp_style_unused_value_assignment_preference = discard_variable:suggestion -csharp_style_var_for_built_in_types = false:warning -csharp_style_var_elsewhere = false:warning +csharp_style_var_for_built_in_types = false:silent csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_elsewhere = false:warning + +csharp_prefer_simple_using_statement = false:silent diff --git a/.gitattributes b/.gitattributes index dd66250813..66aaca3738 100644 --- a/.gitattributes +++ b/.gitattributes @@ -96,22 +96,22 @@ *.gif binary *.jpg binary *.ktx binary +*.otf binary *.pbm binary *.pdf binary *.png binary *.ppt binary *.pptx binary *.pvr binary -*.ttf binary *.snk binary *.tga binary +*.ttc binary *.ttf binary *.woff binary *.woff2 binary *.xls binary *.xlsx binary - ############################################################################### # Set explicit file behavior to: # diff as plain text diff --git a/shared-infrastructure b/shared-infrastructure index 13b1152a9e..a75469fdb9 160000 --- a/shared-infrastructure +++ b/shared-infrastructure @@ -1 +1 @@ -Subproject commit 13b1152a9e93d1b67690e1e9325af248b7c2145d +Subproject commit a75469fdb93fb89b39a5b0b7c01cb7432ceef98f