Example #1
0
        private static void TestPngEncoderCore <TPixel>(
            TestImageProvider <TPixel> provider,
            PngColorType pngColorType,
            PngFilterMethod pngFilterMethod,
            PngBitDepth bitDepth,
            int compressionLevel        = 6,
            int paletteSize             = 255,
            bool appendPngColorType     = false,
            bool appendPngFilterMethod  = false,
            bool appendPixelType        = false,
            bool appendCompressionLevel = false,
            bool appendPaletteSize      = false)
            where TPixel : struct, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage())
            {
                if (!HasAlpha(pngColorType))
                {
                    image.Mutate(c => c.MakeOpaque());
                }

                var encoder = new PngEncoder
                {
                    ColorType        = pngColorType,
                    FilterMethod     = pngFilterMethod,
                    CompressionLevel = compressionLevel,
                    BitDepth         = bitDepth,
                    Quantizer        = new WuQuantizer(paletteSize)
                };

                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 debugInfo            = $"{pngColorTypeInfo}{pngFilterMethodInfo}{compressionLevelInfo}{paletteSizeInfo}";
                //string referenceInfo = $"{pngColorTypeInfo}";

                // Does DebugSave & load reference CompareToReferenceInput():
                string actualOutputFile = ((ITestImageProvider)provider).Utility.SaveTestOutputFile(image, "png", encoder, debugInfo, appendPixelType);

                if (TestEnvironment.IsMono)
                {
                    // There are bugs in mono's System.Drawing implementation, reference decoders are not always reliable!
                    return;
                }

                IImageDecoder referenceDecoder    = TestEnvironment.GetReferenceDecoder(actualOutputFile);
                string        referenceOutputFile = ((ITestImageProvider)provider).Utility.GetReferenceOutputFileName("png", debugInfo, appendPixelType, true);

                bool referenceOutputFileExists = File.Exists(referenceOutputFile);

                using (var actualImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
                {
                    // TODO: Do we still need the reference output files?
                    Image <TPixel> referenceImage = referenceOutputFileExists
                                               ? Image.Load <TPixel>(referenceOutputFile, referenceDecoder)
                                               : image;

                    float paletteToleranceHack = 80f / paletteSize;
                    paletteToleranceHack = paletteToleranceHack * paletteToleranceHack;
                    ImageComparer comparer = pngColorType == PngColorType.Palette
                                                 ? ImageComparer.Tolerant(ToleranceThresholdForPaletteEncoder * paletteToleranceHack)
                                                 : ImageComparer.Exact;
                    try
                    {
                        comparer.VerifySimilarity(referenceImage, actualImage);
                    }
                    finally
                    {
                        if (referenceOutputFileExists)
                        {
                            referenceImage.Dispose();
                        }
                    }
                }
            }
        }
Example #2
0
 public void GifDecoder_DegenerateMemoryRequest_ShouldTranslateTo_ImageFormatException<TPixel>(TestImageProvider<TPixel> provider)
     where TPixel : unmanaged, IPixel<TPixel>
 {
     provider.LimitAllocatorBufferCapacity().InPixelsSqrt(10);
     InvalidImageContentException ex = Assert.Throws<InvalidImageContentException>(() => provider.GetImage(GifDecoder));
     Assert.IsType<InvalidMemoryOperationException>(ex.InnerException);
 }
 public void ThrowsNotSupported <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : unmanaged, IPixel <TPixel> => Assert.Throws <NotSupportedException>(() => provider.GetImage(TiffDecoder));
Example #4
0
 public void ReadApp13_WithEmptyIptc_Works <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : unmanaged, IPixel <TPixel>
 {
     using Image <TPixel> image = provider.GetImage(JpegDecoder);
     Assert.Null(image.Metadata.IptcProfile);
 }
Example #5
0
 public void DecodeBaselineJpeg_CriticalEOF_ShouldThrow_Orig <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel>
 {
     // TODO: We need a public ImageDecoderException class in ImageSharp!
     Assert.ThrowsAny <Exception>(() => provider.GetImage(OrigJpegDecoder));
 }
Example #6
0
 public void LoadingImage_BadHuffman_ShouldNotThrow <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel> => Assert.NotNull(provider.GetImage());
