Example #1
0
        public static unsafe SKPixmap WaveletUpscale(this SKImage image, Wavelet wavelet)
        {
            int width          = image.Width;
            int height         = image.Height;
            int upscaledWidth  = width * 2;
            int upscaledHeight = height * 2;

            float[,] y  = new float[upscaledWidth, upscaledWidth];
            float[,] cb = new float[upscaledWidth, upscaledWidth];
            float[,] cr = new float[upscaledWidth, upscaledWidth];
            float[,] a  = new float[upscaledWidth, upscaledWidth];

            image.ToYCbCrAArrays(y, cb, cr, a);

            WaveletTransform2D wavelet2D;
            WaveletTransform2D upscaledWavelet2D;

            switch (wavelet)
            {
            case Wavelet.Haar:
                wavelet2D         = new HaarWavelet2D(width, height);
                upscaledWavelet2D = new HaarWavelet2D(upscaledWidth, upscaledHeight);
                break;

            case Wavelet.Biorthogonal53:
            default:
                wavelet2D         = new Biorthogonal53Wavelet2D(width, height);
                upscaledWavelet2D = new Biorthogonal53Wavelet2D(upscaledWidth, upscaledHeight);
                break;
            }

            wavelet2D.Transform2D(y);
            wavelet2D.Transform2D(cb);
            wavelet2D.Transform2D(cr);
            wavelet2D.Transform2D(a);

            upscaledWavelet2D.ReverseTransform2D(y);
            upscaledWavelet2D.ReverseTransform2D(cb);
            upscaledWavelet2D.ReverseTransform2D(cr);
            upscaledWavelet2D.ReverseTransform2D(a);

            for (int row = 0; row < upscaledHeight; row++)
            {
                for (int col = 0; col < upscaledWidth; col++)
                {
                    y[col, row]  *= 4.0f;
                    cb[col, row] *= 4.0f;
                    cr[col, row] *= 4.0f;
                    a[col, row]  *= 4.0f;
                }
            }

            SKImageInfo info   = new SKImageInfo(upscaledWidth, upscaledHeight, SKColorType.Rgba8888);
            SKImage     output = SKImage.Create(info);

            SKPixmap pixmap = output.ToRGBAPixmap(y, cb, cr, a);

            return(pixmap);
        }
Example #2
0
        public static SKImage Resize(this SKImage input, int width, int height)
        {
            var     imageInfo = new SKImageInfo(width, height);
            SKImage image     = SKImage.Create(imageInfo);

            input.ScalePixels(image.PeekPixels(), SKFilterQuality.High);
            return(image);
        }
        private SKBitmap Scale(SKBitmap input, int width, int height)
        {
            var info   = new SKImageInfo(width, height);
            var newImg = SKImage.Create(info);

            input.ScalePixels(newImg.PeekPixels(), SKFilterQuality.Medium);
            return(SKBitmap.FromImage(newImg));
        }
        public static void mergeTiles(string folderPath)
        {
            if (folderPath.Last() == '/' || folderPath.Last() == '\\')
            {
                folderPath = folderPath.Remove(folderPath.Length - 1);
            }

            Dictionary <string, SKImage> images = new Dictionary <string, SKImage>();
            int maxNumOfLevels = 3;

            for (int level = maxNumOfLevels; level > 0; --level)
            {
                int numOfTiles   = Convert.ToInt32(Math.Pow(4, level - 1));
                int tilesToASide = Convert.ToInt32(Math.Sqrt(numOfTiles));
                for (int globaly = 0; globaly < tilesToASide; ++globaly)
                {
                    for (int globalx = 0; globalx < tilesToASide; ++globalx)
                    {
                        var tempSurface = SKSurface.Create(new SKImageInfo(512, 512));
                        var canvas      = tempSurface.Canvas;
                        canvas.Clear(SKColors.Transparent);
                        for (int tiley = 0; tiley < 2; ++tiley)
                        {
                            for (int tilex = 0; tilex < 2; ++tilex)
                            {
                                int    imgx     = (globalx * 2 + tilex);
                                int    imgy     = (globaly * 2 + tiley);
                                string tilePath = $"{folderPath}/aqlatestL{level}T{(globalx * 2 + tilex).ToString("D2")}{(globaly * 2 + tiley).ToString("D2")}.png";
                                string tileKey  = $"L{level}T{(globalx * 2 + tilex).ToString("D2")}{(globaly * 2 + tiley).ToString("D2")}";
                                if (images.ContainsKey(tileKey))
                                {
                                    SKBitmap tile = SKBitmap.FromImage(images[tileKey]);
                                    canvas.DrawBitmap(tile, SKRect.Create(tilex * 256, tiley * 256, tile.Width, tile.Height));
                                }
                                else if (File.Exists(tilePath))
                                {
                                    SKBitmap tile = SKBitmap.Decode(File.OpenRead(tilePath));
                                    canvas.DrawBitmap(tile, SKRect.Create(tilex * 256, tiley * 256, tile.Width, tile.Height));
                                }
                            }
                        }
                        SKBitmap bigTile    = SKBitmap.FromImage(tempSurface.Snapshot());
                        SKBitmap littleTile = SKBitmap.FromImage(SKImage.Create(new SKImageInfo(256, 256)));
                        bigTile.ScalePixels(littleTile, SKFilterQuality.High);
                        SKImage outTile = SKImage.FromBitmap(littleTile);
                        images.Add($"L{level - 1}T{globalx.ToString("D2")}{globaly.ToString("D2")}", outTile);
                    }
                }
            }

            foreach (KeyValuePair <string, SKImage> file in images)
            {
                var data   = file.Value.Encode();
                var stream = File.OpenWrite($"{folderPath}/aqlatest{file.Key}.png");
                data.SaveTo(stream);
            }
        }
        public void ImageCreateDoesNotThrow()
        {
            var info = new SKImageInfo(1, 1);

            using (var image = SKImage.Create(info)) {
                Assert.IsFalse(image.IsTextureBacked);
                Assert.AreEqual(image, image.ToRasterImage());
            }
        }
