Beispiel #1
0
        /// <summary>
        /// アスペクトを描画
        /// </summary>
        /// <param name="cvs">Cvs.</param>
        /// <param name="info">Info.</param>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="aspectLine">Aspect line.</param>
        /// <param name="symbol">Symbol.</param>
        public void DrawAspect(SKCanvas cvs, AspectInfo info, Position from, Position to, SKPaint aspectLine, SKPaint symbol)
        {
            System.Reflection.Assembly asm =
                System.Reflection.Assembly.GetExecutingAssembly();
            SKManagedStream stream = new SKManagedStream(asm.GetManifestResourceStream("microcosm.system.AstroDotBasic.ttf"));
            {
                symbol.Typeface = SKTypeface.FromStream(stream);

                /*
                 * p.TextSize = 48;
                 * Position signValuePt;
                 * SKColor pink = SKColors.Pink;
                 * p.Color = pink;
                 * for (int i = 0; i < signs.Length; i++)
                 * {
                 *  signValuePt = Util.Rotate(diameter - 30, 0, 15 + 30 * i - ringsData[0].cusps[1]);
                 *  signValuePt.x = signValuePt.x + CenterX - 15;
                 *  signValuePt.y = -1 * signValuePt.y + CenterY + 20;
                 *  p.Color = CommonData.getSignColor(30 * i);
                 *  cvs.DrawText(signs[i], (float)signValuePt.x, (float)signValuePt.y, p);
                 * }
                 * p.Color = SKColors.Black;
                 */
                Console.WriteLine(info.aspectKind.ToString());
                Console.WriteLine(info.absoluteDegree);
                Console.WriteLine(info.targetDegree);
                Console.WriteLine("");

                cvs.DrawLine((float)from.x, (float)from.y, (float)to.x, (float)to.y, aspectLine);
                cvs.DrawText(CommonData.getAspectSymbol(info.aspectKind),
                             (float)((from.x + to.x) / 2), (float)((from.y + to.y) / 2), symbol);
            }
        }
Beispiel #2
0
        public void ManagedStreamReadsOffsetChunkCorrectly()
        {
            var data = new byte[1024];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % byte.MaxValue);
            }

            var stream          = new MemoryStream(data);
            var skManagedStream = new SKManagedStream(stream);

            var offset = 768;

            skManagedStream.Position = offset;

            var buffer = new byte[data.Length];
            var taken  = skManagedStream.Read(buffer, buffer.Length);

            Assert.AreEqual(data.Length - offset, taken);

            var resultData = data.Skip(offset).Take(buffer.Length).ToArray();

            resultData = resultData.Concat(Enumerable.Repeat <byte>(0, offset)).ToArray();
            Assert.AreEqual(resultData, buffer);
        }
Beispiel #3
0
        async void OnButtonClickedChoosePhotos(object sender, EventArgs e)
        {
            IPicturePicker picturePicker = DependencyService.Get <IPicturePicker>();

            using (Stream stream = await picturePicker.GetImageStreamAsync())
            {
                if (stream != null)
                {
                    loadBitMap = true;
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        stream.CopyTo(memStream);
                        memStream.Seek(0, SeekOrigin.Begin);

                        using (SKManagedStream skStream = new SKManagedStream(memStream))
                        {
                            bitMap = SKBitmap.Decode(skStream);
                        }
                    }
                }
                else
                {
                    loadBitMap = false;
                }
            }
            CallImageActionTools();
        }
Beispiel #4
0
        protected override void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            canvas.Clear(SKColors.White);

            var paint = new SKPaint
            {
                IsStroke    = true,
                StrokeWidth = 3,
                Color       = SampleMedia.Colors.XamarinLightBlue
            };

            using (var stream = new SKManagedStream(SampleMedia.Images.BabyTux))
                using (var bigBitmap = SKBitmap.Decode(stream))
                {
                    canvas.DrawBitmap(bigBitmap, 10, 10);
                }

            using (var stream = new SKManagedStream(SampleMedia.Images.BabyTux))
                using (var codec = SKCodec.Create(stream))
                {
                    var info    = codec.Info;
                    var subset  = SKRectI.Create(100, 50, 190, 170);
                    var options = new SKCodecOptions(subset);
                    using (var bitmap = new SKBitmap(subset.Width, subset.Height, info.ColorType, SKAlphaType.Premul))
                    {
                        var result = codec.GetPixels(bitmap.Info, bitmap.GetPixels(), options);
                        if (result == SKCodecResult.Success || result == SKCodecResult.IncompleteInput)
                        {
                            canvas.DrawBitmap(bitmap, info.Width + 20, subset.Top + 10);
                        }
                    }
                }
        }
