Exemplo n.º 1
0
        public void Encode_UseCompression_WhenTextIsGreaterThenThreshold_Works <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            var decoder = new PngDecoder();

            using (Image <TPixel> 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
                    {
                        TextCompressionThreshold = 50
                    });

                    memoryStream.Position = 0;
                    using (Image <Rgba32> image = decoder.Decode <Rgba32>(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));
                    }
                }
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ContentType"></param>
        public void SetDecoder(string ContentType)
        {
            IImageDecoder imageDecoder = null;

            switch (ContentType)
            {
            case _Png:                  // PNG 格式上传会出错,原因未知,所以曲线救国(已经解决)
                imageDecoder = new PngDecoder()
                {
                };
                break;

            case _Bmp:
                imageDecoder = new BmpDecoder();
                break;

            case _Gif:
                imageDecoder = new GifDecoder();
                break;

            case _Jpg:
                imageDecoder = new JpegDecoder();
                break;

            default:        // 前面已经验证过,因此走不到这里,不需要处理
                break;
            }
            ImageDecoder = imageDecoder;
        }
Exemplo n.º 3
0
        public void Encoder_PreservesTextData <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : struct, IPixel <TPixel>
        {
            var decoder = new PngDecoder();

            using (Image <TPixel> input = provider.GetImage(decoder))
                using (var memoryStream = new MemoryStream())
                {
                    input.Save(memoryStream, new PngEncoder());

                    memoryStream.Position = 0;
                    using (Image <Rgba32> image = decoder.Decode <Rgba32>(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"));
                    }
                }
        }
Exemplo n.º 4
0
        public void Decode_8bitTestImages(string path, int w, int h)
        {
            var d = new PngDecoder();

            // Expect exception here, 8bit pngs are not yet supported
            Assert.Throws<NotImplementedException>(() => d.Decode(File.ReadAllBytes(path)));
        }
Exemplo n.º 5
0
        public static ImageInfo?FromStream(Stream stream)
        {
            ImageInfo?info = null;

            if (JpgDecoder.Test(stream))
            {
                info = JpgDecoder.Info(stream);
            }
            else if (PngDecoder.Test(stream))
            {
                info = PngDecoder.Info(stream);
            }
            else if (BmpDecoder.Test(stream))
            {
                info = BmpDecoder.Info(stream);
            }
            else if (GifDecoder.Test(stream))
            {
                info = GifDecoder.Info(stream);
            }
            else if (PsdDecoder.Test(stream))
            {
                info = PsdDecoder.Info(stream);
            }
            else if (TgaDecoder.Test(stream))
            {
                info = TgaDecoder.Info(stream);
            }

            return(info);
        }
Exemplo n.º 6
0
        public void DecodePngImageTest()
        {
            using (Stream stream = File.OpenRead("screenshot.png"))
                using (PngDecoder decoder = new PngDecoder(stream))
                {
                    Assert.Equal(8, decoder.BitDepth);
                    Assert.Equal(0x00214800, decoder.DecompressedSize);
                    Assert.Equal(0x780, decoder.BytesPerRow);
                    Assert.Equal(3, decoder.Channels);
                    Assert.Equal(PngColorType.RGB, decoder.ColorType);
                    Assert.Equal(1136, decoder.Height);
                    Assert.Equal(stream, decoder.Stream);

                    // The revision can differ, e.g. 1.16.34 on Windows and 1.16.20 on Ubuntu Xenial, so don't check the
                    // entire string.
                    Assert.NotNull(decoder.Version);
                    var version = new Version(decoder.Version);
                    Assert.Equal(1, version.Major);

                    Assert.Equal(640, decoder.Width);

                    byte[] data = new byte[decoder.DecompressedSize];
                    decoder.TransformSetBgr();
                    decoder.Decode(data);

                    SHA1 hasher     = SHA1.Create();
                    var  hash       = hasher.ComputeHash(data);
                    var  hashString = string.Join("", hash.Select(c => c.ToString("x2")));
                    Assert.Equal(2181120, data.Length);
                    Assert.Equal("43e046fbb27bfc352c6007247380966dc92f25e0", hashString);
                }
        }
Exemplo n.º 7
0
        public void Decode_8bitTestImages(string path, int w, int h)
        {
            var d = new PngDecoder();

            // Expect exception here, 8bit pngs are not yet supported
            Assert.Throws <NotImplementedException>(() => d.Decode(File.ReadAllBytes(path)));
        }
Exemplo n.º 8
0
        public static Image FromFile(string filename)
        {
            //TODO: review here
            //should not depend on the extension
            string fileext = IO.Path.GetExtension(filename).ToLower();

            switch (fileext)
            {
            default:
                throw new NotSupportedException();

            case ".jpg":
            {
                JpegDecoder jpegDec = new JpegDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    jpegDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".gif":
            {
                GifDecoder gifDec = new GifDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    gifDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".png":
            {
                ImageTools.IO.Png.PngDecoder pngDecoder = new PngDecoder();
                //HjgPngDecoder pngDecoder = new HjgPngDecoder();
                //PngDecoder pngDecoder = new PngDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    pngDecoder.Decode(outputImg, fs);
                }

                Bitmap bmp = new Bitmap(outputImg.PixelWidth,
                                        outputImg.PixelHeight, outputImg.Pixels,
                                        outputImg.DensityXInt32, outputImg.DensityYInt32);
                bmp.PixelFormat = Imaging.PixelFormat.Format32bppArgb;
                return(bmp);
            }
            }
            return(null);
        }
Exemplo n.º 9
0
 public McResourcePack(ZipArchive archive, McResourcePackPreloadCallback preloadCallback)
 {
     PngDecoder = new PngDecoder()
     {
         IgnoreMetadata = true
     };
     PreloadCallback = preloadCallback;
     //_archive = archive;
     Load(archive);
 }
Exemplo n.º 10
0
 public void Decode_32bitTestImages(string path, int w, int h)
 {
     var d = new PngDecoder();
     var pixels = d.Decode(File.ReadAllBytes(path));
     Assert.AreEqual(w, pixels.GetLength(0));
     Assert.AreEqual(h, pixels.GetLength(1));
     Assert.IsNotNull(pixels);
     var e = new PngEncoder(new PngEncoderOptions());
     var encodedPixels = e.Encode(pixels);
     File.WriteAllBytes(Path.ChangeExtension(path, "out.png"), encodedPixels);
 }
Exemplo n.º 11
0
        [InlineData(PngChunkTypes.Physical)] // It's ok to test physical as we don't throw for duplicate chunks.
        //[InlineData(PngChunkTypes.Text)] //TODO: Figure out how to test this
        public void Decode_IncorrectCRCForNonCriticalChunk_ExceptionIsThrown(string chunkName)
        {
            using (var memStream = new MemoryStream())
            {
                WriteHeaderChunk(memStream);
                WriteChunk(memStream, chunkName);
                WriteDataChunk(memStream);

                var decoder = new PngDecoder();
                decoder.Decode <Rgb24>(null, memStream);
            }
        }
Exemplo n.º 12
0
        public McResourcePack(ZipArchive archive, McResourcePackPreloadCallback preloadCallback, LoadProgress progressReporter = null)
        {
            ProgressReporter = progressReporter;

            PngDecoder = new PngDecoder()
            {
                IgnoreMetadata = true
            };
            PreloadCallback = preloadCallback;
            //_archive = archive;
            Load(archive);
        }
Exemplo n.º 13
0
    public IReadOnlyTexture <byte> Serdes(IReadOnlyTexture <byte> existing, AssetInfo info, AssetMapping mapping, ISerializer s, IJsonUtil jsonUtil)
    {
        if (info == null)
        {
            throw new ArgumentNullException(nameof(info));
        }
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }

        var paletteNum = info.Get(AssetProperty.PaletteId, 0);
        var paletteId  = new PaletteId(AssetType.Palette, paletteNum);
        var palette    = Resolve <IAssetManager>().LoadPalette(paletteId);

        if (palette == null)
        {
            throw new InvalidOperationException($"Could not load palette {paletteId} ({paletteNum}) for asset {info.AssetId} in file {info.File.Filename}");
        }
        var unambiguousPalette = palette.GetUnambiguousPalette();

        if (s.IsWriting())
        {
            if (existing == null)
            {
                throw new ArgumentNullException(nameof(existing));
            }
            var encoder = new PngEncoder();
            PackedChunks.Pack(s, existing.Regions.Count, frameNum => Write(encoder, unambiguousPalette, existing, frameNum));
            return(existing);
        }

        // Read
        var decoder       = new PngDecoder();
        var configuration = new Configuration();
        var images        = new List <Image <Rgba32> >();

        try
        {
            foreach (var(bytes, _) in PackedChunks.Unpack(s))
            {
                using var stream = new MemoryStream(bytes);
                images.Add(decoder.Decode <Rgba32>(configuration, stream));
            }

            return(Read(info.AssetId, unambiguousPalette, images));
        }
        finally { foreach (var image in images)
                  {
                      image.Dispose();
                  }
        }
    }
Exemplo n.º 14
0
        public void Decode_IgnoresExifData_WhenIgnoreMetadataIsTrue <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            var decoder = new PngDecoder
            {
                IgnoreMetadata = true
            };

            using (Image <TPixel> image = provider.GetImage(decoder))
            {
                Assert.Null(image.Metadata.ExifProfile);
            }
        }