Example #6
0
        public static SKImage ToSKImage(this Bitmap bitmap)
        {
            SKImage sKImage = SKImage.Create(new SKImageInfo(bitmap.Width, bitmap.Height));

            using (SKPixmap pixmap = sKImage.PeekPixels())
            {
                bitmap.ToSKPixmap(pixmap);
                return(sKImage);
            }
        }
Example #7
0
        public static SKImage ToSKImage(this CGImage cgImage)
        {
            var info  = new SKImageInfo((int)cgImage.Width, (int)cgImage.Height);
            var image = SKImage.Create(info);

            using (var pixmap = image.PeekPixels())
            {
                cgImage.ToSKPixmap(pixmap);
            }
            return(image);
        }
        public static SKImage ToSKImage(this BitmapSource bitmap)
        {
            var info  = new SKImageInfo(bitmap.PixelWidth, bitmap.PixelHeight);
            var image = SKImage.Create(info);

            using (var pixmap = image.PeekPixels())
            {
                bitmap.ToSKPixmap(pixmap);
            }
            return(image);
        }
Example #9
0
        public void ImageInfoHasColorSpace()
        {
            var colorspace = SKColorSpace.CreateSrgb();

            var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, colorspace);

            Assert.Equal(colorspace, info.ColorSpace);

            var image = SKImage.Create(info);

            Assert.Equal(colorspace, image.PeekPixels().ColorSpace);
        }
Example #10
0
        public static SKImage ToSKImage(this CIImage ciImage)
        {
            var extent = ciImage.Extent;
            var info   = new SKImageInfo((int)extent.Width, (int)extent.Height);
            var image  = SKImage.Create(info);

            using (var pixmap = image.PeekPixels())
            {
                ciImage.ToSKPixmap(pixmap);
            }
            return(image);
        }
Example #11
0
        static SKImage toSKImage(BitmapSource bitmap)
        {
            // TODO: maybe keep the same color types where we can, instead of just going to the platform default
            var info  = new SKImageInfo(bitmap.PixelWidth, bitmap.PixelHeight);
            var image = SKImage.Create(info);

            using (var pixmap = image.PeekPixels())
            {
                toSKPixmap(bitmap, pixmap);
            }
            return(image);
        }
Example #12
0
        public static SKImage ToSKImage(this System.Drawing.Bitmap bitmap)
        {
            // TODO: maybe keep the same color types where we can, instead of just going to the platform default

            var info  = new SKImageInfo(bitmap.Width, bitmap.Height);
            var image = SKImage.Create(info);

            using (var pixmap = image.PeekPixels())
            {
                bitmap.ToSKPixmap(pixmap);
            }
            return(image);
        }
Example #13
0
        private static string CreateInputFile()
        {
            var inputPath = GetTempPath();

            using (var stream = File.OpenWrite(inputPath))
            {
                SKBitmap.FromImage(SKImage.Create(new SKImageInfo(100, 100)))
                .PeekPixels()
                .Encode(SKPngEncoderOptions.Default)
                .SaveTo(stream);
            }

            return(inputPath);
        }