Beispiel #5
0
        public void DuplicateStreamIsCollected()
        {
            VerifySupportsExceptionsInDelegates();

            var handle = DoWork();

            CollectGarbage();

            Assert.False(SKObject.GetInstance <SKManagedStream>(handle, out _));

            IntPtr DoWork()
            {
                var dotnet = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
                var stream = new SKManagedStream(dotnet, true);

                Assert.Equal(1, stream.ReadByte());
                Assert.Equal(2, stream.ReadByte());

                var dupe1 = stream.Duplicate();

                Assert.Equal(1, dupe1.ReadByte());
                Assert.Equal(2, dupe1.ReadByte());

                Assert.Throws <InvalidOperationException>(() => stream.Duplicate());

                stream.Dispose();

                var dupe2 = dupe1.Duplicate();

                Assert.Equal(1, dupe2.ReadByte());
                Assert.Equal(2, dupe2.ReadByte());

                return(dupe2.Handle);
            }
        }
Beispiel #6
0
        public void MiddleDuplicateCanBeRemoved()
        {
            VerifySupportsExceptionsInDelegates();

            var dotnet = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
            var stream = new SKManagedStream(dotnet, true);

            Assert.Equal(1, stream.ReadByte());
            Assert.Equal(2, stream.ReadByte());

            var dupe1 = stream.Duplicate();

            Assert.Equal(1, dupe1.ReadByte());
            Assert.Equal(2, dupe1.ReadByte());
            Assert.Throws <InvalidOperationException>(() => stream.Duplicate());

            var dupe2 = dupe1.Duplicate();

            Assert.Equal(1, dupe2.ReadByte());
            Assert.Equal(2, dupe2.ReadByte());
            Assert.Throws <InvalidOperationException>(() => stream.Duplicate());
            Assert.Throws <InvalidOperationException>(() => dupe1.Duplicate());

            dupe1.Dispose();
            Assert.Throws <InvalidOperationException>(() => stream.Duplicate());

            dupe2.Dispose();
            var dupe3 = stream.Duplicate();

            Assert.Equal(1, dupe3.ReadByte());
            Assert.Equal(2, dupe3.ReadByte());
            Assert.Throws <InvalidOperationException>(() => stream.Duplicate());
        }
Beispiel #7
0
        public unsafe void StreamLosesOwnershipAndCanBeDisposedButIsNotActually()
        {
            var path   = Path.Combine(PathToImages, "color-wheel.png");
            var bytes  = File.ReadAllBytes(path);
            var stream = new SKManagedStream(new MemoryStream(bytes), true);
            var handle = stream.Handle;

            Assert.True(stream.OwnsHandle);
            Assert.False(stream.IgnorePublicDispose);
            Assert.True(SKObject.GetInstance <SKManagedStream>(handle, out _));

            var codec = SKCodec.Create(stream);

            Assert.False(stream.OwnsHandle);
            Assert.True(stream.IgnorePublicDispose);

            stream.Dispose();
            Assert.True(SKObject.GetInstance <SKManagedStream>(handle, out var inst));
            Assert.Same(stream, inst);

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

            codec.Dispose();
            Assert.False(SKObject.GetInstance <SKManagedStream>(handle, out _));
        }