Exemplo n.º 15
0
        public void Decode_32bitTestImages(string path, int w, int h)
        {
            var d      = new PngDecoder();
            var pixels = d.Decode(File.ReadAllBytes(path));

            Assert.AreEqual(w, pixels.GetLength(0));
            Assert.AreEqual(h, pixels.GetLength(1));
            Assert.IsNotNull(pixels);
            var e             = new PngEncoder(new PngEncoderOptions());
            var encodedPixels = e.Encode(pixels);

            File.WriteAllBytes(Path.ChangeExtension(path, "out.png"), encodedPixels);
        }
Exemplo n.º 16
0
        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);
            }
        }
Exemplo n.º 17
0
        public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored()
        {
            var options = new PngDecoder()
            {
                IgnoreMetadata = true
            };

            var testFile = TestFile.Create(TestImages.Png.Blur);

            using (Image <Rgba32> image = testFile.CreateImage(options))
            {
                Assert.Equal(0, image.Metadata.Properties.Count);
            }
        }
Exemplo n.º 18
0
        public void Decode_ReadsExifData <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            var decoder = new PngDecoder
            {
                IgnoreMetadata = false
            };

            using (Image <TPixel> image = provider.GetImage(decoder))
            {
                Assert.NotNull(image.Metadata.ExifProfile);
                ExifProfile exif = image.Metadata.ExifProfile;
                VerifyExifDataIsPresent(exif);
            }
        }