Example #14
0
        public ImmutableBitmap(ImmutableBitmap src, PixelSize destinationSize, BitmapInterpolationMode interpolationMode)
        {
            SKImageInfo info   = new SKImageInfo(destinationSize.Width, destinationSize.Height, SKColorType.Bgra8888);
            SKImage     output = SKImage.Create(info);

            src._image.ScalePixels(output.PeekPixels(), interpolationMode.ToSKFilterQuality());

            _image = output;

            PixelSize = new PixelSize(_image.Width, _image.Height);

            // TODO: Skia doesn't have an API for DPI.
            Dpi = new Vector(96, 96);
        }
        public async Task ImageReturnsSameImage()
        {
            using var image = SKImage.Create(new SKImageInfo(100, 100));

            var source = new SKImageImageSource {
                Image = image
            };

            var result = await source.ToSKImageAsync();

            Assert.NotNull(result);

            Assert.Equal(image, result);
        }
Example #16
0
        public void LazyRasterCanReadToNonLazy()
        {
            using var data  = SKData.Create(Path.Combine(PathToImages, "baboon.jpg"));
            using var image = SKImage.FromEncodedData(data);
            Assert.True(image.IsLazyGenerated);

            var info = new SKImageInfo(image.Width, image.Height);

            using var copy = SKImage.Create(info);
            using var pix  = copy.PeekPixels();

            Assert.True(image.ReadPixels(pix));
            Assert.False(copy.IsLazyGenerated);
            Assert.NotNull(copy.PeekPixels());
        }
Example #17
0
        public SnapshotImage GetSnapshotAndAddUser(int id)
        {
            lock (_snapshotLock)
            {
                if (_snapshots.TryGetValue(id, out var snapshotImage))
                {
                    snapshotImage.AddUser();
                    return(snapshotImage);
                }

                return(new SnapshotImage(
                           SKImage.Create(new SKImageInfo(1, 1)),
                           new SKSizeI(0, 0)
                           ));
            }
        }
Example #18
0
 public RoomData(string id)
 {
     RoomId    = id;
     ImageInfo = new SKImageInfo(800, 600);
     Image     = SKImage.Create(new SKImageInfo(800, 600));
     Surface   = SKSurface.Create(ImageInfo);
     Paint     = new SKPaint
     {
         IsAntialias = true,
         Color       = new SKColor(0, 0, 0, 255),
         StrokeWidth = 4,
         PathEffect  = SKPathEffect.CreateCorner(50),
         Style       = SKPaintStyle.Stroke
     };
     Path = new SKPath();
 }
        public static SKImage CaptureRegion(int x, int y, int width, int height)
        {
            IntPtr sourceDC = IntPtr.Zero;
            IntPtr targetDC = IntPtr.Zero;
            IntPtr compatibleBitmapHandle = IntPtr.Zero;

            // create the final SkiaSharp image
            SKImage  image  = SKImage.Create(new SKImageInfo(width, height));
            SKPixmap pixmap = image.PeekPixels();

            try
            {
                // gets the main desktop and all open windows
                sourceDC = User32.GetDC(User32.GetDesktopWindow());
                targetDC = Gdi32.CreateCompatibleDC(sourceDC);

                // create a bitmap compatible with our target DC
                compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height);

                // gets the bitmap into the target device context
                Gdi32.SelectObject(targetDC, compatibleBitmapHandle);

                // copy from source to destination
                Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.TernaryRasterOperations.SRCCOPY);

                // create the info structure
                Gdi32.BITMAPINFOHEADER bmi = new Gdi32.BITMAPINFOHEADER();
                bmi.biPlanes      = 1;
                bmi.biBitCount    = 32;
                bmi.biWidth       = width;
                bmi.biHeight      = -height;
                bmi.biCompression = Gdi32.BitmapCompressionMode.BI_RGB;

                // read the raw pixels into the pixmap for the image
                Gdi32.GetDIBits(targetDC, compatibleBitmapHandle, 0, height, pixmap.GetPixels(), bmi, Gdi32.DIB_Color_Mode.DIB_RGB_COLORS);
            }
            finally
            {
                Gdi32.DeleteObject(compatibleBitmapHandle);

                User32.ReleaseDC(IntPtr.Zero, sourceDC);
                User32.ReleaseDC(IntPtr.Zero, targetDC);
            }

            return(image);
        }
