Beispiel #1
0
        internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation?orientation, out SKCodecOrigin origin)
        {
            if (!fileSystem.FileExists(path))
            {
                throw new FileNotFoundException("File not found", path);
            }

            var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);

            if (requiresTransparencyHack || forceCleanBitmap)
            {
                using (var stream = new SKFileStream(NormalizePath(path, fileSystem)))
                {
                    using (var codec = SKCodec.Create(stream))
                    {
                        if (codec == null)
                        {
                            origin = GetSKCodecOrigin(orientation);
                            return(null);
                        }

                        // create the bitmap
                        var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);

                        if (bitmap != null)
                        {
                            // decode
                            codec.GetPixels(bitmap.Info, bitmap.GetPixels());

                            origin = codec.Origin;
                        }
                        else
                        {
                            origin = GetSKCodecOrigin(orientation);
                        }

                        return(bitmap);
                    }
                }
            }

            var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));

            if (resultBitmap == null)
            {
                return(Decode(path, true, fileSystem, orientation, out origin));
            }

            // If we have to resize these they often end up distorted
            if (resultBitmap.ColorType == SKColorType.Gray8)
            {
                using (resultBitmap)
                {
                    return(Decode(path, true, fileSystem, orientation, out origin));
                }
            }

            origin = SKCodecOrigin.TopLeft;
            return(resultBitmap);
        }
Beispiel #2
0
        public void SpecialCharactersPath()
        {
            var stream = new SKFileStream(@"C:\Projects\SkiaSharp\tests\Content\images\上田jj雅美.jpg");

            Assert.NotNull(stream);
            Assert.True(stream.Length > 0);
        }
Beispiel #3
0
    public static int Main()
    {
        using SKFileStream skfs = new SKFileStream("mono.png");
        using SKImage img       = SKImage.FromEncodedData(skfs);

        Console.WriteLine($"Size: {skfs.Length} Height: {img.Height}, Width: {img.Width}");
        return(0);
    }
Beispiel #4
0
        protected override void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            string text = "\u03A3 and \u0750";

            canvas.Clear(SKColors.White);

            using (var paint = new SKPaint())
            {
                paint.IsAntialias = true;

                using (var tf = SKTypeface.FromFile(SampleMedia.Fonts.ContentFontPath))
                {
                    paint.Color    = SampleMedia.Colors.XamarinGreen;
                    paint.TextSize = 60;
                    paint.Typeface = tf;

                    canvas.DrawText(text, 50, 50, paint);
                }

                using (var fileStream = new SKFileStream(SampleMedia.Fonts.ContentFontPath))
                    using (var tf = SKTypeface.FromStream(fileStream))
                    {
                        paint.Color    = SampleMedia.Colors.XamarinDarkBlue;
                        paint.TextSize = 60;
                        paint.Typeface = tf;

                        canvas.DrawText(text, 50, 100, paint);
                    }

                using (var resource = SampleMedia.Fonts.EmbeddedFont)
                    using (var memory = new MemoryStream())
                    {
                        resource.CopyTo(memory);
                        var bytes = memory.ToArray();

                        using (var stream = new SKMemoryStream(bytes))
                            using (var tf = SKTypeface.FromStream(stream))
                            {
                                paint.Color    = SampleMedia.Colors.XamarinLightBlue;
                                paint.TextSize = 60;
                                paint.Typeface = tf;

                                canvas.DrawText(text, 50, 150, paint);
                            }
                    }

                using (var managedResource = SampleMedia.Fonts.EmbeddedFont)
                    using (var managedStream = new SKManagedStream(managedResource, true))
                        using (var tf = SKTypeface.FromStream(managedStream))
                        {
                            paint.Color    = SampleMedia.Colors.XamarinPurple;
                            paint.TextSize = 60;
                            paint.Typeface = tf;

                            canvas.DrawText(text, 50, 200, paint);
                        }
            }
        }
