예제 #1
0
 public ImagePackage(IImageDecoder decoder, ImageSource source, double width, double height)
 {
     this.Decoder = decoder;
     this.ImageSource = source;
     this.PixelWidth = width;
     this.PixelHeight = height;
 }
예제 #2
0
 /// <summary>
 /// Sets a specific image decoder as the decoder for a specific image format.
 /// </summary>
 /// <param name="imageFormat">The image format to register the encoder for.</param>
 /// <param name="decoder">The decoder to use,</param>
 public void SetDecoder(IImageFormat imageFormat, IImageDecoder decoder)
 {
     Guard.NotNull(imageFormat, nameof(imageFormat));
     Guard.NotNull(decoder, nameof(decoder));
     this.AddImageFormat(imageFormat);
     this.mimeTypeDecoders.AddOrUpdate(imageFormat, decoder, (s, e) => decoder);
 }
예제 #3
0
                public Key(PixelTypes pixelType, string filePath, IImageDecoder customDecoder)
                {
                    Type customType = customDecoder?.GetType();

                    this.commonValues      = new Tuple <PixelTypes, string, Type>(pixelType, filePath, customType);
                    this.decoderParameters = GetDecoderParameters(customDecoder);
                }
예제 #4
0
        private void DecodeJpegBenchmarkImpl(string fileName, IImageDecoder decoder)
        {
            // do not run this on CI even by accident
            if (TestEnvironment.RunsOnCI)
            {
                return;
            }

            const int ExecutionCount = 30;

            if (!Vector.IsHardwareAccelerated)
            {
                throw new Exception("Vector.IsHardwareAccelerated == false! ('prefer32 bit' enabled?)");
            }

            string path = TestFile.GetInputFileFullPath(fileName);

            byte[] bytes = File.ReadAllBytes(path);

            this.Measure(
                ExecutionCount,
                () =>
            {
                Image <Rgba32> img = Image.Load <Rgba32>(bytes, decoder);
            },
                // ReSharper disable once ExplicitCallerInfoArgument
                $"Decode {fileName}");
        }
예제 #5
0
        public static Image <TPixel> CompareToOriginal <TPixel>(
            this Image <TPixel> image,
            ITestImageProvider provider,
            ImageComparer comparer,
            IImageDecoder referenceDecoder = null)
            where TPixel : struct, IPixel <TPixel>
        {
            string path = TestImageProvider <TPixel> .GetFilePathOrNull(provider);

            if (path == null)
            {
                throw new InvalidOperationException("CompareToOriginal() works only with file providers!");
            }

            var testFile = TestFile.Create(path);

            referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(path);

            using (var original = Image.Load <TPixel>(testFile.Bytes, referenceDecoder))
            {
                comparer.VerifySimilarity(original, image);
            }

            return(image);
        }
