コード例 #1
0
        public unsafe void DataOutLivesImageUntilFinalizersRun()
        {
            var released = false;

            var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "baboon.jpg"));
            var gch   = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            var dataHandle = DoWork();

            Assert.Equal(1, dataHandle.GetReferenceCount(false));
            Assert.False(released, "Data was disposed too soon.");

            CollectGarbage();

            Assert.True(released, "Data was not disposed.");

            gch.Free();

            IntPtr DoWork()
            {
                var input  = SKData.Create(gch.AddrOfPinnedObject(), bytes.Length, (_, __) => released = true);
                var handle = input.Handle;

                var img = SKImage.FromEncodedData(input);

                Assert.Equal(3, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                img.Dispose();
                Assert.Equal(1, handle.GetReferenceCount(false));
                Assert.False(released, "Data was disposed too soon.");

                return(handle);
            }
        }
コード例 #2
0
        /// <summary>
        /// Creates a bitmap of the graph.
        /// </summary>
        /// <param name="Settings">Graph settings.</param>
        /// <param name="States">State object(s) that contain graph-specific information about its inner states.
        /// These can be used in calls back to the graph object to make actions on the generated graph.</param>
        /// <returns>Bitmap</returns>
        public override SKImage CreateBitmap(GraphSettings Settings, out object[] States)
        {
            SKImageInfo ImageInfo = new SKImageInfo(this.bitmap.Width, this.bitmap.Height, SKColorType.Bgra8888);
            int         c         = ImageInfo.BytesSize;

            States = new object[0];

            IntPtr Pixels = Marshal.AllocCoTaskMem(c);

            try
            {
                this.bitmap.ReadPixels(ImageInfo, Pixels, ImageInfo.RowBytes, 0, 0);

                using (SKData Data = SKData.Create(Pixels, c))
                {
                    SKImage Result = SKImage.FromPixels(new SKImageInfo(ImageInfo.Width, ImageInfo.Height, SKColorType.Bgra8888), Data, ImageInfo.RowBytes);
                    Pixels = IntPtr.Zero;

                    return(Result);
                }
            }
            finally
            {
                if (Pixels != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(Pixels);
                }
            }
        }
コード例 #3
0
        public unsafe void ReleaseDataWasInvokedOnlyAfterTheTypefaceWasFinished()
        {
            if (IsMac)
            {
                throw new SkipException("macOS does not release the data when the typeface is disposed.");
            }

            var path  = Path.Combine(PathToFonts, "Distortable.ttf");
            var bytes = File.ReadAllBytes(path);

            var released = false;

            fixed(byte *b = bytes)
            {
                var data = SKData.Create((IntPtr)b, bytes.Length, (addr, ctx) => released = true);

                var typeface = SKTypeface.FromData(data);

                Assert.Equal("Distortable", typeface.FamilyName);

                data.Dispose();
                Assert.False(released, "The SKDataReleaseDelegate was called too soon.");

                typeface.Dispose();
                Assert.True(released, "The SKDataReleaseDelegate was not called at all.");
            }
        }
コード例 #4
0
        public unsafe bool Register(ResourceFile file, out string familyName)
        {
            if (file.IsNone)
            {
                throw new ArgumentException("file is none.", nameof(file));
            }
            using var stream = file.GetStream();

            SKTypeface tf;

            if (stream.CanSeek && stream.Length <= int.MaxValue)
            {
                var size = (int)stream.Length;
                using var data = SKData.Create(size);
                stream.Read(new Span <byte>((void *)data.Data, size));
                tf = SKTypeface.FromData(data, 0);
            }
            else
            {
                using var data = SKData.Create(stream);
                tf             = SKTypeface.FromData(data, 0);
            }
            familyName = tf.FamilyName;
            return(_dic.TryAdd(tf.FamilyName, tf));
        }