Beispiel #5
0
        public void DecodeImageScanlines()
        {
            var path        = Path.Combine(PathToImages, "CMYK.jpg");
            var imageHeight = 516;

            var fileData      = File.ReadAllBytes(path);
            var correctBitmap = SKBitmap.Decode(path);

            var stream = new SKFileStream(path);

            using (var codec = SKCodec.Create(stream))
            {
                var info = new SKImageInfo(codec.Info.Width, codec.Info.Height);
                using (var scanlineBitmap = new SKBitmap(info))
                {
                    scanlineBitmap.Erase(SKColors.Fuchsia);

                    var result = codec.StartScanlineDecode(info);
                    Assert.Equal(SKCodecResult.Success, result);

                    Assert.Equal(SKCodecScanlineOrder.TopDown, codec.ScanlineOrder);
                    Assert.Equal(0, codec.NextScanline);

                    // only decode every second line
                    for (int y = 0; y < info.Height; y += 2)
                    {
                        Assert.Equal(1, codec.GetScanlines(scanlineBitmap.GetAddress(0, y), 1, info.RowBytes));
                        Assert.Equal(y + 1, codec.NextScanline);
                        if (codec.SkipScanlines(1))
                        {
                            Assert.Equal(y + 2, codec.NextScanline);
                        }
                        else
                        {
                            Assert.Equal(imageHeight, codec.NextScanline);                             // reached the end
                        }
                    }

                    Assert.False(codec.SkipScanlines(1));
                    Assert.Equal(imageHeight, codec.NextScanline);

                    for (var x = 0; x < info.Width; x++)
                    {
                        for (var y = 0; y < info.Height; y++)
                        {
                            if (y % 2 == 0)
                            {
                                Assert.Equal(correctBitmap.GetPixel(x, y), scanlineBitmap.GetPixel(x, y));
                            }
                            else
                            {
                                Assert.Equal(SKColors.Fuchsia, scanlineBitmap.GetPixel(x, y));
                            }
                        }
                    }
                }
            }
        }
Beispiel #6
0
        public void FileStreamSelectCorrectStreamForASCIIPath()
        {
            var path = Path.Combine(PathToImages, "baboon.jpg");

            using (var stream = SKFileStream.OpenStream(path))
            {
                Assert.IsType <SKFileStream>(stream);
            }
        }
Beispiel #7
0
        public void CanGetPixels()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "baboon.png"));

            using (var codec = SKCodec.Create(stream)) {
                var pixels = codec.Pixels;
                Assert.Equal(codec.Info.BytesSize, pixels.Length);
            }
        }
Beispiel #8
0
        public void FileStreamSelectCorrectStreamForNonASCIIPath()
        {
            var path = Path.Combine(PathToImages, "上田雅美.jpg");

            using (var stream = SKFileStream.OpenStream(path))
            {
                Assert.IsType <SKFileStream>(stream);
                Assert.True(((SKFileStream)stream).IsValid);
            }
        }
Beispiel #9
0
        public ImageDimensions GetImageSize(string path)
        {
            using (var s = new SKFileStream(path))
                using (var codec = SKCodec.Create(s))
                {
                    var info = codec.Info;

                    return(new ImageDimensions(info.Width, info.Height));
                }
        }
Beispiel #10
0
        public void DataCanBeCreatedFromStream()
        {
            using var stream = new SKFileStream(Path.Combine(PathToImages, "baboon.jpg"));
            Assert.True(stream.IsValid);

            using var data = SKData.Create(stream);

            Assert.NotNull(data);
            Assert.True(data.Size > 0);
        }
Beispiel #11
0
        public void GetEncodedInfo()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "color-wheel.png"));

            using (var codec = SKCodec.Create(stream)) {
                Assert.Equal(SKEncodedInfoColor.Rgba, codec.EncodedInfo.Color);
                Assert.Equal(SKEncodedInfoAlpha.Unpremul, codec.EncodedInfo.Alpha);
                Assert.Equal(8, codec.EncodedInfo.BitsPerComponent);
            }
        }
Beispiel #12
0
        public void StringIsMarshaledCorrectly()
        {
            var filename = Path.GetTempFileName();

            bitmap.Save(filename, ImageFormat.Png);

            var    filestream = new SKFileStream(filename);
            var    decoder    = new SKImageDecoder(filestream);
            string format1    = decoder.FormatName;
        }