예제 #6
0
        /// <summary>
        /// Loads the expected image with a reference decoder + compares it to <paramref name="image"/>.
        /// Also performs a debug save using <see cref="ImagingTestCaseUtility.SaveTestOutputFile{TPixel}"/>.
        /// </summary>
        internal static void VerifyEncoder <TPixel>(
            this Image <TPixel> image,
            ITestImageProvider provider,
            string extension,
            object testOutputDetails,
            IImageEncoder encoder,
            ImageComparer customComparer   = null,
            bool appendPixelTypeToFileName = true,
            string referenceImageExtension = null,
            IImageDecoder referenceDecoder = null)
            where TPixel : struct, IPixel <TPixel>
        {
            string actualOutputFile = provider.Utility.SaveTestOutputFile(
                image,
                extension,
                encoder,
                testOutputDetails,
                appendPixelTypeToFileName);

            referenceDecoder = referenceDecoder ?? TestEnvironment.GetReferenceDecoder(actualOutputFile);

            using (var actualImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
            {
                ImageComparer comparer = customComparer ?? ImageComparer.Exact;
                comparer.VerifySimilarity(actualImage, image);
            }
        }
예제 #7
0
        /// <summary>
        /// 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 <see cref="DebugSave{TPixel}(Image{TPixel}, ITestImageProvider, object, string, bool)"/>.
        /// </summary>
        /// <typeparam name="TPixel">The pixel format</typeparam>
        /// <param name="image">The image</param>
        /// <param name="comparer">The <see cref="ImageComparer"/> to use</param>
        /// <param name="provider">The image provider</param>
        /// <param name="testOutputDetails">Details to be concatenated to the test output file, describing the parameters of the test.</param>
        /// <param name="extension">The extension</param>
        /// <param name="grayscale">A boolean indicating whether we should debug save + compare against a grayscale image, smaller in size.</param>
        /// <param name="appendPixelTypeToFileName">A boolean indicating whether to append the pixel type to the  output file name.</param>
        /// <param name="appendSourceFileOrDescription">A boolean indicating whether to append <see cref="ITestImageProvider.SourceFileOrDescription"/> to the test output file name.</param>
        /// <param name="decoder">A custom decoder.</param>
        /// <returns></returns>
        public static Image <TPixel> CompareToReferenceOutput <TPixel>(
            this Image <TPixel> image,
            ImageComparer comparer,
            ITestImageProvider provider,
            object testOutputDetails           = null,
            string extension                   = "png",
            bool grayscale                     = false,
            bool appendPixelTypeToFileName     = true,
            bool appendSourceFileOrDescription = true,
            IImageDecoder decoder              = null)
            where TPixel : struct, IPixel <TPixel>
        {
            using (Image <TPixel> referenceImage = GetReferenceOutputImage <TPixel>(
                       provider,
                       testOutputDetails,
                       extension,
                       appendPixelTypeToFileName,
                       appendSourceFileOrDescription,
                       decoder))
            {
                comparer.VerifySimilarity(referenceImage, image);
            }

            return(image);
        }
예제 #8
0
 /// <summary>
 /// Create a new instance of the <see cref="Image"/> class from the given file.
 /// </summary>
 /// <param name="config">The Configuration.</param>
 /// <param name="path">The file path to the image.</param>
 /// <param name="decoder">The decoder.</param>
 /// <exception cref="NotSupportedException">
 /// Thrown if the stream is not readable nor seekable.
 /// </exception>
 /// <returns>The <see cref="Image"/>.</returns>
 public static Image Load(Configuration config, string path, IImageDecoder decoder)
 {
     using (Stream stream = config.FileSystem.OpenRead(path))
     {
         return(Load(config, stream, decoder));
     }
 }
예제 #9
0
 /// <summary>
 /// Loads the image from the given byte array.
 /// </summary>
 /// <param name="data">The byte array containing image data.</param>
 /// <param name="decoder">The decoder.</param>
 /// <param name="options">The options for the decoder.</param>
 /// <exception cref="NotSupportedException">
 /// Thrown if the stream is not readable nor seekable.
 /// </exception>
 /// <returns>The image</returns>
 public static Image Load(byte[] data, IImageDecoder decoder, IDecoderOptions options)
 {
     using (MemoryStream ms = new MemoryStream(data))
     {
         return(Load(ms, decoder, options));
     }
 }
예제 #10
0
        /// <summary>
        /// Decode first frame for the specified file.
        /// </summary>
        ///
        /// <param name="fileName">File name to read image from.</param>
        /// <param name="imageInfo">Information about the decoded image.</param>
        ///
        /// <returns>Return decoded image. In the case if file format support multiple
        /// frames, the method return the first frame.</returns>
        ///
        /// <remarks><para>The method uses table of registered image decoders to find the one,
        /// which should be used for the specified file. If there is not appropriate decoder
        /// found, the method uses default .NET's image decoding routine (see
        /// <see cref="System.Drawing.Image.FromFile(string)"/>).</para></remarks>
        ///
        public static Bitmap DecodeFromFile(string fileName, out ImageInfo imageInfo)
        {
            string fileExtension = FormatDecoderAttribute.GetNormalizedExtension(fileName);

            IImageDecoder decoder = FormatDecoderAttribute.GetDecoders(fileExtension, decoderTypes, decoders.Value);

            if (decoder != null)
            {
                // open stream
                using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    // open decoder
                    decoder.Open(stream);

                    // read the first frame from the image
                    Bitmap bitmap = decoder.DecodeFrame(0, out imageInfo);

                    // close the decoder and return the bitmap
                    decoder.Close();
                    return(bitmap);
                }
            }
            else
            {
                // use default .NET's image decoding routine
                Bitmap bitmap = FromFile(fileName);

                decoderTypes[fileExtension] = null; // mark that the file could be loaded using default .NET decoders

                imageInfo = new ImageInfo(bitmap.Width, bitmap.Height, Image.GetPixelFormatSize(bitmap.PixelFormat), 0, 1);

                return(bitmap);
            }
        }