Beispiel #8
0
        public void FullOwnershipIsTransferredToTheChildIfTheParentIsDisposed()
        {
            VerifySupportsExceptionsInDelegates();

            var dotnet = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 });
            var stream = new SKManagedStream(dotnet, true);

            Assert.Equal(1, stream.ReadByte());
            Assert.Equal(2, stream.ReadByte());

            var dupe1 = stream.Duplicate();

            Assert.Equal(1, dupe1.ReadByte());
            Assert.Equal(2, dupe1.ReadByte());

            Assert.Throws <InvalidOperationException>(() => stream.Duplicate());

            stream.Dispose();

            var dupe2 = dupe1.Duplicate();

            Assert.Equal(1, dupe2.ReadByte());
            Assert.Equal(2, dupe2.ReadByte());

            Assert.Throws <InvalidOperationException>(() => dupe1.Duplicate());

            dupe1.Dispose();
            dupe2.Dispose();

            Assert.Throws <ObjectDisposedException>(() => dotnet.Position);
        }
        // Preprocess the quadrants of the input image
        public void ProcessInputImageColors(int tileWidth, int tileHeight)
        {
            using (var skStream = new SKManagedStream(inputStream))
                using (var bitmap = SKBitmap.Decode(skStream)) {
                    int xTileCount = bitmap.Width / tileWidth;
                    int yTileCount = bitmap.Height / tileHeight;

                    int tileDivisionWidth  = tileWidth / quadrantDivisionCount;
                    int tileDivisionHeight = tileHeight / quadrantDivisionCount;

                    int quadrantsCompleted = 0;
                    int quadrantsTotal     = xTileCount * yTileCount * quadrantDivisionCount * quadrantDivisionCount;
                    inputImageRGBGrid = new SKColor[xTileCount, yTileCount][, ];

                    //Divide the input image into separate tile sections and calculate the average pixel value for each one
                    for (int yTileIndex = 0; yTileIndex < yTileCount; yTileIndex++)
                    {
                        for (int xTileIndex = 0; xTileIndex < xTileCount; xTileIndex++)
                        {
                            var rect = SKRectI.Create(xTileIndex * tileWidth, yTileIndex * tileHeight, tileWidth, tileHeight);
                            inputImageRGBGrid[xTileIndex, yTileIndex] = GetAverageColorGrid(bitmap, rect);
                            quadrantsCompleted += (quadrantDivisionCount * quadrantDivisionCount);
                        }
                    }
                }
        }
Beispiel #10
0
        public ColorPickerView(ContextManager mg)
        {
            manager = mg;
            InitializeComponent();
            SetBindingContext();
            StrokeWidthSlider.BindingContext = Service;
            HardnesSlider.BindingContext     = Service;

            SpacingSlider.BindingContext          = Service;
            XDispSlider.BindingContext            = Service;
            YDispSlider.BindingContext            = Service;
            OpacityRandomSlider.BindingContext    = Service;
            ScaleSlider.BindingContext            = Service;
            HueJitterSlider.BindingContext        = Service;
            SaturationJitterSlider.BindingContext = Service;
            LightnessJitterSlider.BindingContext  = Service;
            HardnessJitter.BindingContext         = Service;
            BMSelector.ItemsSource = PBlendingMode.Names;


            Assembly assembly = GetType().GetTypeInfo().Assembly;

            using (Stream strem = assembly.GetManifestResourceStream("Pen.bg.bmp"))
                using (SKManagedStream skStream = new SKManagedStream(strem))
                    using (SKBitmap bitma = SKBitmap.Decode(skStream))
                        using (SKShader shader = SKShader.CreateBitmap(bitma, SKShaderTileMode.Repeat, SKShaderTileMode.Repeat))
                        {
                            //BgPaint.Shader = shader;
                        };
            var a = manager.ActiveKernel.Get <BackgroundImage>();

            BgPaint.Shader = a.GetShader();
        }