Beispiel #13
0
        public void GetEncodedInfo()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "color-wheel.png"));

            using (var codec = SKCodec.Create(stream)) {
                Assert.Equal(SKImageInfo.PlatformColorType, codec.Info.ColorType);
                Assert.Equal(SKAlphaType.Unpremul, codec.Info.AlphaType);
                Assert.Equal(32, codec.Info.BitsPerPixel);
            }
        }
Beispiel #14
0
        internal static SKBitmap Decode(string path, bool forceCleanBitmap, out SKCodecOrigin origin)
        {
            var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);

            if (requiresTransparencyHack || forceCleanBitmap)
            {
                using (var stream = new SKFileStream(path))
                {
                    using (var codec = SKCodec.Create(stream))
                    {
                        if (codec == null)
                        {
                            origin = SKCodecOrigin.TopLeft;
                            return(null);
                        }

                        // create the bitmap
                        var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);

                        if (bitmap != null)
                        {
                            // decode
                            codec.GetPixels(bitmap.Info, bitmap.GetPixels());

                            origin = codec.Origin;
                        }
                        else
                        {
                            origin = SKCodecOrigin.TopLeft;
                        }

                        return(bitmap);
                    }
                }
            }

            var resultBitmap = SKBitmap.Decode(path);

            if (resultBitmap == null)
            {
                return(Decode(path, true, out origin));
            }

            // If we have to resize these they often end up distorted
            if (resultBitmap.ColorType == SKColorType.Gray8)
            {
                using (resultBitmap)
                {
                    return(Decode(path, true, out origin));
                }
            }

            origin = SKCodecOrigin.TopLeft;
            return(resultBitmap);
        }
Beispiel #15
0
        public void SupportsNonASCIICharactersInPath()
        {
            var path = Path.Combine(PathToImages, "上田雅美.jpg");

            using (var stream = new SKFileStream(path))
            {
                Assert.NotNull(stream);
                Assert.True(stream.Length > 0);
                Assert.True(stream.IsValid);
            }
        }
Beispiel #16
0
        public void FileStreamForMissingFile()
        {
            var path = Path.Combine(PathToImages, "missing-image.png");

            Assert.Null(SKFileStream.OpenStream(path));

            var stream = new SKFileStream(path);

            Assert.Equal(0, stream.Length);
            Assert.False(stream.IsValid);
        }
Beispiel #17
0
        public void GetGifFrames()
        {
            const int FrameCount = 16;

            var stream = new SKFileStream(Path.Combine(PathToImages, "animated-heart.gif"));

            using (var codec = SKCodec.Create(stream))
            {
                Assert.Equal(-1, codec.RepetitionCount);

                var frameInfos = codec.FrameInfo;
                Assert.Equal(FrameCount, frameInfos.Length);

                Assert.Equal(-1, frameInfos[0].RequiredFrame);

                var cachedFrames = new SKBitmap[FrameCount];
                var info         = new SKImageInfo(codec.Info.Width, codec.Info.Height);

                var decode = new Action <SKBitmap, int, int>((bm, cachedIndex, index) =>
                {
                    var decodeInfo = info;
                    if (index > 0)
                    {
                        decodeInfo = info.WithAlphaType(frameInfos[index].AlphaType);
                    }
                    Assert.True(bm.TryAllocPixels(decodeInfo));
                    if (cachedIndex != -1)
                    {
                        Assert.True(cachedFrames[cachedIndex].CopyTo(bm));
                    }
                    var opts   = new SKCodecOptions(index, cachedIndex);
                    var result = codec.GetPixels(decodeInfo, bm.GetPixels(), opts);
                    if (cachedIndex != -1 && frameInfos[cachedIndex].DisposalMethod == SKCodecAnimationDisposalMethod.RestorePrevious)
                    {
                        Assert.Equal(SKCodecResult.InvalidParameters, result);
                    }
                    Assert.Equal(SKCodecResult.Success, result);
                });

                for (var i = 0; i < FrameCount; i++)
                {
                    var cachedFrame = cachedFrames[i] = new SKBitmap();
                    decode(cachedFrame, -1, i);

                    var uncachedFrame = new SKBitmap();
                    decode(uncachedFrame, frameInfos[i].RequiredFrame, i);

                    var cachedBytes   = cachedFrame.Bytes;
                    var uncachedBytes = uncachedFrame.Bytes;
                    Assert.Equal(cachedBytes, uncachedBytes);
                }
            }
        }