예제 #11
0
        private async Task LoadDecoderAsync()
        {
            _rawStream.Position = _originalPosition;
            Stream rawImageReaderStream = _imageFormat.CreateReader().CreateInputStream(_rawStream, true);

            _imageDecoder      = _imageDecoderFactory.BuildDecoder(rawImageReaderStream, _decodingConfiguration);
            _imageReaderStream = await _imageDecoder.GetDataReaderStreamAsync(rawImageReaderStream);
        }
예제 #12
0
 /// <summary>
 /// Create a new instance of the <see cref="Image{TPixel}"/> class from the given byte array.
 /// </summary>
 /// <param name="data">The byte array containing image data.</param>
 /// <param name="decoder">The decoder.</param>
 /// <param name="options">The options for the decoder.</param>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 /// <returns>A new <see cref="Image{TPixel}"/>.</returns>
 public static Image <TPixel> Load <TPixel>(byte[] data, IImageDecoder decoder, IDecoderOptions options)
     where TPixel : struct, IPixel <TPixel>
 {
     using (var ms = new MemoryStream(data))
     {
         return(Load <TPixel>(ms, decoder, options));
     }
 }
예제 #13
0
 public static Image <TPixel> CompareToOriginal <TPixel>(
     this Image <TPixel> image,
     ITestImageProvider provider,
     IImageDecoder referenceDecoder = null)
     where TPixel : unmanaged, IPixel <TPixel>
 {
     return(CompareToOriginal(image, provider, ImageComparer.Tolerant(), referenceDecoder));
 }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="SavePath"></param>
        /// <param name="ImageDecoder"></param>
        /// <param name="Size"></param>
        public void CreateSmallPic(Stream stream, string SavePath, IImageDecoder ImageDecoder, int Size)
        {
            Image <Rgba32> image = Image.Load(stream, ImageDecoder);

            ReSize(ref image, Size);
            SaveThumbPic(ref image, SavePath);
            image.Dispose();//销毁
        }
예제 #15
0
 /// <summary>
 /// Create a new instance of the <see cref="Image"/> class from the given file.
 /// </summary>
 /// <param name="configuration">The Configuration.</param>
 /// <param name="path">The file path to the image.</param>
 /// <param name="decoder">The decoder.</param>
 /// <exception cref="NotSupportedException">
 /// Thrown if the stream is not readable nor seekable.
 /// </exception>
 /// <returns>The <see cref="Image"/>.</returns>
 public static Image Load(Configuration configuration, string path, IImageDecoder decoder)
 {
     Guard.NotNull(configuration, nameof(configuration));
     using (Stream stream = configuration.FileSystem.OpenRead(path))
     {
         return(Load(configuration, stream, decoder));
     }
 }
예제 #16
0
 /// <summary>
 /// Create a new instance of the <see cref="Image{TPixel}"/> class from the given byte array.
 /// </summary>
 /// <param name="data">The byte array containing image data.</param>
 /// <param name="decoder">The decoder.</param>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 /// <returns>A new <see cref="Image{TPixel}"/>.</returns>
 public static Image <TPixel> Load <TPixel>(byte[] data, IImageDecoder decoder)
     where TPixel : struct, IPixel <TPixel>
 {
     using (var memoryStream = new MemoryStream(data))
     {
         return(Load <TPixel>(memoryStream, decoder));
     }
 }