Beispiel #11
0
        /// <summary>
        /// 创建系列缩略图
        /// </summary>
        /// <param name="imageStream"></param>
        /// <param name="folder"></param>
        /// <param name="fileName"></param>
        /// <param name="widths"></param>
        /// <returns></returns>
        public static string[] CreateThumbnails(Stream imageStream, string folder, string fileName, IEnumerable <int> widths)
        {
            Directory.CreateDirectory(folder);
            var displayName = Path.GetFileNameWithoutExtension(fileName);
            var ext         = Path.GetExtension(fileName);
            var format      = GetFormat(fileName);

            var result = new List <string>();

            using (var inputStream = new SKManagedStream(imageStream))
                using (var codec = SKCodec.Create(inputStream))
                    using (var original = SKBitmap.Decode(codec))
                        using (var image = HandleOrientation(original, codec.EncodedOrigin))
                        {
                            foreach (var width in widths)
                            {
                                int height = (int)Math.Round(width * ((float)image.Height / image.Width));

                                string thumbnailPath = Path.Combine(folder, $"{displayName}-{width}x{height}{ext}");
                                result.Add(thumbnailPath);
                                var info = new SKImageInfo(width, height);

                                using (var resized = image.Resize(info, SKFilterQuality.Medium))
                                    using (var thumb = SKImage.FromBitmap(resized))
                                        using (var fs = new FileStream(thumbnailPath, FileMode.CreateNew, FileAccess.ReadWrite))
                                        {
                                            thumb.Encode(format, Quality)
                                            .SaveTo(fs);
                                        }
                            }
                        }
            return(result.ToArray());
        }
        public void CreateThumbnails(Stream imageStream, string filePath)
        {
            string dir         = Path.Combine(Path.GetDirectoryName(filePath), "thumbnail");
            string displayName = Path.GetFileNameWithoutExtension(filePath);
            string ext         = Path.GetExtension(filePath);

            Directory.CreateDirectory(dir);

            var format = GetFormat(filePath);

            using (var inputStream = new SKManagedStream(imageStream))
                using (var codec = SKCodec.Create(inputStream))
                    using (var original = SKBitmap.Decode(codec))
                        using (var image = HandleOrientation(original, codec.Origin))
                        {
                            foreach (ImageType type in Enum.GetValues(typeof(ImageType)))
                            {
                                int width  = (int)type;
                                int height = (int)Math.Round(width * ((float)image.Height / image.Width));

                                string thumbnailPath = Path.Combine(dir, $"{displayName}-{width}x{height}{ext}");
                                var    info          = new SKImageInfo(width, height);

                                using (var resized = image.Resize(info, SKBitmapResizeMethod.Lanczos3))
                                    using (var thumb = SKImage.FromBitmap(resized))
                                        using (var fs = new FileStream(thumbnailPath, FileMode.CreateNew, FileAccess.ReadWrite))
                                        {
                                            thumb.Encode(format, Quality)
                                            .SaveTo(fs);
                                        }
                            }
                        }
        }
Beispiel #13
0
        /// <summary>
        /// 创建缩略图,未格式化
        /// </summary>
        /// <param name="abPath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static SKBitmap MakeThumb(string abPath, int width, int height, CroppingMode mode)
        {
            using (var input = System.IO.File.OpenRead(abPath))
            {
                if (mode == CroppingMode.NONE)
                {
                    return(SKBitmap.Decode(input));
                }
                using (var inputStream = new SKManagedStream(input))
                {
                    using (var bitmap = SKBitmap.Decode(inputStream))
                    {
                        var cropRect = new CroppingRectangle(bitmap, width, height, mode);

                        SKBitmap croppedBitmap = new SKBitmap((int)cropRect.Dest.Width, (int)cropRect.Dest.Height);

                        using (SKCanvas canvas = new SKCanvas(croppedBitmap))
                        {
                            canvas.DrawBitmap(bitmap, cropRect.Rect, cropRect.Dest);
                        }
                        return(croppedBitmap);
                    }
                }
            }
        }
        protected override void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            // load the image from the embedded resource stream
            using (var stream = new SKManagedStream(SampleMedia.Images.ColorWheel))
                using (var source = SKBitmap.Decode(stream))
                {
                    // invert the pixels
                    var pixels = source.Pixels;
                    for (int i = 0; i < pixels.Length; i++)
                    {
                        pixels[i] = new SKColor(
                            (byte)(255 - pixels[i].Red),
                            (byte)(255 - pixels[i].Green),
                            (byte)(255 - pixels[i].Blue),
                            pixels[i].Alpha);
                    }
                    source.Pixels = pixels;

                    using (var shader = SKShader.CreateBitmap(source, SKShaderTileMode.Repeat, SKShaderTileMode.Repeat))
                        using (var paint = new SKPaint())
                        {
                            paint.IsAntialias = true;
                            paint.Shader      = shader;

                            // tile the bitmap
                            canvas.Clear(SKColors.White);
                            canvas.DrawPaint(paint);
                        }
                }
        }