Example #20
0
    private static Stream CreateImage(int width,
                                      int height,
                                      Action <SKBitmap> bitmapModifier)
    {
        var image  = SKImage.Create(new SKImageInfo(width, height));
        var bitmap = SKBitmap.FromImage(image);

        // Modify graphic
        bitmapModifier(bitmap);

        // Prepare result stream
        var result = new MemoryStream();

        bitmap.Encode(result, SKEncodedImageFormat.Png, 100);

        // Set result pointer back to 0 for the result consumer to read
        result.Position = 0;
        // Closing the stream is up to the consumer
        return(result);
    }
        public async Task StreamReturnsSimilarImage()
        {
            var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, SKColorSpace.CreateSrgb());

            using var image  = SKImage.Create(info);
            using var data   = image.Encode();
            using var stream = data.AsStream();

            var source = new StreamImageSource {
                Stream = token => Task.FromResult(stream)
            };

            var result = await source.ToSKImageAsync();

            Assert.NotNull(result);

            var resultInfo = new SKImageInfo(result.Width, result.Height, result.ColorType, result.AlphaType, result.ColorSpace);

            Assert.Equal(info, resultInfo);
        }
        protected virtual SKImage ConvertProfile(SKImage data, float width, float height)
        {
            using SKImage srcImg = data;
            SKImageInfo info = new SKImageInfo((int)width, (int)height,
                                               SKImageInfo.PlatformColorType, SKAlphaType.Opaque, SKColorSpace.CreateSrgb());
            // this is the important part. set the destination ColorSpace as
            // `SKColorSpace.CreateSrgb()`. Skia will then be able to automatically convert
            // the original CMYK colorspace, to this new sRGB colorspace.

            SKImage newImg = SKImage.Create(info);

            srcImg.ScalePixels(newImg.PeekPixels(), SKFilterQuality.None);

            // Remove transparency
            var bitmap = RemoveTransparency(srcImg);

            newImg = SKImage.FromBitmap(bitmap);
            // now when doing this resize, Skia knows the original ColorSpace, and the
            // destination ColorSpace, and converts the colors from CMYK to sRGB.
            return(newImg);
        }
Example #23
0
        private static SKImage CreateLabelAsBitmap(LabelStyle style, string text, SKPaint paint, float layerOpacity)
        {
            var rect = new SKRect();

            paint.MeasureText(text, ref rect);

            var backRect = new SKRect(0, 0, rect.Width + 6, rect.Height + 6);

            var skImageInfo = new SKImageInfo((int)backRect.Width, (int)backRect.Height);

            var bitmap = SKImage.Create(skImageInfo);

            // todo: Construct SKCanvas with SKImage once this option becomes available
            using (var target = new SKCanvas(SKBitmap.FromImage(bitmap)))
            {
                target.Clear();

                DrawBackground(style, backRect, target, layerOpacity);
                target.DrawText(text, -rect.Left + 3, -rect.Top + 3, paint);
                return(bitmap);
            }
        }
Example #24
0
 public static SKImage GetImage(this SKCodecFrameInfo info, SKCodec codec)
 {
     return(SKImage.Create(codec.Info));
 }
Example #25
0
        /// <summary>
        /// Load an image from the phone
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void LoadImage(object sender, EventArgs args)
        {
            IPhotoLibrary photoLibrary = DependencyService.Get <IPhotoLibrary>();

            using (Stream stream = await photoLibrary.PickPhotoAsync())
            {
                if (stream != null)
                {
                    SKBitmap loaded = SKBitmap.Decode(stream);
                    if (loaded != null)
                    {
                        if (animation)
                        {
                            StopAccelerometer();
                        }


                        //Set the image dimensions
                        width  = (int)imgGenerated.CanvasSize.ToFormsSize().Width;
                        height = (int)imgGenerated.CanvasSize.ToFormsSize().Height;

                        int oldSize = width;
                        if (width > height)
                        {
                            oldSize = height;
                        }

                        int size = oldSize;
                        for (int i = 1; i < oldSize; i <<= 1)
                        {
                            size = i;
                        }

                        width  = size;
                        height = size;

                        generator.SetDimensions(width, height);


                        // Resize the loaded image
                        //source: https://stackoverflow.com/questions/48422724/fastest-way-to-scale-an-skimage-skiasharp
                        SKImageInfo info = new SKImageInfo(width, height, SKColorType.Rgba8888);

                        SKImage output = SKImage.Create(info);

                        loaded.ScalePixels(output.PeekPixels(), SKFilterQuality.None);

                        imgBitmap = SKBitmap.FromImage(output);

                        skRect = new SKRect(0, 0, oldSize, oldSize);

                        generator.Load(imgBitmap);
                        imgGenerated.InvalidateSurface();

                        if (animation)
                        {
                            StartAccelerometer();
                        }
                    }
                }
            }
        }