Exemplo n.º 19
0
        public void Decode_IgnoreMetadataIsTrue_TextChunksAreIgnored()
        {
            var options = new PngDecoder
            {
                IgnoreMetadata = true
            };

            var testFile = TestFile.Create(TestImages.Png.PngWithMetadata);

            using (Image <Rgba32> image = testFile.CreateRgba32Image(options))
            {
                PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
                Assert.Equal(0, meta.TextData.Count);
            }
        }
Exemplo n.º 20
0
        public void Decode_TextEncodingSetToUnicode_TextIsReadWithCorrectEncoding()
        {
            var options = new PngDecoder()
            {
                TextEncoding = Encoding.Unicode
            };

            var testFile = TestFile.Create(TestImages.Png.Blur);

            using (Image <Rgba32> image = testFile.CreateImage(options))
            {
                Assert.Equal(1, image.Metadata.Properties.Count);
                Assert.Equal("潓瑦慷敲", image.Metadata.Properties[0].Name);
            }
        }
Exemplo n.º 21
0
        public void Decode_IgnoreMetadataIsFalse_TextChunckIsRead()
        {
            var options = new PngDecoder()
            {
                IgnoreMetadata = false
            };

            var testFile = TestFile.Create(TestImages.Png.Blur);

            using (Image <Rgba32> image = testFile.CreateImage(options))
            {
                Assert.Equal(1, image.Metadata.Properties.Count);
                Assert.Equal("Software", image.Metadata.Properties[0].Name);
                Assert.Equal("paint.net 4.0.6", image.Metadata.Properties[0].Value);
            }
        }