Beispiel #15
0
        // This code uses System.Drawing to merge images and render text on the image
        // System.Drawing SHOULD NOT be used in a production application
        // It is not supported in server scenarios and is used here as a demo only!
        public static void MergeCardImage(string cardPath, byte[] imageBytes, Stream outputStream, string personName, string personTitle, double score)
        {
            using (MemoryStream faceImageStream = new MemoryStream(imageBytes)) {
                using (var surface = SKSurface.Create(width: CardWidth, height: CardHeight, colorType: SKImageInfo.PlatformColorType, alphaType: SKAlphaType.Premul)) {
                    SKCanvas canvas = surface.Canvas;

                    canvas.DrawColor(SKColors.White); // clear the canvas / fill with white

                    using (var fileStream = File.OpenRead(cardPath))
                        using (var stream = new SKManagedStream(fileStream)) // decode the bitmap from the stream
                            using (var cardBack = SKBitmap.Decode(stream))
                                using (var face = SKBitmap.Decode(imageBytes))
                                    using (var paint = new SKPaint()) {
                                        canvas.DrawBitmap(cardBack, SKRect.Create(0, 0, CardWidth, CardHeight), paint);
                                        canvas.DrawBitmap(face, SKRect.Create(TopLeftFaceX, TopLeftFaceY, FaceWidth, FaceWidth));

                                        RenderText(canvas, NameFontSize, NameTextX, NameTextY, NameWidth, personName);
                                        RenderText(canvas, TitleFontSize, NameTextX, TitleTextY, NameWidth, personTitle);
                                        RenderScore(canvas, ScoreX, ScoreY, ScoreWidth, score.ToString());

                                        canvas.Flush();

                                        using (var jpgImage = surface.Snapshot().Encode(SKEncodedImageFormat.Jpeg, 80)) {
                                            jpgImage.SaveTo(outputStream);
                                        }
                                    }
                }
            }
        }
Beispiel #16
0
        public void ManagedStreamReadsByteCorrectly()
        {
            var data = new byte[1024];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % byte.MaxValue);
            }

            var stream = new MemoryStream(data);
            var skManagedStream = new SKManagedStream(stream);

            skManagedStream.Rewind();
            Assert.AreEqual(0, stream.Position);
            Assert.AreEqual(0, skManagedStream.Position);

            for (int i = 0; i < data.Length; i++)
            {
                skManagedStream.Position = i;

                Assert.AreEqual(i, stream.Position);
                Assert.AreEqual(i, skManagedStream.Position);

                Assert.AreEqual((byte)(i % byte.MaxValue), data[i]);
                Assert.AreEqual((byte)(i % byte.MaxValue), skManagedStream.ReadByte());

                Assert.AreEqual(i + 1, stream.Position);
                Assert.AreEqual(i + 1, skManagedStream.Position);
            }
        }
Beispiel #17
0
        public void ManagedStreamIsAccessableFromNativeType()
        {
            var paint = CreatePaint();

            CollectGarbage();

            var tf = paint.Typeface;

            Assert.Equal("Roboto2", tf.FamilyName);
            Assert.True(tf.TryGetTableTags(out var tags));
            Assert.NotEmpty(tags);

            SKPaint CreatePaint()
            {
                var bytes  = File.ReadAllBytes(Path.Combine(PathToFonts, "Roboto2-Regular_NoEmbed.ttf"));
                var dotnet = new MemoryStream(bytes);
                var stream = new SKManagedStream(dotnet, true);

                var typeface = SKTypeface.FromStream(stream);

                return(new SKPaint
                {
                    Typeface = typeface
                });
            }
        }