Example #7
0
        public void BlendFillColorOverBackround <TPixel>(
            TestImageProvider <TPixel> provider,
            bool triggerFillRegion,
            string newColorName,
            float alpha,
            PixelColorBlendingMode blenderMode,
            float blendPercentage)
            where TPixel : struct, IPixel <TPixel>
        {
            var vec = TestUtils.GetPixelOfNamedColor <RgbaVector>(newColorName).ToVector4();

            vec.W = alpha;

            TPixel fillColor = default;

            fillColor.FromVector4(vec);

            using (Image <TPixel> image = provider.GetImage())
            {
                TPixel bgColor = image[0, 0];

                var options = new GraphicsOptions(false)
                {
                    ColorBlendingMode = blenderMode, BlendPercentage = blendPercentage
                };

                if (triggerFillRegion)
                {
                    var region = new ShapeRegion(new RectangularPolygon(0, 0, 16, 16));

                    image.Mutate(c => c.Fill(options, new SolidBrush <TPixel>(fillColor), region));
                }
                else
                {
                    image.Mutate(c => c.Fill(options, new SolidBrush <TPixel>(fillColor)));
                }

                var testOutputDetails = new
                {
                    triggerFillRegion = triggerFillRegion,
                    newColorName      = newColorName,
                    alpha             = alpha,
                    blenderMode       = blenderMode,
                    blendPercentage   = blendPercentage
                };

                image.DebugSave(
                    provider,
                    testOutputDetails,
                    appendPixelTypeToFileName: false,
                    appendSourceFileOrDescription: false);

                PixelBlender <TPixel> blender = PixelOperations <TPixel> .Instance.GetPixelBlender(
                    blenderMode,
                    PixelAlphaCompositionMode.SrcOver);

                TPixel expectedPixel = blender.Blend(bgColor, fillColor, blendPercentage);

                image.ComparePixelBufferTo(expectedPixel);
            }
        }
Example #8
0
 public void BmpDecoder_ThrowsNotSupportedException_OnUnsupportedBitmaps <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel>
 {
     Assert.Throws <NotSupportedException>(() => { using (provider.GetImage(new BmpDecoder())) { } });
 }
Example #9
0
 public void LoadingImage_InvalidTagLength_ShouldThrow <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel> => Assert.Throws <ImageFormatException>(() => provider.GetImage());
Example #10
0
 public void BmpDecoder_ThrowsImageFormatException_OnInvalidPaletteSize <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel>
 {
     Assert.Throws <ImageFormatException>(() => { using (provider.GetImage(new BmpDecoder())) { } });
 }
Example #11
0
        public void Encode_PreservesMetadata <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            // Load Tiff image
            using Image <TPixel> image = provider.GetImage(new TiffDecoder()
            {
                IgnoreMetadata = false
            });

            ImageMetadata       inputMetaData  = image.Metadata;
            ImageFrame <TPixel> rootFrameInput = image.Frames.RootFrame;
            TiffFrameMetadata   frameMetaInput = rootFrameInput.Metadata.GetTiffMetadata();

            byte[]      xmpProfileInput  = rootFrameInput.Metadata.XmpProfile;
            ExifProfile exifProfileInput = rootFrameInput.Metadata.ExifProfile;

            Assert.Equal(TiffCompression.Lzw, frameMetaInput.Compression);
            Assert.Equal(TiffBitsPerPixel.Bit4, frameMetaInput.BitsPerPixel);

            // Save to Tiff
            var tiffEncoder = new TiffEncoder()
            {
                PhotometricInterpretation = TiffPhotometricInterpretation.Rgb
            };

            using var ms = new MemoryStream();
            image.Save(ms, tiffEncoder);

            // Assert
            ms.Position            = 0;
            using var encodedImage = Image.Load <Rgba32>(ms);

            ImageMetadata       encodedImageMetaData         = encodedImage.Metadata;
            ImageFrame <Rgba32> rootFrameEncodedImage        = encodedImage.Frames.RootFrame;
            TiffFrameMetadata   tiffMetaDataEncodedRootFrame = rootFrameEncodedImage.Metadata.GetTiffMetadata();
            ExifProfile         encodedImageExifProfile      = rootFrameEncodedImage.Metadata.ExifProfile;

            byte[] encodedImageXmpProfile = rootFrameEncodedImage.Metadata.XmpProfile;

            Assert.Equal(TiffBitsPerPixel.Bit4, tiffMetaDataEncodedRootFrame.BitsPerPixel);
            Assert.Equal(TiffCompression.Lzw, tiffMetaDataEncodedRootFrame.Compression);

            Assert.Equal(inputMetaData.HorizontalResolution, encodedImageMetaData.HorizontalResolution);
            Assert.Equal(inputMetaData.VerticalResolution, encodedImageMetaData.VerticalResolution);
            Assert.Equal(inputMetaData.ResolutionUnits, encodedImageMetaData.ResolutionUnits);

            Assert.Equal(rootFrameInput.Width, rootFrameEncodedImage.Width);
            Assert.Equal(rootFrameInput.Height, rootFrameEncodedImage.Height);

            PixelResolutionUnit resolutionUnitInput   = UnitConverter.ExifProfileToResolutionUnit(exifProfileInput);
            PixelResolutionUnit resolutionUnitEncoded = UnitConverter.ExifProfileToResolutionUnit(encodedImageExifProfile);

            Assert.Equal(resolutionUnitInput, resolutionUnitEncoded);
            Assert.Equal(exifProfileInput.GetValue(ExifTag.XResolution).Value.ToDouble(), encodedImageExifProfile.GetValue(ExifTag.XResolution).Value.ToDouble());
            Assert.Equal(exifProfileInput.GetValue(ExifTag.YResolution).Value.ToDouble(), encodedImageExifProfile.GetValue(ExifTag.YResolution).Value.ToDouble());

            Assert.Equal(xmpProfileInput, encodedImageXmpProfile);

            Assert.Equal("IrfanView", exifProfileInput.GetValue(ExifTag.Software).Value);
            Assert.Equal("This is Название", exifProfileInput.GetValue(ExifTag.ImageDescription).Value);
            Assert.Equal("This is Изготовитель камеры", exifProfileInput.GetValue(ExifTag.Make).Value);
            Assert.Equal("This is Авторские права", exifProfileInput.GetValue(ExifTag.Copyright).Value);

            Assert.Equal(exifProfileInput.GetValue(ExifTag.ImageDescription).Value, encodedImageExifProfile.GetValue(ExifTag.ImageDescription).Value);
            Assert.Equal(exifProfileInput.GetValue(ExifTag.Make).Value, encodedImageExifProfile.GetValue(ExifTag.Make).Value);
            Assert.Equal(exifProfileInput.GetValue(ExifTag.Copyright).Value, encodedImageExifProfile.GetValue(ExifTag.Copyright).Value);

            // Note that the encoded profile has PlanarConfiguration explicitly set, which is missing in the original image profile.
            Assert.Equal((ushort)TiffPlanarConfiguration.Chunky, encodedImageExifProfile.GetValue(ExifTag.PlanarConfiguration)?.Value);
            Assert.Equal(exifProfileInput.Values.Count + 1, encodedImageExifProfile.Values.Count);
        }