Beispiel #18
0
        public void CanCreateStreamCodec()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "color-wheel.png"));

            using (var codec = SKCodec.Create(stream)) {
                Assert.Equal(SKEncodedFormat.Png, codec.EncodedFormat);
                Assert.Equal(128, codec.Info.Width);
                Assert.Equal(128, codec.Info.Height);
                Assert.Equal(SKAlphaType.Unpremul, codec.Info.AlphaType);
                Assert.Equal(SKImageInfo.PlatformColorType, codec.Info.ColorType);
            }
        }
Beispiel #19
0
        public ImageSize GetImageSize(string path)
        {
            using (var s = new SKFileStream(path))
                using (var codec = SKCodec.Create(s))
                {
                    var info = codec.Info;

                    return(new ImageSize
                    {
                        Width = info.Width,
                        Height = info.Height
                    });
                }
        }
Beispiel #20
0
        public void GetSingleGifFrame()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "animated-heart.gif"));

            using (var codec = SKCodec.Create(stream))
            {
                var frameInfos = codec.FrameInfo;
                for (var i = 0; i < frameInfos.Length; i++)
                {
                    Assert.True(codec.GetFrameInfo(i, out var info));
                    Assert.Equal(frameInfos[i], info);
                }
            }
        }
Beispiel #21
0
        public ImageDimensions GetImageSize(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("File not found", path);
            }

            using (var s = new SKFileStream(path))
                using (var codec = SKCodec.Create(s))
                {
                    var info = codec.Info;

                    return(new ImageDimensions(info.Width, info.Height));
                }
        }
Beispiel #22
0
        private async void LoadSkBitmap()
        {
            var path      = ContentImg;
            var newBitmap = await Task.Run(() =>
            {
                using (var stream = new SKFileStream(path))
                {
                    return(SKBitmap.Decode(stream));
                }
            });

            _contentBitmap?.Dispose();
            _contentBitmap = newBitmap;
            InvalidateSurface();
        }
Beispiel #23
0
        public void CanCreateStreamCodecWithResult()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "color-wheel.png"));

            Assert.True(stream.IsValid);

            using var codec = SKCodec.Create(stream, out var result);

            Assert.Equal(SKCodecResult.Success, result);
            Assert.Equal(SKEncodedImageFormat.Png, codec.EncodedFormat);
            Assert.Equal(128, codec.Info.Width);
            Assert.Equal(128, codec.Info.Height);
            Assert.Equal(SKAlphaType.Unpremul, codec.Info.AlphaType);
            Assert.Equal(SKImageInfo.PlatformColorType, codec.Info.ColorType);
        }
Beispiel #24
0
        public void FileStreamSelectCorrectStreamForNonASCIIPath()
        {
            var path = Path.Combine(PathToImages, "上田雅美.jpg");

            using (var stream = SKFileStream.OpenStream(path))
            {
                if (IsWindows)
                {
                    Assert.IsType <SKManagedStream>(stream);
                }
                else
                {
                    Assert.IsType <SKFileStream>(stream);
                }
            }
        }
Beispiel #25
0
        protected ImageData GetImage(string path)
        {
            using (var stream = new SKFileStream(path))
                using (var bitmap = SKBitmap.Decode(stream))
                {
                    ConvertBitmapIfNecessary(bitmap);

                    return(new ImageData
                    {
                        Path = path,
                        Width = bitmap.Width,
                        Height = bitmap.Height,
                        Pixels = bitmap.Bytes,
                        Format = ConvertToFormat(bitmap.ColorType)
                    });
                }
        }