Beispiel #18
0
        public void StreamIsAccessableFromNativeType()
        {
            VerifyImmediateFinalizers();

            var paint = CreatePaint(out var typefaceHandle);

            CollectGarbage();

            Assert.False(SKObject.GetInstance <SKTypeface>(typefaceHandle, out _));

            var tf = paint.Typeface;

            Assert.Equal("Roboto2", tf.FamilyName);
            Assert.True(tf.TryGetTableTags(out var tags));
            Assert.NotEmpty(tags);

            SKPaint CreatePaint(out IntPtr handle)
            {
                var bytes  = File.ReadAllBytes(Path.Combine(PathToFonts, "Roboto2-Regular_NoEmbed.ttf"));
                var dotnet = new MemoryStream(bytes);
                var stream = new SKManagedStream(dotnet, true);

                var typeface = SKTypeface.FromStream(stream);

                handle = typeface.Handle;

                return(new SKPaint
                {
                    Typeface = typeface
                });
            }
        }
Beispiel #19
0
        public Asset(string path)
        {
            this.Path = path;
            this.Path.WithoutQualifier(out string name, out string extension);
            this.FilenameWithoutQualifierAndExtension = name;
            this.Extension = extension;

            if (Densities.TryFind(path, out double foundDensity))
            {
                this.Density = foundDensity;
            }

            using (var input = File.Open(path, FileMode.Open))
                using (var memory = new MemoryStream())
                {
                    input.CopyTo(memory);
                    memory.Seek(0, SeekOrigin.Begin);
                    memory.Position = 0;

                    using (var stream = new SKManagedStream(memory))
                    {
                        this.bitmap = SKBitmap.Decode(stream);

                        if (this.bitmap == null)
                        {
                            throw new InvalidOperationException($"The provided image isn't valid : {path} (SKBitmap can't be created).");
                        }
                    }
                }
        }
Beispiel #20
0
        async void LoadImagesAsync()
        {
            var images = new List <Uri>
            {
                new System.Uri("ms-appx:///Assets/LockScreenLogo.scale-200.png"),
                new System.Uri("ms-appx:///Assets/StoreLogo.png"),
            };

            foreach (var uri in images)
            {
                var storagefile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

                Stream fileStream = (await storagefile.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStreamForRead();

                // decode the bitmap from the stream
                using (var stream = new SKManagedStream(fileStream))
                {
                    var bitmap     = SKBitmap.Decode(stream);
                    var renderItem = new RenderItemViewModel
                    {
                        Name       = uri.ToString(),
                        RenderItem = new TouchManipulationBitmap(bitmap),
                        X          = 40,
                        Y          = 60
                    };
                    ViewModel.Layers.Add(renderItem);
                }
            }

            //using (var paint = new SKPaint())
            //{
            //    canvas.DrawBitmap(bitmap, SKRect.Create(Width, Height), paint);
            //}
        }
        protected void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            canvas.Clear(SKColors.White);

            // decode the bitmap
            var desiredInfo = new SKImageInfo(386, 395, SKImageInfo.PlatformColorType, SKAlphaType.Premul);

            using (var stream = new SKManagedStream(SampleMedia.Images.BabyTux))
                using (var bitmap = SKBitmap.Decode(stream, desiredInfo))
                {
                    // draw directly on the bitmap
                    using (var annotationCanvas = new SKCanvas(bitmap))
                        using (var paint = new SKPaint())
                        {
                            paint.StrokeWidth = 3;
                            paint.Color       = SampleMedia.Colors.XamarinLightBlue;
                            paint.Style       = SKPaintStyle.Stroke;

                            var face = SKRectI.Create(100, 50, 190, 170);
                            annotationCanvas.DrawRect(face, paint);
                        }

                    // draw the modified bitmap to the screen
                    canvas.DrawBitmap(bitmap, 10, 10);
                }
        }
        internal static void SkiaCanvasLoadResizeSave(string path, int size, string outputDirectory)
        {
            using (var input = File.OpenRead(path))
                using (var inputStream = new SKManagedStream(input))
                    using (var original = SKBitmap.Decode(inputStream))
                    {
                        var scaled = ScaledSize(original.Width, original.Height, size);
                        using (var surface = SKSurface.Create(scaled.width, scaled.height, original.ColorType, original.AlphaType))
                            using (var paint = new SKPaint()
                            {
                                FilterQuality = SKFilterQuality.High
                            })
                            {
                                var canvas = surface.Canvas;
                                canvas.Scale((float)scaled.width / original.Width);
                                canvas.DrawBitmap(original, 0, 0, paint);
                                canvas.Flush();

                                using (var output = File.OpenWrite(OutputPath(path, outputDirectory, SkiaSharpCanvas)))
                                {
                                    surface.Snapshot()
                                    .Encode(SKEncodedImageFormat.Jpeg, Quality)
                                    .SaveTo(output);
                                }
                            }
                    }
        }