예제 #17
0
 /// <summary>
 /// Load a new instance of <see cref="Image{TPixel}"/> from the given encoded byte array.
 /// </summary>
 /// <param name="data">The byte array containing encoded image data.</param>
 /// <param name="decoder">The decoder.</param>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 /// <returns>A new <see cref="Image{TPixel}"/>.</returns>
 public static Image <TPixel> Load <TPixel>(byte[] data, IImageDecoder decoder)
     where TPixel : struct, IPixel <TPixel>
 {
     using (var stream = new MemoryStream(data, 0, data.Length, false, true))
     {
         return(Load <TPixel>(stream, decoder));
     }
 }
예제 #18
0
    static ConversionResult Convert(Stream stream, string extension, IImageDecoder decoder)
    {
        var image = Image.Load(stream, decoder);

        stream.Position = 0;
        var info = image.GetInfo();

        return(new(info, extension, stream));
    }
예제 #19
0
            public override Task <Image <TPixel> > GetImageAsync(IImageDecoder decoder)
            {
                Guard.NotNull(decoder, nameof(decoder));

                // Used in small subset of decoder tests, no caching.
                string path = Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, this.FilePath);

                return(Image.LoadAsync <TPixel>(this.Configuration, path, decoder));
            }
예제 #20
0
        private static void TestPngEncoderCore <TPixel>(
            TestImageProvider <TPixel> provider,
            PngColorType pngColorType,
            PngFilterMethod pngFilterMethod,
            PngBitDepth bitDepth,
            PngInterlaceMode interlaceMode,
            PngCompressionLevel compressionLevel = PngCompressionLevel.DefaultCompression,
            int paletteSize               = 255,
            bool appendPngColorType       = false,
            bool appendPngFilterMethod    = false,
            bool appendPixelType          = false,
            bool appendCompressionLevel   = false,
            bool appendPaletteSize        = false,
            bool appendPngBitDepth        = false,
            PngChunkFilter optimizeMethod = PngChunkFilter.None)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage())
            {
                var encoder = new PngEncoder
                {
                    ColorType        = pngColorType,
                    FilterMethod     = pngFilterMethod,
                    CompressionLevel = compressionLevel,
                    BitDepth         = bitDepth,
                    Quantizer        = new WuQuantizer(new QuantizerOptions {
                        MaxColors = paletteSize
                    }),
                    InterlaceMethod = interlaceMode,
                    ChunkFilter     = optimizeMethod,
                };

                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 <TPixel>(actualOutputFile, new PngDecoder()))
                    using (var referenceImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
                    {
                        ImageComparer.Exact.VerifySimilarity(referenceImage, imageSharpImage);
                    }
            }
        }
예제 #21
0
        private static void TestPngEncoderCore <TPixel>(
            TestImageProvider <TPixel> provider,
            PngColorType pngColorType,
            int compressionLevel        = 6,
            int paletteSize             = 255,
            bool appendPngColorType     = 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
                {
                    PngColorType     = pngColorType,
                    CompressionLevel = compressionLevel,
                    Quantizer        = new WuQuantizer(paletteSize)
                };

                string pngColorTypeInfo     = appendPngColorType ? pngColorType.ToString() : "";
                string compressionLevelInfo = appendCompressionLevel ? $"_C{compressionLevel}" : "";
                string paletteSizeInfo      = appendPaletteSize ? $"_PaletteSize-{paletteSize}" : "";
                string debugInfo            = $"{pngColorTypeInfo}{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);

                using (var actualImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
                    using (var referenceImage = Image.Load <TPixel>(referenceOutputFile, referenceDecoder))
                    {
                        float paletteToleranceHack = 80f / paletteSize;
                        paletteToleranceHack = paletteToleranceHack * paletteToleranceHack;
                        ImageComparer comparer = pngColorType == PngColorType.Palette
                                                 ? ImageComparer.Tolerant(ToleranceThresholdForPaletteEncoder * paletteToleranceHack)
                                                 : ImageComparer.Exact;

                        comparer.VerifySimilarity(referenceImage, actualImage);
                    }
            }
        }