Exemplo n.º 22
0
        public IReadOnlyTexture <byte> Serdes(IReadOnlyTexture <byte> existing, AssetInfo info, AssetMapping mapping, ISerializer s, IJsonUtil jsonUtil)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            var paletteId = info.Get(AssetProperty.PaletteId, 0);
            var palette   = Resolve <IAssetManager>()
                            .LoadPalette(new PaletteId(AssetType.Palette, paletteId))
                            .GetUnambiguousPalette();

            if (info.AssetId.Type == AssetType.Font)
            {
                palette    = new uint[256];
                palette[1] = 0xffffffff;
                palette[2] = 0xffcccccc;
                palette[3] = 0xffaaaaaa;
                palette[4] = 0xff777777;
                palette[5] = 0xff555555;
            }

            if (s.IsWriting())
            {
                if (existing == null)
                {
                    throw new ArgumentNullException(nameof(existing));
                }
                var encoder = new PngEncoder();
                var bytes   = Write(encoder, palette, existing);
                s.Bytes(null, bytes, bytes.Length);
                return(existing);
            }
            else // Read
            {
                var decoder       = new PngDecoder();
                var configuration = new Configuration();
                var bytes         = s.Bytes(null, null, (int)s.BytesRemaining);
                using var stream = new MemoryStream(bytes);
                using var image  = decoder.Decode <Rgba32>(configuration, stream);
                return(Read(info.AssetId, palette, image, info.Width, info.Height));
            }
        }
Exemplo n.º 23
0
        private static byte[] ReprocessPngFile(byte[] png, ParseContext context, CommandLineOptions opts)
        {
            var tempFilePath = Path.Combine(Path.GetTempPath(), "IcoCrush" + Guid.NewGuid().ToString("N") + ".png");

            File.WriteAllBytes(tempFilePath, png);

            var tokens = opts.PngToolPath.Split(' ').ToList();
            var exe    = tokens[0];

            tokens.RemoveAt(0);
            tokens.Add(tempFilePath);

            var info = new ProcessStartInfo
            {
                FileName    = exe,
                Arguments   = string.Join(' ', tokens),
                WindowStyle = ProcessWindowStyle.Hidden,
            };

            System.Console.WriteLine(info.FileName);
            System.Console.WriteLine(info.Arguments);
            using (var process = Process.Start(info))
            {
                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    throw new Exception($"PNG process returned error code {process.ExitCode}.  Process: {info.FileName} {info.Arguments}");
                }
            }

            var result = File.ReadAllBytes(tempFilePath);

            File.Delete(tempFilePath);

            var outputEncoding = PngDecoder.GetPngFileEncoding(new Memory <byte>(result));

            if (outputEncoding.ColorType != PngColorType.RGBA)
            {
                System.Console.WriteLine($"Warning: After running the PNG through the external tool, the color type is: {outputEncoding.ColorType}.  ICO files require color type RGBA for embedded PNGs.");
            }
            else if (outputEncoding.BitsPerChannel != 8)
            {
                System.Console.WriteLine($"Warning: After running the PNG through the external tool, the color depth is: {outputEncoding.BitsPerChannel * 4}-bit.  ICO files require 32-bit color depth for embedded PNGs.");
            }

            return(result);
        }
Exemplo n.º 24
0
        private static void ReadPngFile(CommandLineOptions opts, ParseContext context, IcoFrame frame, byte[] sourceFile, out bool canSourceBePreserved)
        {
            using (var stream = new MemoryStream(sourceFile))
            {
                var decoder = new SixLabors.ImageSharp.Formats.Png.PngDecoder();
                frame.CookedData = decoder.Decode <Rgba32>(new Configuration(), stream);
            }

            var encoding = PngDecoder.GetPngFileEncoding(new Memory <byte>(sourceFile));

            frame.Encoding.Type = IcoEncodingType.Png;

            frame.Encoding.ClaimedBitDepth = 32;
            frame.Encoding.ActualBitDepth  = 32;

            canSourceBePreserved = encoding.ColorType == PngColorType.RGBA && encoding.BitsPerChannel == 8;
        }
Exemplo n.º 25
0
        [InlineData((uint)PngChunkType.End)]     // IEND
        public void Decode_IncorrectCRCForCriticalChunk_ExceptionIsThrown(uint chunkType)
        {
            string chunkName = GetChunkTypeName(chunkType);

            using (var memStream = new MemoryStream())
            {
                WriteHeaderChunk(memStream);
                WriteChunk(memStream, chunkName);
                WriteDataChunk(memStream);

                var decoder = new PngDecoder();

                ImageFormatException exception = Assert.Throws <ImageFormatException>(() => decoder.Decode <Rgb24>(null, memStream));

                Assert.Equal($"CRC Error. PNG {chunkName} chunk is corrupt!", exception.Message);
            }
        }