Beispiel #23
0
        public Asset([NotNull] string path)
        {
            Path = path ?? throw new ArgumentNullException(nameof(path));

            (FilenameWithoutQualifierAndExtension, Extension) = Path.WithoutQualifier();

            if (Densities.TryFind(path, out var foundDensity))
            {
                Density = foundDensity;
            }

            using (var input = File.Open(path, FileMode.Open))
                using (var memory = new MemoryStream())
                {
                    input.CopyTo(memory);
                    memory.Seek(0, SeekOrigin.Begin);
                    memory.Position = 0;

                    using (var stream = new SKManagedStream(memory))
                    {
                        _bitmap = SKBitmap.Decode(stream);

                        if (_bitmap == null)
                        {
                            throw new InvalidOperationException($"The provided image isn't valid: {path} (SKBitmap can't be created).");
                        }
                    }
                }
        }
Beispiel #24
0
        //convert file size to 500X500 and save it on disk
        public void SaveImage(IFormFile file, IHostingEnvironment env, string currentFolder)
        {
            string fileName = Path.GetFileName(file.FileName);

            fileName = DisplayUtils.RenameDuplicates(env, currentFolder, fileName);
            string filePath = Path.Combine(env.WebRootPath, currentFolder, fileName);

            var format = GetFormat(filePath);

            using (var imageStream = file.OpenReadStream())
                using (var inputStream = new SKManagedStream(imageStream))
                    using (var codec = SKCodec.Create(inputStream))
                        using (var original = SKBitmap.Decode(codec))
                            using (var image = HandleOrientation(original, codec.Origin))
                            //using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                            {
                                int width  = imageSize;
                                int height = (int)Math.Round(width * ((float)image.Height / image.Width));

                                var info = new SKImageInfo(width, height);

                                using (var resized = image.Resize(info, SKBitmapResizeMethod.Lanczos3))
                                    using (var thumb = SKImage.FromBitmap(resized))
                                        using (var fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite))
                                        {
                                            thumb.Encode(format, Quality)
                                            .SaveTo(fs);
                                        }


                                //imageProcessor.CreateThumbnails(imageStream, filePath);
                                //await file.CopyToAsync(fileStream);
                            }
        }
        public Page1()
        {
            InitializeComponent();

            if (Device.RuntimePlatform == Device.Android)
            {
                NavigationPage.SetHasNavigationBar(this, false);
            }

            // Load in all the available bitmaps
            Assembly assembly = GetType().GetTypeInfo().Assembly;

            string[] resourceIDs = assembly.GetManifestResourceNames();

            _smileyImagesList = new List <SKBitmap>();

            foreach (string resourceID in resourceIDs)
            {
                if (resourceID.EndsWith(".png") ||
                    resourceID.EndsWith(".jpg"))
                {
                    using (Stream stream = assembly.GetManifestResourceStream(resourceID))
                        using (SKManagedStream skStream = new SKManagedStream(stream))
                        {
                            SKBitmap bitmap = SKBitmap.Decode(skStream);

                            _smileyImagesList.Add(bitmap);
                        }
                }
            }

            _touchPoints = new List <SmileyImage>();
        }
Beispiel #26
0
 public AlphaCircleGraph()
 {
     //	※iOS 版では Font だけ残して他はこの場で Dispose() して構わないが Android 版では遅延処理が行われるようでそれだと disposed object へのアクセスが発生してしまう。
     FontSource = AlphaFactory.GetApp().GetFontStream();
     FontStream = new SKManagedStream(FontSource);
     Font       = SKTypeface.FromStream(FontStream);
 }