예제 #22
0
        /// <summary>
        /// Load a new instance of <see cref="Image{TPixel}"/> from the given encoded byte array.
        /// </summary>
        /// <param name="data">The byte array containing encoded image data.</param>
        /// <param name="decoder">The decoder.</param>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        /// <exception cref="ArgumentNullException">The data is null.</exception>
        /// <exception cref="UnknownImageFormatException">Image format not recognised.</exception>
        /// <exception cref="InvalidImageContentException">Image contains invalid content.</exception>
        /// <returns>A new <see cref="Image{TPixel}"/>.</returns>
        public static Image <TPixel> Load <TPixel>(byte[] data, IImageDecoder decoder)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            Guard.NotNull(data, nameof(data));

            using (var stream = new MemoryStream(data, 0, data.Length, false, true))
            {
                return(Load <TPixel>(stream, decoder));
            }
        }
        public void GetReferenceDecoder_ReturnsCorrectDecoders_Windows(string fileName, Type expectedDecoderType)
        {
            if (!TestEnvironment.IsWindows)
            {
                return;
            }

            IImageDecoder decoder = TestEnvironment.GetReferenceDecoder(fileName);
            Assert.IsType(expectedDecoderType, decoder);
        }
예제 #24
0
        /// <summary>
        /// Loads the image from the given file.
        /// </summary>
        /// <typeparam name="TColor">The pixel format.</typeparam>
        /// <param name="path">The file path to the image.</param>
        /// <param name="decoder">The decoder.</param>
        /// <param name="options">The options for the decoder.</param>
        /// <exception cref="NotSupportedException">
        /// Thrown if the stream is not readable nor seekable.
        /// </exception>
        /// <returns>The image</returns>
        public static Image <TColor> Load <TColor>(string path, IImageDecoder decoder, IDecoderOptions options)
            where TColor : struct, IPixel <TColor>
        {
            Configuration config = Configuration.Default;

            using (Stream s = config.FileSystem.OpenRead(path))
            {
                return(Load <TColor>(s, decoder, options));
            }
        }