Example #26
0
        public void ImageInfoColorSpaceIsReferencedCorrectly()
        {
            VerifyImmediateFinalizers();

            var img = DoWork(out var colorspaceHandle);

            CollectGarbage();

            Assert.Equal(1, colorspaceHandle.GetReferenceCount(true));

            Check();

            CollectGarbage();

            Assert.Equal(1, colorspaceHandle.GetReferenceCount(true));

            void Check()
            {
                var peek = img.PeekPixels();

                Assert.Equal(2, colorspaceHandle.GetReferenceCount(true));

                // get the info and color space
                var info1 = peek.Info;
                var cs1   = info1.ColorSpace;

                Assert.Equal(3, colorspaceHandle.GetReferenceCount(true));
                Assert.NotNull(cs1);

                // get the info and color space again and make sure we are all using the same things
                var info2 = peek.Info;
                var cs2   = info2.ColorSpace;

                Assert.Equal(3, colorspaceHandle.GetReferenceCount(true));
                Assert.NotNull(cs2);

                Assert.Same(cs1, cs2);
            }

            SKImage DoWork(out IntPtr handle)
            {
                var colorspace = SKColorSpace.CreateRgb(
                    new SKColorSpaceTransferFn {
                    A = 0.6f, B = 0.5f, C = 0.4f, D = 0.3f, E = 0.2f, F = 0.1f
                },
                    SKMatrix44.CreateIdentity());

                Assert.NotNull(colorspace);

                handle = colorspace.Handle;
                Assert.Equal(1, handle.GetReferenceCount(true));

                var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, colorspace);

                Assert.Equal(1, handle.GetReferenceCount(true));

                var image = SKImage.Create(info);

                Assert.Equal(2, handle.GetReferenceCount(true));

                return(image);
            }
        }
Example #27
0
        public void ColorSpaceIsNotDisposedPrematurely()
        {
            VerifyImmediateFinalizers();

            var img = DoWork(out var colorSpaceHandle, out var weakColorspace);

            CheckBeforeCollection(colorSpaceHandle);

            CheckExistingImage(3, img, colorSpaceHandle);

            CollectGarbage();

            Assert.Null(weakColorspace.Target);
            Assert.Equal(1, colorSpaceHandle.GetReferenceCount(true));

            CheckExistingImage(2, img, colorSpaceHandle);

            CollectGarbage();

            Assert.Null(weakColorspace.Target);
            Assert.Equal(1, colorSpaceHandle.GetReferenceCount(true));

            CollectGarbage();

            Assert.Equal(1, colorSpaceHandle.GetReferenceCount(true));

            GC.KeepAlive(img);

            void CheckBeforeCollection(IntPtr csh)
            {
                Assert.NotNull(weakColorspace.Target);
                Assert.Equal(2, csh.GetReferenceCount(true));
            }

            void CheckExistingImage(int expected, SKImage image, IntPtr csh)
            {
                var peek = image.PeekPixels();

                Assert.Equal(expected, csh.GetReferenceCount(true));

                var info = peek.Info;

                Assert.Equal(3, csh.GetReferenceCount(true));

                var cs = info.ColorSpace;

                Assert.Equal(3, csh.GetReferenceCount(true));
                Assert.NotNull(cs);
            }

            SKImage DoWork(out IntPtr handle, out WeakReference weak)
            {
                var colorspace = SKColorSpace.CreateRgb(
                    new SKColorSpaceTransferFn {
                    A = 0.1f, B = 0.2f, C = 0.3f, D = 0.4f, E = 0.5f, F = 0.6f
                },
                    SKMatrix44.CreateIdentity());

                Assert.NotNull(colorspace);

                handle = colorspace.Handle;
                weak   = new WeakReference(colorspace);

                Assert.Equal(1, handle.GetReferenceCount(true));

                var info = new SKImageInfo(100, 100, SKImageInfo.PlatformColorType, SKAlphaType.Premul, colorspace);

                Assert.Equal(1, handle.GetReferenceCount(true));

                var image = SKImage.Create(info);

                Assert.Equal(2, handle.GetReferenceCount(true));

                return(image);
            }
        }