コード例 #5
0
ファイル: QR.cs プロジェクト: wflorescisternas/XamarinApp
        public static byte[] GenerateCodePng(string Text, int Width, int Height)
        {
            BarcodeWriterPixelData Writer = new BarcodeWriterPixelData()
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions()
                {
                    Width  = Width,
                    Height = Height
                }
            };

            PixelData QrCode = Writer.Write(Text);

            Width  = QrCode.Width;
            Height = QrCode.Height;

            int Size = Width * Height << 2;

            using (SKData Data = SKData.Create(Size))
            {
                Marshal.Copy(QrCode.Pixels, 0, Data.Data, Size);

                using (SKImage Result = SKImage.FromPixels(new SKImageInfo(Width, Height, SKColorType.Bgra8888), Data, Width << 2))
                {
                    using (SKData Encoded = Result.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        return(Encoded.ToArray());
                    }
                }
            }
        }
コード例 #6
0
        public void EmptyAndZeroLengthSameObject()
        {
            var empty = SKData.Empty;
            var zero  = SKData.Create(0);

            Assert.Same(empty, zero);
        }
コード例 #7
0
        public void DataCanBeCreatedFromNonASCIIFile()
        {
            var data = SKData.Create(Path.Combine(PathToImages, "上田雅美.jpg"));

            Assert.NotNull(data);
            Assert.True(data.Size > 0);
        }