예제 #25
0
        /// <summary>
        /// By reading the header on the provided stream this calculates the images format.
        /// </summary>
        /// <param name="stream">The image stream to read the header from.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>The decoder and the image format or null if none found.</returns>
        private static async Task <(IImageDecoder decoder, IImageFormat format)> DiscoverDecoderAsync(Stream stream, Configuration config)
        {
            IImageFormat format = await InternalDetectFormatAsync(stream, config).ConfigureAwait(false);

            IImageDecoder decoder = format != null
                ? config.ImageFormatsManager.FindDecoder(format)
                : null;

            return(decoder, format);
        }
        private static void TestMetaDataImpl(
            bool useIdentify,
            IImageDecoder decoder,
            string imagePath,
            int expectedPixelSize,
            bool exifProfilePresent,
            bool iccProfilePresent)
        {
            var testFile = TestFile.Create(imagePath);

            using (var stream = new MemoryStream(testFile.Bytes, false))
            {
                IImageInfo imageInfo = useIdentify
                                           ? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream)
                                           : decoder.Decode <Rgba32>(Configuration.Default, stream);

                Assert.NotNull(imageInfo);
                Assert.NotNull(imageInfo.PixelType);

                if (useIdentify)
                {
                    Assert.Equal(expectedPixelSize, imageInfo.PixelType.BitsPerPixel);
                }
                else
                {
                    // When full Image<TPixel> decoding is performed, BitsPerPixel will match TPixel
                    int bpp32 = Unsafe.SizeOf <Rgba32>() * 8;
                    Assert.Equal(bpp32, imageInfo.PixelType.BitsPerPixel);
                }

                ExifProfile exifProfile = imageInfo.MetaData.ExifProfile;

                if (exifProfilePresent)
                {
                    Assert.NotNull(exifProfile);
                    Assert.NotEmpty(exifProfile.Values);
                }
                else
                {
                    Assert.Null(exifProfile);
                }

                IccProfile iccProfile = imageInfo.MetaData.IccProfile;

                if (iccProfilePresent)
                {
                    Assert.NotNull(iccProfile);
                    Assert.NotEmpty(iccProfile.Entries);
                }
                else
                {
                    Assert.Null(iccProfile);
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Async loading image from cache or network
        /// </summary>
        /// <param name="imageUri">Uri of the image to load</param>
        /// <returns>BitmapImage if load was successfull or null otherwise</returns>
        public virtual async Task <ImagePackage> LoadImage(Image image, Uri uriSource,
                                                           CancellationTokenSource cancellationTokenSource)
        {
            CheckConfig();
            ImagePackage imagePackage = null;
            var          decoders     = this.GetAvailableDecoders();

            var randStream = await this.LoadImageStream(uriSource, cancellationTokenSource);

            if (randStream == null)
            {
                throw new Exception("stream is null");
            }
            if (decoders.Count > 0)
            {
                int maxHeaderSize = decoders.Max(x => x.HeaderSize);
                if (maxHeaderSize > 0)
                {
                    byte[] header     = new byte[maxHeaderSize];
                    var    readStream = randStream.AsStreamForRead();
                    readStream.Position = 0;
                    await readStream.ReadAsync(header, 0, maxHeaderSize);

                    readStream.Position = 0;
                    int           maxPriority = -1;
                    IImageDecoder decoder     = null;
                    foreach (var item in decoders)
                    {
                        var priority = item.GetPriority(header);
                        if (priority > maxPriority)
                        {
                            maxPriority = priority;
                            decoder     = item;
                        }
                    }
                    if (decoder != null)
                    {
                        var package = await decoder.InitializeAsync(image.Dispatcher, image, uriSource, randStream, cancellationTokenSource);

                        if (!cancellationTokenSource.IsCancellationRequested)
                        {
                            imagePackage = package;
                            //imagePackage?.Decoder?.Start();
                        }
                    }
                }
            }
            return(imagePackage);

            //var bitmapImage = new BitmapImage();
            //var stream = await LoadImageStream(imageUri, cancellationTokenSource);
            //await bitmapImage.SetSourceAsync(stream);
            //return bitmapImage;
        }
예제 #28
0
 private static void ConfigureCodecs(
     this Configuration cfg,
     IImageFormat imageFormat,
     IImageDecoder decoder,
     IImageEncoder encoder,
     IImageFormatDetector detector)
 {
     cfg.ImageFormatsManager.SetDecoder(imageFormat, decoder);
     cfg.ImageFormatsManager.SetEncoder(imageFormat, encoder);
     cfg.ImageFormatsManager.AddImageFormatDetector(detector);
 }
예제 #29
0
        /// <summary>
        /// Create a new instance of the <see cref="Image"/> class from the given file.
        /// </summary>
        /// <param name="configuration">The Configuration.</param>
        /// <param name="path">The file path to the image.</param>
        /// <param name="decoder">The decoder.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <exception cref="ArgumentNullException">The configuration is null.</exception>
        /// <exception cref="ArgumentNullException">The path is null.</exception>
        /// <exception cref="ArgumentNullException">The decoder is null.</exception>
        /// <exception cref="UnknownImageFormatException">Image format not recognised.</exception>
        /// <exception cref="NotSupportedException">Image format is not supported.</exception>
        /// <exception cref="InvalidImageContentException">Image contains invalid content.</exception>
        /// <returns>A <see cref="Task{Image}"/> representing the asynchronous operation.</returns>
        public static Task <Image> LoadAsync(
            Configuration configuration,
            string path,
            IImageDecoder decoder,
            CancellationToken cancellationToken = default)
        {
            Guard.NotNull(configuration, nameof(configuration));
            Guard.NotNull(path, nameof(path));

            using Stream stream = configuration.FileSystem.OpenRead(path);
            return(LoadAsync(configuration, stream, decoder, cancellationToken));
        }
        private static void TestMetadataImpl(
            bool useIdentify,
            IImageDecoder decoder,
            string imagePath,
            int expectedPixelSize,
            bool exifProfilePresent,
            bool iccProfilePresent)
        {
            TestImageInfo(
                imagePath,
                decoder,
                useIdentify,
                imageInfo =>
            {
                Assert.NotNull(imageInfo);
                Assert.NotNull(imageInfo.PixelType);

                if (useIdentify)
                {
                    Assert.Equal(expectedPixelSize, imageInfo.PixelType.BitsPerPixel);
                }
                else
                {
                    // When full Image<TPixel> decoding is performed, BitsPerPixel will match TPixel
                    int bpp32 = Unsafe.SizeOf <Rgba32>() * 8;
                    Assert.Equal(bpp32, imageInfo.PixelType.BitsPerPixel);
                }

                ExifProfile exifProfile = imageInfo.Metadata.ExifProfile;

                if (exifProfilePresent)
                {
                    Assert.NotNull(exifProfile);
                    Assert.NotEmpty(exifProfile.Values);
                }
                else
                {
                    Assert.Null(exifProfile);
                }

                IccProfile iccProfile = imageInfo.Metadata.IccProfile;

                if (iccProfilePresent)
                {
                    Assert.NotNull(iccProfile);
                    Assert.NotEmpty(iccProfile.Entries);
                }
                else
                {
                    Assert.Null(iccProfile);
                }
            });
        }
예제 #31
0
        private static void TestImageInfo(string imagePath, IImageDecoder decoder, bool useIdentify, Action <IImageInfo> test)
        {
            var testFile = TestFile.Create(imagePath);

            using (var stream = new MemoryStream(testFile.Bytes, false))
            {
                IImageInfo imageInfo = useIdentify
                                           ? ((IImageInfoDetector)decoder).Identify(Configuration.Default, stream)
                                           : decoder.Decode <Rgba32>(Configuration.Default, stream);
                test(imageInfo);
            }
        }
예제 #32
0
        public void Load(Stream stream, IImageDecoder decoder)
        {
            try
            {
                if (!stream.CanRead)
                {
                    throw new NotSupportedException("Cannot read from the stream.");
                }

                if (!stream.CanSeek)
                {
                    throw new NotSupportedException("The stream does not support seeking.");
                }

                int maxHeaderSize = decoder.HeaderSize;
                byte[] header = new byte[maxHeaderSize];

                stream.Read(header, 0, maxHeaderSize);
                stream.Position = 0;

                //var decoder = FindFirstSupport(decoders, header); //decoders.FirstOrDefault(x => x.IsSupportedFileFormat(header));
                if (decoder != null)
                {
                    decoder.Decode(this, stream);

                }



                //if (IsLoading)
                //{
                //    IsLoading = false;

                //    StringBuilder stringBuilder = new StringBuilder();
                //    stringBuilder.AppendLine("Image cannot be loaded. Available decoders:");

                //    foreach (IImageDecoder decoder in decoders)
                //    {
                //        stringBuilder.AppendLine("-" + decoder);
                //    }

                //    throw new UnsupportedImageFormatException(stringBuilder.ToString());
                //}
            }
            finally
            {
                stream.Dispose();
            }
        }
예제 #33
0
        private static ImageProperty[] GetAllPropertiesInternal(IImageDecoder decoder)
        {
            uint num;
            uint num2;
            if (decoder == null)
            {
                throw new ArgumentNullException();
            }
            List<ImageProperty> list = new List<ImageProperty>(ImageUtils.GetAllTags(decoder).Length);
            decoder.GetPropertySize(out num, out num2);

            // Если драйвер возвращает заведомо мало информации, то значит она битая и вытащить
            // оттуда всё равно ничего не вытащить. Число 30 взято исходя из опытных расчётов.
            // Выходим из процедуры, иначе вывалится ошибка COM.
            if (num < num2 * 30)
                return list.ToArray();

            IntPtr pItems = Marshal.AllocHGlobal((int)num);
            PropertyItem[] itemArray = new PropertyItem[num2];
            decoder.GetAllPropertyItems(num, num2, pItems);
            IntPtr ptr = pItems;
            for (uint i = 0; i < num2; i++)
            {
                itemArray[i] = (PropertyItem)Marshal.PtrToStructure(ptr, typeof(PropertyItem));
                ptr = (IntPtr)(ptr.ToInt32() + Marshal.SizeOf(typeof(PropertyItem)));
            }
            foreach (PropertyItem item in itemArray)
            {
                list.Add(ImageUtils.LoadProperty(item));
            }
            Marshal.FreeHGlobal(pItems);
            return list.ToArray();
        }
예제 #34
0
        /// <summary>
        /// Register image decoder for a specified file extension.
        /// </summary>
        /// 
        /// <param name="fileExtension">File extension to register decoder for ("bmp", for example).</param>
        /// <param name="decoder">Image decoder to use for the specified file extension.</param>
        /// 
        /// <remarks><para>The method allows to register image decoder object, which should be used
        /// to decode images from files with the specified extension.</para></remarks>
        /// 
        public static void RegisterDecoder( string fileExtension, IImageDecoder decoder )
        {
            System.Diagnostics.Debug.WriteLine( "Registering decoder: " + fileExtension );

            decoders.Add( fileExtension.ToLower( ), decoder );
        }
예제 #35
0
        //Handles encoding/decoding using the correct method and settings when the 'Proceed' button is pressed.
        private void _encodeOrDecodeImage() {
            if (rdioEncode.Checked) {
                if (picResult.Image != null) {
                    picResult.Image.Dispose();
                }

                byte[] msg = _getMessageFromTextboxOrFile();

                //Create an _imageEncoder according according to selected method
                if (!OptionsForm.LSBMethodSelected) {
                    lblProcessing.Text = "Encoding using GT method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();

                    //Use simple constructor if a table is null 
                    if (OptionsForm.QuantizationTableY == null || OptionsForm.QuantizationTableChr == null || OptionsForm.HuffmanTableYAC == null || OptionsForm.HuffmanTableYDC == null || OptionsForm.HuffmanTableChrAC == null || OptionsForm.HuffmanTableChrDC == null) {
                        _imageEncoder = new JpegImage(CoverImage, OptionsForm.Quality, OptionsForm.MValue);
                    } else {
                        _imageEncoder = new JpegImage(CoverImage, OptionsForm.Quality, OptionsForm.MValue, OptionsForm.QuantizationTableY, OptionsForm.QuantizationTableChr, OptionsForm.HuffmanTableYDC, OptionsForm.HuffmanTableYAC, OptionsForm.HuffmanTableChrDC, OptionsForm.HuffmanTableChrAC);
                    }
                } else {
                    lblProcessing.Text = "Encoding using LSB method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageEncoder = new LeastSignificantBitImage(CoverImage);
                }

                //Encode
                try {
                    _imageEncoder.Encode(msg);
                    _imageEncoder.Save(_userSavePath);
                    picResult.Image = Image.FromFile(_userSavePath);
                }
                catch (ImageCannotContainDataException) {
                    MessageBox.Show("Image cannot contain data!");
                }
                catch (ExternalException) {
                    MessageBox.Show("Failed to load result picture! Your Huffman table may be invalid");
                }
                catch (Exception) {
                    MessageBox.Show("An error occured when encoding!");
                }
            } else if (rdioDecode.Checked) {
                picResult.Image = null;
                tbMessage.Text = "";

                if (!OptionsForm.LSBMethodSelected) {
                    lblProcessing.Text = "Decoding using GT method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageDecoder = new JPEGDecoder(_decodeFilePath);
                } else {
                    lblProcessing.Text = "Decoding using LSB method...";
                    lblProcessing.Visible = true;
                    Application.DoEvents();
                    _imageDecoder = new LeastSignificantBitDecoder(_decodeFilePath);
                }

                //Decode
                try {
                    byte[] message = _imageDecoder.Decode();
                    tbMessage.Text = new string(message.Select(x => (char)x).ToArray());
                    File.WriteAllBytes(_userSavePath, message);
                }
                catch (Exception) {
                    MessageBox.Show("An Error occured when decoding! Cover image might not contain a message.");
                }
            }
        }