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); } }
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)); } } }
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))); }
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))); }
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")); } } }
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); }
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); }
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(); } } }
[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); } }
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 <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, stream)) { ImageMetadata meta = image.Metadata; Assert.Equal(xResolution, meta.HorizontalResolution); Assert.Equal(yResolution, meta.VerticalResolution); Assert.Equal(resolutionUnit, meta.ResolutionUnits); } } }
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)); } }
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); }
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); } } }
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); } }
[InlineData((uint)PngChunkType.Palette)] // PLTE /* [InlineData(PngChunkTypes.Data)] TODO: Figure out how to test this */ 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); } }
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); }
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); } }
public override void LoadFileDialog(FolderLocations folderLocation, int maxWidth, int maxHeight, int x, int y, int width, int height, string[] fileTypes, StreamLoadedCallbackMethod streamLoadedCallback) { if (streamLoadedCallback == null) { return; } string filename = EditorUtility.OpenFilePanel("Load file", "", generateFilterValue(fileTypes)); if (!string.IsNullOrEmpty(filename)) { if (maxWidth == 0 || maxHeight == 0 || folderLocation != FolderLocations.Pictures) { streamLoadedCallback(new FileStream(filename, FileMode.Open, FileAccess.Read), true); } else { var newStream = new MemoryStream(); try { using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { IImageDecoder decoder = null; switch (Path.GetExtension(filename).ToLower()) { case ".jpg": decoder = new JpegDecoder(); break; case ".jpeg": decoder = new JpegDecoder(); break; case ".png": decoder = new PngDecoder(); break; default: Debug.LogError("Unsuported file ext type: " + Path.GetExtension(filename)); streamLoadedCallback(null, false); return; } var image = new ExtendedImage(); decoder.Decode(image, stream); var newSize = MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight); var newImage = ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new NearestNeighborResizer()); var encoder = new PngEncoder(); encoder.Encode(newImage, newStream); newStream.Position = 0; } } catch (Exception e) { newStream.Dispose(); newStream = null; Debug.LogError(e.Message); } finally { streamLoadedCallback(newStream, true); } } } else { streamLoadedCallback(null, false); } }
public override Image Load(Stream s) { PngDecoder p = new PngDecoder(); return(p.Decode(s)); }