Beispiel #26
0
        public void Load(string imgFileName, Enums.ImageLoadMode loadMode = Enums.ImageLoadMode.Full)
        {
            Task.Factory.StartNew(() =>
            {
                Path = imgFileName;
                switch (loadMode)
                {
                case Enums.ImageLoadMode.Full:
                    Bitmap = new Bitmap(imgFileName);
                    Width  = Bitmap.PixelSize.Width;
                    Height = Bitmap.PixelSize.Height;
                    break;

                case Enums.ImageLoadMode.Miniature:
                    using (var stream = new SKFileStream(imgFileName))
                        using (var src = SKBitmap.Decode(stream))
                        {
                            Width       = src.Width;
                            Height      = src.Height;
                            var scale   = 100f / src.Width;
                            var resized = new SKBitmap(
                                (int)(src.Width * scale),
                                (int)(src.Height * scale),
                                src.ColorType,
                                src.AlphaType);
                            src.ScalePixels(resized, SKFilterQuality.Low);
                            Bitmap = new Bitmap(
                                resized.ColorType.ToPixelFormat(),
                                resized.GetPixels(),
                                new PixelSize(resized.Width, resized.Height),
                                SkiaPlatform.DefaultDpi,
                                resized.RowBytes);
                        }
                    break;

                default:
                    throw new Exception($"invalid ImageLoadMode:{loadMode.ToString()}");
                }
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    ImageBrush.Source = Bitmap;
                    OnLoad?.Invoke();
                });
            });
        }
Beispiel #27
0
        public void SupportsNonASCIICharactersInPath()
        {
            var path = Path.Combine(PathToImages, "上田雅美.jpg");

            using (var stream = new SKFileStream(path))
            {
                if (IsWindows)
                {
                    Assert.Equal(0, stream.Length);

                    throw new SkipException("Windows does not support non-ASCII characters: https://github.com/mono/SkiaSharp/issues/390");
                }
                else
                {
                    Assert.NotNull(stream);
                    Assert.True(stream.Length > 0);
                }
            }
        }
Beispiel #28
0
        public void CanCreateStreamCodec()
        {
            var stream = new SKFileStream(Path.Combine(PathToImages, "color-wheel.png"));

            using (var codec = SKCodec.Create(stream)) {
                Assert.AreEqual(SKEncodedFormat.Png, codec.EncodedFormat);
                Assert.AreEqual(128, codec.Info.Width);
                Assert.AreEqual(128, codec.Info.Height);
                Assert.AreEqual(SKAlphaType.Unpremul, codec.Info.AlphaType);
                if (IsUnix)
                {
                    Assert.AreEqual(SKColorType.Rgba8888, codec.Info.ColorType);
                }
                else
                {
                    Assert.AreEqual(SKColorType.Bgra8888, codec.Info.ColorType);
                }
            }
        }
Beispiel #29
0
        public void GetGifFrames()
        {
            const int FrameCount = 16;

            var stream = new SKFileStream(Path.Combine(PathToImages, "animated-heart.gif"));

            using (var codec = SKCodec.Create(stream)) {
                Assert.Equal(-1, codec.RepetitionCount);

                var frameInfos = codec.FrameInfo;
                Assert.Equal(FrameCount, frameInfos.Length);

                Assert.Equal(-1, frameInfos [0].RequiredFrame);

                var cachedFrames = new SKBitmap [FrameCount];
                var info         = new SKImageInfo(codec.Info.Width, codec.Info.Height);

                var decode = new Action <SKBitmap, bool, int> ((bm, cached, index) => {
                    if (cached)
                    {
                        var requiredFrame = frameInfos [index].RequiredFrame;
                        if (requiredFrame != -1)
                        {
                            Assert.True(cachedFrames [requiredFrame].CopyTo(bm));
                        }
                    }
                    var opts   = new SKCodecOptions(index, cached);
                    var result = codec.GetPixels(info, bm.GetPixels(), opts);
                    Assert.Equal(SKCodecResult.Success, result);
                });

                for (var i = 0; i < FrameCount; i++)
                {
                    var cachedFrame = cachedFrames [i] = new SKBitmap(info);
                    decode(cachedFrame, true, i);

                    var uncachedFrame = new SKBitmap(info);
                    decode(uncachedFrame, false, i);

                    Assert.Equal(cachedFrame.Bytes, uncachedFrame.Bytes);
                }
            }
        }
Beispiel #30
0
        public void GarbageCollectionCollectsStreams()
        {
            VerifyImmediateFinalizers();

            var path = Path.Combine(PathToImages, "baboon.jpg");

            var weak = DoWork();

            CollectGarbage();

            Assert.False(weak.IsAlive);
            Assert.Null(weak.Target);

            WeakReference DoWork()
            {
                var stream = new SKFileStream(path);

                return(new WeakReference(stream));
            }
        }