コード例 #8
0
        public unsafe void EncodeReturnTheSameInstanceIfItWasUsedToConstruct()
        {
            var released = false;

            var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "baboon.jpg"));

            fixed(byte *b = bytes)
            {
                var input = SKData.Create((IntPtr)b, bytes.Length, (_, __) => released = true);
                var image = SKImage.FromEncodedData(input);

                var result = image.Encode();

                Assert.Same(input, result);
                Assert.Equal(3, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                image.Dispose();
                Assert.Equal(1, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                input.Dispose();
                Assert.True(released, "Data was not disposed.");
            }
        }
コード例 #9
0
        public unsafe void DataInstanceIsCorrectlyDisposedWhenPassed()
        {
            var released = false;

            var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "baboon.jpg"));

            fixed(byte *b = bytes)
            {
                var input = SKData.Create((IntPtr)b, bytes.Length, (_, __) => released = true);

                Assert.Equal(1, input.GetReferenceCount());

                var image = SKImage.FromEncodedData(input);

                Assert.Equal(3, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                image.Dispose();
                Assert.Equal(1, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                input.Dispose();
                Assert.True(released, "Data was not disposed.");
            }
        }
コード例 #10
0
ファイル: SkImageCodec.cs プロジェクト: sahwar/DjvuNet
        public T Decode(Stream stream, ImageCodecSettings settings = null)
        {
            using (SKData data = SKData.Create(stream))
            {
                SKCodec     codec   = SKCodec.Create(data);
                var         format  = codec.EncodedFormat;
                var         info    = codec.Info;
                SKImageInfo decInfo = new SKImageInfo
                {
                    ColorType = info.ColorType,
                    Height    = info.Height,
                    Width     = info.Width
                };
                byte[]   buffer = new byte[info.Width * info.Height * 4];
                GCHandle hData  = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                var      result = codec.GetPixels(decInfo, hData.AddrOfPinnedObject());
                if (hData.IsAllocated)
                {
                    hData.Free();
                }

                IPixelMap pixMap = new PixelMap();
                return((T)pixMap);
            }
        }
コード例 #11
0
        public async Task EnsureMultithreadingDoesNotThrow(int iterations)
        {
            var imagePath = Path.Combine(PathToImages, "baboon.jpg");

            var tasks = new Task[iterations];

            for (var i = 0; i < iterations; i++)
            {
                var task = new Task(() =>
                {
                    using (var stream = File.OpenRead(imagePath))
                        using (var data = SKData.Create(stream))
                            using (var codec = SKCodec.Create(data))
                            {
                                var info = new SKImageInfo(codec.Info.Width, codec.Info.Height);
                                using (var image = SKBitmap.Decode(codec, info))
                                {
                                    var img = new byte[image.Height, image.Width];
                                }
                            }
                });

                tasks[i] = task;
                task.Start();
            }

            await Task.WhenAll(tasks);
        }
コード例 #12
0
        public void DecodingWithDataAndDrawingOnGPUCreatesCorrectImage()
        {
            var info = new SKImageInfo(120, 120);
            var path = Path.Combine(PathToImages, "vimeo_icon_dark.png");

            using (var ctx = CreateGlContext())
            {
                ctx.MakeCurrent();

                using (var grContext = GRContext.CreateGl())
                    using (var surface = SKSurface.Create(grContext, true, info))
                    {
                        var canvas = surface.Canvas;

                        canvas.Clear(SKColors.Crimson);

                        using (var data = SKData.Create(path))
                            using (var image = SKImage.FromEncodedData(data))
                            {
                                canvas.DrawImage(image, 0, 0);
                            }

                        using (var bmp = new SKBitmap(info))
                        {
                            surface.ReadPixels(info, bmp.GetPixels(), info.RowBytes, 0, 0);

                            Assert.Equal(SKColors.Crimson, bmp.GetPixel(3, 3));
                            Assert.Equal(SKColors.Crimson, bmp.GetPixel(70, 50));
                            Assert.Equal(new SKColor(23, 35, 34), bmp.GetPixel(40, 40));
                        }
                    }
            }
        }
コード例 #13
0
        public static bool CompareBitmaps(Stream?bitmapStream1, Stream?bitmapStream2, int allowedColorDistance = 0, double proportionCorrect = 1)
        {
            // The bitmaps in WPF can slightly differ from test to test. No idea why. So introduced proportion correct.

            long trueCount  = 0;
            long falseCount = 0;

            if (bitmapStream1 == null && bitmapStream2 == null)
            {
                return(true);
            }

            if (bitmapStream1 == null || bitmapStream2 == null)
            {
                return(false);
            }

            bitmapStream1.Position = 0;
            bitmapStream2.Position = 0;

            using var skData1 = SKData.Create(bitmapStream1);
            var bitmap1 = SKBitmap.FromImage(SKImage.FromEncodedData(skData1));

            using var skData2 = SKData.Create(bitmapStream2);
            var bitmap2 = SKBitmap.FromImage(SKImage.FromEncodedData(skData2));

            if (bitmap1.Width != bitmap2.Width || bitmap1.Height != bitmap2.Height)
            {
                return(false);
            }

            for (var x = 0; x < bitmap1.Width; x++)
            {
                for (var y = 0; y < bitmap1.Height; y++)
                {
                    var color1 = bitmap1.GetPixel(x, y);
                    var color2 = bitmap2.GetPixel(x, y);
                    if (color1 == color2)
                    {
                        trueCount++;
                    }
                    else
                    {
                        if (CompareColors(color1, color2, allowedColorDistance))
                        {
                            trueCount++;
                        }
                        else
                        {
                            falseCount++;
                        }
                    }
                }
            }

            var proportion = (double)(trueCount) / (trueCount + falseCount);

            return(proportionCorrect <= proportion);
        }
コード例 #14
0
        /// <summary>
        /// Encode image to stream.
        /// </summary>
        /// <param name="image">Image to be encoded.</param>
        /// <param name="stream">Stream to which to encode.</param>
        public void Encode(Image image, Stream stream)
        {
            var data = SKData.Create(image.ImageData, image.Size);
            var img  = SKImage.FromPixelData(SKImageInfo.Empty, data, image.Stride);
            var jpeg = img.Encode(SKEncodedImageFormat.Jpeg, this.QualityLevel);

            jpeg.SaveTo(stream);
        }
コード例 #15
0
ファイル: SKDataTest.cs プロジェクト: ywscr/SkiaSharp
        public void CanCreateFromNonSeekable()
        {
            using var stream      = File.OpenRead(Path.Combine(PathToImages, "baboon.png"));
            using var nonSeekable = new NonSeekableReadOnlyStream(stream);
            using var data        = SKData.Create(nonSeekable);

            Assert.NotNull(data);
        }
コード例 #16
0
ファイル: PngBitmapEncoder.cs プロジェクト: xiangzhi/psi
        /// <summary>
        /// Encode image to stream.
        /// </summary>
        /// <param name="image">Image to be encoded.</param>
        /// <param name="stream">Stream to which to encode.</param>
        public void Encode(Image image, Stream stream)
        {
            var data = SKData.Create(image.ImageData, image.Size);
            var img  = SKImage.FromPixelData(SKImageInfo.Empty, data, image.Stride);
            var png  = img.Encode(SKEncodedImageFormat.Png, 100);

            png.SaveTo(stream);
        }
コード例 #17
0
        public unsafe void FromDataReturnsDifferentObject()
        {
            using var data = SKData.Create(Path.Combine(PathToFonts, "Roboto2-Regular_NoEmbed.ttf"));

            using var tf1 = SKTypeface.FromData(data);
            using var tf2 = SKTypeface.FromData(data);

            Assert.NotSame(tf1, tf2);
        }
コード例 #18
0
        public void ToRasterImageReturnsSameRaster()
        {
            using var data  = SKData.Create(Path.Combine(PathToImages, "baboon.jpg"));
            using var image = SKImage.FromEncodedData(data);

            Assert.True(image.IsLazyGenerated);
            Assert.Null(image.PeekPixels());
            Assert.Equal(image, image.ToRasterImage());
        }
コード例 #19
0
        public void DataCanBeCreatedFromManagedStream()
        {
            using var managed = File.OpenRead(Path.Combine(PathToImages, "baboon.jpg"));
            using var stream  = new SKManagedStream(managed);
            using var data    = SKData.Create(stream);

            Assert.NotNull(data);
            Assert.True(data.Size > 0);
        }
コード例 #20
0
        public unsafe void DataCanBeResurrectedFromImage()
        {
            var released = false;

            var bytes = File.ReadAllBytes(Path.Combine(PathToImages, "baboon.jpg"));
            var gch   = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            using (var image = DoWork(out var dataHandle))
            {
                Assert.Equal(2, dataHandle.GetReferenceCount(false));
                Assert.False(released, "Data was disposed too soon.");

                ResurrectData(image);
            }

            Assert.True(released, "Data was not disposed.");

            gch.Free();

            SKImage DoWork(out IntPtr handle)
            {
                var input = SKData.Create(gch.AddrOfPinnedObject(), bytes.Length, (_, __) => released = true);

                handle = input.Handle;

                var img = SKImage.FromEncodedData(input);

                Assert.Equal(3, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                var result = img.Encode();

                Assert.Same(input, result);
                Assert.Equal(3, input.GetReferenceCount());
                Assert.False(released, "Data was disposed too soon.");

                result.Dispose();
                Assert.Equal(2, handle.GetReferenceCount(false));
                Assert.False(released, "Data was disposed too soon.");

                return(img);
            }

            void ResurrectData(SKImage img)
            {
                var encoded = img.EncodedData;

                Assert.NotNull(encoded);
                Assert.Equal(3, encoded.GetReferenceCount());

                var handle = encoded.Handle;

                encoded.Dispose();
                Assert.Equal(2, handle.GetReferenceCount(false));
                Assert.False(released, "Data was disposed too soon.");
            }
        }
コード例 #21
0
        /// <summary>
        /// Converts a base64 string to a SKImage, using minimal suppression via JPEG conversion
        /// <param name="base64">The base64 string being converted.</param>
        /// </summary>
        public static SKImage Base64ToSKImage(string base64)
        {
            var data   = Convert.FromBase64String(base64);
            var stream = new MemoryStream(data);
            var skData = SKData.Create(stream);

            stream.Dispose();
            return(SKImage.FromEncodedData(skData));
        }
コード例 #22
0
ファイル: BlurFace.cs プロジェクト: sugarik/PhotoCoreSite
        public BlurFace(string file, int retryAttempts, int nextRetryDelay, List <RestrictedFaceArea> hiddenRects, int jpegQuality)
        {
            dtStart = DateTime.Now;
            if (retryAttempts < 1)
            {
                retryAttempts = 1;
            }
            if (nextRetryDelay < 100)
            {
                nextRetryDelay = 100;
            }
            if (String.IsNullOrEmpty(file))
            {
                bytes = null;
            }
            else
            {
                bytes = null;

                if (File.Exists(file))
                {
                    bool       fileIsReady = false;
                    FileStream fileStream  = null;
                    try
                    {
                        do
                        {
                            try { fileStream = File.OpenRead(file); fileIsReady = true; }
                            catch (IOException exc) { Console.WriteLine("Ooops"); }
                            retryAttempts--;
                            if (!fileIsReady)
                            {
                                Thread.Sleep(nextRetryDelay);
                            }
                        }while (!fileIsReady && retryAttempts > 0);

                        if (fileStream != null)
                        {
                            fileStream.Position = 0;
                            using (SKData data = SKData.Create(fileStream))
                                using (SKImage image = SKImage.FromEncodedData(data))
                                {
                                    if (image != null)
                                    {
                                        Process(image, hiddenRects, jpegQuality);
                                    }
                                }
                        }
                    }
                    catch (Exception exc)
                    {
                    }
                    fileStream = null;
                }
            }
        }
コード例 #23
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);
        }