Exemplo n.º 26
0
        public static byte[] DecompressImage()
        {
            byte[] buffer = new byte[BufferSize];

            using (Stream stream = File.OpenRead(FileName))
            {
                for (int i = 0; i < N; i++)
                {
                    stream.Position = 0;
                    PngDecoder png = new PngDecoder(stream);
                    png.TransformSetBgr();
                    png.Decode(buffer);
                }
            }

            return(buffer);
        }
Exemplo n.º 27
0
        public void Encoder_PreservesTextData <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            var decoder = new PngDecoder();

            using (Image <TPixel> input = provider.GetImage(decoder))
                using (var memoryStream = new MemoryStream())
                {
                    input.Save(memoryStream, new PngEncoder());

                    memoryStream.Position = 0;
                    using (Image <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, memoryStream))
                    {
                        PngMetadata meta = image.Metadata.GetFormatMetadata(PngFormat.Instance);
                        VerifyTextDataIsPresent(meta);
                    }
                }
        }
Exemplo n.º 28
0
        public void InfersColorTypeAndBitDepth <TPixel>(TestImageProvider <TPixel> provider, PngColorType pngColorType, PngBitDepth pngBitDepth)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            using (Stream stream = new MemoryStream())
            {
                PngEncoder.Encode(provider.GetImage(), stream);

                stream.Seek(0, SeekOrigin.Begin);

                var decoder = new PngDecoder();

                Image image = decoder.Decode(Configuration.Default, stream);

                PngMetadata metadata = image.Metadata.GetPngMetadata();
                Assert.Equal(pngColorType, metadata.ColorType);
                Assert.Equal(pngBitDepth, metadata.BitDepth);
            }
        }
Exemplo n.º 29
0
        public static ImageResult FromStream(Stream stream, ColorComponents?requiredComponents = null,
                                             bool use8BitsPerChannel = true)
        {
            ImageResult result = null;

            if (JpgDecoder.Test(stream))
            {
                result = JpgDecoder.Decode(stream, requiredComponents);
            }
            else if (PngDecoder.Test(stream))
            {
                result = PngDecoder.Decode(stream, requiredComponents);
            }
            else if (BmpDecoder.Test(stream))
            {
                result = BmpDecoder.Decode(stream, requiredComponents);
            }
            else if (GifDecoder.Test(stream))
            {
                result = GifDecoder.Decode(stream, requiredComponents);
            }
            else if (PsdDecoder.Test(stream))
            {
                result = PsdDecoder.Decode(stream, requiredComponents);
            }
            else if (TgaDecoder.Test(stream))
            {
                result = TgaDecoder.Decode(stream, requiredComponents);
            }

            if (result == null)
            {
                Decoder.stbi__err("unknown image type");
            }

            if (use8BitsPerChannel && result.BitsPerChannel != 8)
            {
                result.Data = Conversion.stbi__convert_16_to_8(result.Data, result.Width, result.Height,
                                                               (int)result.ColorComponents);
            }

            return(result);
        }
Exemplo n.º 30
0
        public void Decode_IgnoreMetadataIsFalse_TextChunkIsRead()
        {
            var options = new PngDecoder
            {
                IgnoreMetadata = false
            };

            var testFile = TestFile.Create(TestImages.Png.Blur);

            using (Image <Rgba32> 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);
            }
        }
Exemplo n.º 31
0
        public void Decode_IncorrectCRCForCriticalChunk_ExceptionIsThrown(string chunkName)
        {
            using (var memStream = new MemoryStream())
            {
                memStream.Skip(8);

                WriteChunk(memStream, chunkName);

                CompressStream(memStream);

                var decoder = new PngDecoder();

                ImageFormatException exception = Assert.Throws <ImageFormatException>(() =>
                {
                    decoder.Decode <Rgb24>(null, memStream);
                });

                Assert.Equal($"CRC Error. PNG {chunkName} chunk is corrupt!", exception.Message);
            }
        }
Exemplo n.º 32
0
        public Rgba32[] GetPixelsFromBytes(byte[] imageArray, int height, int width)
        {
            Rgba32[]      tempPixels   = new Rgba32[height * width];
            IImageDecoder imageDecoder = new PngDecoder()
            {
                IgnoreMetadata = true
            };

            using (var image = Image.Load(imageArray, imageDecoder))
            {
                for (int x = 0; x < height; x++)
                {
                    for (int y = 0; y < width; y++)
                    {
                        tempPixels[x * width + y] = image[y, x];
                    }
                }
                return(tempPixels);
            }
        }