Example #12
0
        public void BaselineTags <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage(TiffDecoder))
            {
                ImageFrame <TPixel> rootFrame = image.Frames.RootFrame;
                Assert.Equal(32, rootFrame.Width);
                Assert.Equal(32, rootFrame.Height);
                Assert.NotNull(rootFrame.Metadata.XmpProfile);
                Assert.Equal(2599, rootFrame.Metadata.XmpProfile.Length);

                ExifProfile       exifProfile       = rootFrame.Metadata.ExifProfile;
                TiffFrameMetadata tiffFrameMetadata = rootFrame.Metadata.GetTiffMetadata();
                Assert.NotNull(exifProfile);

                // The original exifProfile has 30 values, but 4 of those values will be stored in the TiffFrameMetaData
                // and removed from the profile on decode.
                Assert.Equal(26, exifProfile.Values.Count);
                Assert.Equal(TiffBitsPerPixel.Bit4, tiffFrameMetadata.BitsPerPixel);
                Assert.Equal(TiffCompression.Lzw, tiffFrameMetadata.Compression);
                Assert.Equal("This is Название", exifProfile.GetValue(ExifTag.ImageDescription).Value);
                Assert.Equal("This is Изготовитель камеры", exifProfile.GetValue(ExifTag.Make).Value);
                Assert.Equal("This is Модель камеры", exifProfile.GetValue(ExifTag.Model).Value);
                Assert.Equal("IrfanView", exifProfile.GetValue(ExifTag.Software).Value);
                Assert.Null(exifProfile.GetValue(ExifTag.DateTime)?.Value);
                Assert.Equal("This is author1;Author2", exifProfile.GetValue(ExifTag.Artist).Value);
                Assert.Null(exifProfile.GetValue(ExifTag.HostComputer)?.Value);
                Assert.Equal("This is Авторские права", exifProfile.GetValue(ExifTag.Copyright).Value);
                Assert.Equal(4, exifProfile.GetValue(ExifTag.Rating).Value);
                Assert.Equal(75, exifProfile.GetValue(ExifTag.RatingPercent).Value);
                var expectedResolution = new Rational(10000, 1000, simplify: false);
                Assert.Equal(expectedResolution, exifProfile.GetValue(ExifTag.XResolution).Value);
                Assert.Equal(expectedResolution, exifProfile.GetValue(ExifTag.YResolution).Value);
                Assert.Equal(new Number[] { 8u }, exifProfile.GetValue(ExifTag.StripOffsets)?.Value, new NumberComparer());
                Assert.Equal(new Number[] { 297u }, exifProfile.GetValue(ExifTag.StripByteCounts)?.Value, new NumberComparer());
                Assert.Null(exifProfile.GetValue(ExifTag.ExtraSamples)?.Value);
                Assert.Equal(32u, exifProfile.GetValue(ExifTag.RowsPerStrip).Value);
                Assert.Null(exifProfile.GetValue(ExifTag.SampleFormat));
                Assert.Equal(TiffPredictor.None, tiffFrameMetadata.Predictor);
                Assert.Equal(PixelResolutionUnit.PixelsPerInch, UnitConverter.ExifProfileToResolutionUnit(exifProfile));
                ushort[] colorMap = exifProfile.GetValue(ExifTag.ColorMap)?.Value;
                Assert.NotNull(colorMap);
                Assert.Equal(48, colorMap.Length);
                Assert.Equal(10537, colorMap[0]);
                Assert.Equal(14392, colorMap[1]);
                Assert.Equal(58596, colorMap[46]);
                Assert.Equal(3855, colorMap[47]);
                Assert.Equal(TiffPhotometricInterpretation.PaletteColor, tiffFrameMetadata.PhotometricInterpretation);
                Assert.Equal(1u, exifProfile.GetValue(ExifTag.SamplesPerPixel).Value);

                ImageMetadata imageMetaData = image.Metadata;
                Assert.NotNull(imageMetaData);
                Assert.Equal(PixelResolutionUnit.PixelsPerInch, imageMetaData.ResolutionUnits);
                Assert.Equal(10, imageMetaData.HorizontalResolution);
                Assert.Equal(10, imageMetaData.VerticalResolution);

                TiffMetadata tiffMetaData = image.Metadata.GetTiffMetadata();
                Assert.NotNull(tiffMetaData);
                Assert.Equal(ByteOrder.LittleEndian, tiffMetaData.ByteOrder);
            }
        }
        protected static void TestStripLength <TPixel>(
            TestImageProvider <TPixel> provider,
            TiffPhotometricInterpretation photometricInterpretation,
            TiffCompression compression,
            bool useExactComparer  = true,
            float compareTolerance = 0.01f)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            // arrange
            var tiffEncoder = new TiffEncoder()
            {
                PhotometricInterpretation = photometricInterpretation, Compression = compression
            };

            using Image <TPixel> input = provider.GetImage();
            using var memStream = new MemoryStream();
            TiffFrameMetadata inputMeta        = input.Frames.RootFrame.Metadata.GetTiffMetadata();
            TiffCompression   inputCompression = inputMeta.Compression ?? TiffCompression.None;

            // act
            input.Save(memStream, tiffEncoder);

            // assert
            memStream.Position = 0;
            using var output   = Image.Load <Rgba32>(memStream);
            ExifProfile         exifProfileOutput = output.Frames.RootFrame.Metadata.ExifProfile;
            TiffFrameMetadata   outputMeta        = output.Frames.RootFrame.Metadata.GetTiffMetadata();
            ImageFrame <Rgba32> rootFrame         = output.Frames.RootFrame;

            Number rowsPerStrip = exifProfileOutput.GetValue(ExifTag.RowsPerStrip) != null?exifProfileOutput.GetValue(ExifTag.RowsPerStrip).Value : TiffConstants.RowsPerStripInfinity;

            Assert.True(output.Height > (int)rowsPerStrip);
            Assert.True(exifProfileOutput.GetValue(ExifTag.StripOffsets)?.Value.Length > 1);
            Number[] stripByteCounts = exifProfileOutput.GetValue(ExifTag.StripByteCounts)?.Value;
            Assert.NotNull(stripByteCounts);
            Assert.True(stripByteCounts.Length > 1);
            Assert.NotNull(outputMeta.BitsPerPixel);

            foreach (Number sz in stripByteCounts)
            {
                Assert.True((uint)sz <= TiffConstants.DefaultStripSize);
            }

            // For uncompressed more accurate test.
            if (compression == TiffCompression.None)
            {
                for (int i = 0; i < stripByteCounts.Length - 1; i++)
                {
                    // The difference must be less than one row.
                    int stripBytes = (int)stripByteCounts[i];
                    int widthBytes = ((int)outputMeta.BitsPerPixel + 7) / 8 * rootFrame.Width;

                    Assert.True((TiffConstants.DefaultStripSize - stripBytes) < widthBytes);
                }
            }

            // Compare with reference.
            TestTiffEncoderCore(
                provider,
                inputMeta.BitsPerPixel,
                photometricInterpretation,
                inputCompression,
                useExactComparer: useExactComparer,
                compareTolerance: compareTolerance);
        }
 public void UnrecoverableImagesShouldThrowCorrectError <TPixel>(TestImageProvider <TPixel> provider)
     where TPixel : struct, IPixel <TPixel> => Assert.Throws <ImageFormatException>(() => provider.GetImage());