コード例 #24
0
        public unsafe void FromDataReturnsDifferentObject()
        {
            var fonts = SKFontManager.Default;

            using var data = SKData.Create(Path.Combine(PathToFonts, "Roboto2-Regular_NoEmbed.ttf"));

            using var tf1 = fonts.CreateTypeface(data);
            using var tf2 = fonts.CreateTypeface(data);

            Assert.NotSame(tf1, tf2);
        }
コード例 #25
0
        public static SKImage ConvertPixelsToImage(byte[] data, int width, int height)
        {
            SKImage img;

            using (var ms = new MemoryStream(data)) {
                SKImageInfo ii     = new SKImageInfo(width, height);
                SKData      sKData = SKData.Create(ms);
                img = SKImage.FromPixels(ii, sKData);
            }
            return(img);
        }
コード例 #26
0
        public void IccToXyzIsCorrect()
        {
            var path = Path.Combine(PathToImages, "AdobeRGB1998.icc");

            using var data = SKData.Create(path);

            using var icc = SKColorSpaceIccProfile.Create(data);
            var xyz = icc.ToColorSpaceXyz();

            Assert.Equal(SKColorSpaceXyz.AdobeRgb, xyz);
        }
コード例 #27
0
        public void TestLazyImage()
        {
            var data = SKData.Create(Path.Combine(PathToImages, "baboon.jpg"));

            Assert.NotNull(data);

            var image = SKImage.FromEncodedData(data);

            Assert.NotNull(image);

            Assert.True(image.IsLazyGenerated);
        }
コード例 #28
0
        public void NoDelegateDataCanBeCreated()
        {
            var memory = Marshal.AllocCoTaskMem(10);

            using (var data = SKData.Create(memory, 10))
            {
                Assert.Equal(memory, data.Data);
                Assert.Equal(10, data.Size);
            }

            Marshal.FreeCoTaskMem(memory);
        }
コード例 #29
0
        public void IccCanBeConstructedFromData()
        {
            var path = Path.Combine(PathToImages, "AdobeRGB1998.icc");

            using var data = SKData.Create(path);

            using var icc = SKColorSpaceIccProfile.Create(data);

            Assert.NotNull(icc);
            Assert.NotEqual(IntPtr.Zero, icc.Buffer);
            Assert.Equal(data.Size, icc.Size);
        }
コード例 #30
0
ファイル: SKCodecTest.cs プロジェクト: rookiejava/SkiaSharp
        public void CanDecodeData(string image)
        {
            var path = Path.Combine(PathToImages, image);

            using var data = SKData.Create(path);
            Assert.NotNull(data);

            using var codec = SKCodec.Create(data);
            Assert.NotNull(codec);

            Assert.Equal(SKCodecResult.Success, codec.GetPixels(out var pixels));
            Assert.NotEmpty(pixels);
        }