Beispiel #27
0
        public void load_bitmap(string url, int key)
        {
            Uri        uri     = new Uri(url);
            WebRequest request = WebRequest.Create(uri);

            request.BeginGetResponse((IAsyncResult arg) =>
            {
                try
                {
                    using (Stream stream = request.EndGetResponse(arg).GetResponseStream())
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            stream.CopyTo(memStream);
                            memStream.Seek(0, SeekOrigin.Begin);

                            using (SKManagedStream skStream = new SKManagedStream(memStream))
                            {
                                hours_weatherstatusthumb.AddOrUpdate(key, SKBitmap.Decode(skStream), (k, v) => v);
                                Device.BeginInvokeOnMainThread(() => CanvasView.InvalidateSurface());
                            }
                        }
                }
                catch
                {
                }
            }, null);
        }
Beispiel #28
0
        public Image(string path)
        {
            Stream fileStream = File.OpenRead(path);

            using (var stream = new SKManagedStream(fileStream))
                bitMap = SKBitmap.Decode(stream);
        }
        private static void ObtainFont()
        {
            byte[] font   = Resources.Properties.Resources.Chiaro;
            var    stream = new SKManagedStream(new MemoryStream(font));

            typeface = SKTypeface.FromStream(stream);
        }
Beispiel #30
0
        public void ManagedStreamReadsByteCorrectly()
        {
            var data = new byte[1024];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % byte.MaxValue);
            }

            var stream          = new MemoryStream(data);
            var skManagedStream = new SKManagedStream(stream);

            skManagedStream.Rewind();
            Assert.AreEqual(0, stream.Position);
            Assert.AreEqual(0, skManagedStream.Position);

            for (int i = 0; i < data.Length; i++)
            {
                skManagedStream.Position = i;

                Assert.AreEqual(i, stream.Position);
                Assert.AreEqual(i, skManagedStream.Position);

                Assert.AreEqual((byte)(i % byte.MaxValue), data[i]);
                Assert.AreEqual((byte)(i % byte.MaxValue), skManagedStream.ReadByte());

                Assert.AreEqual(i + 1, stream.Position);
                Assert.AreEqual(i + 1, skManagedStream.Position);
            }
        }
        public static byte[] ResizeImage(this string path, int size)
        {
            using var input       = File.OpenRead(path);
            using var inputStream = new SKManagedStream(input);
            using var original    = SKBitmap.Decode(inputStream);
            int width, height;

            if (original.Width > original.Height)
            {
                width  = size;
                height = original.Height * size / original.Width;
            }
            else
            {
                width  = original.Width * size / original.Height;
                height = size;
            }

            using var resized =
                      original.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3);

            if (resized == null)
            {
                return(null);
            }

            using var image = SKImage.FromBitmap(resized);


            return(image.Encode(SKEncodedImageFormat.Jpeg, 75).ToArray());
        }
Beispiel #32
0
        public void ManagedStreamReadsChunkCorrectly()
        {
            var data = new byte[1024];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % byte.MaxValue);
            }

            var stream = new MemoryStream(data);
            var skManagedStream = new SKManagedStream(stream);

            skManagedStream.Rewind();
            Assert.AreEqual(0, stream.Position);
            Assert.AreEqual(0, skManagedStream.Position);

            var buffer = new byte[data.Length / 2];
            skManagedStream.Read(buffer, buffer.Length);

            CollectionAssert.AreEqual(data.Take(buffer.Length), buffer);
        }
Beispiel #33
0
        public void ManagedStreamReadsOffsetChunkCorrectly()
        {
            var data = new byte[1024];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % byte.MaxValue);
            }

            var stream = new MemoryStream(data);
            var skManagedStream = new SKManagedStream(stream);

            var offset = 768;

            skManagedStream.Position = offset;

            var buffer = new byte[data.Length];
            var taken = skManagedStream.Read(buffer, buffer.Length);

            Assert.AreEqual(data.Length - offset, taken);

            var resultData = data.Skip(offset).Take(buffer.Length).ToArray();
            resultData = resultData.Concat(Enumerable.Repeat<byte>(0, offset)).ToArray();
            CollectionAssert.AreEqual(resultData, buffer);
        }