void OnCanvasViewPaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs args)
        {
            SkiaSharp.SKImageInfo info    = args.Info;
            SkiaSharp.SKSurface   surface = args.Surface;
            SkiaSharp.SKCanvas    canvas  = surface.Canvas;
            canvas.Clear();
            SkiaSharp.SKRect bounds;
            SkiaSharp.SKPath path = SkiaSharp.SKPath.ParseSvgPathData((string)this.Resources["PathString"]);
            path.GetTightBounds(out bounds);
            SkiaSharp.SKPaint paint = new SkiaSharp.SKPaint
            {
                Style       = SkiaSharp.SKPaintStyle.Stroke,
                Color       = SkiaSharp.SKColors.Black,
                StrokeWidth = 10,
                StrokeCap   = SkiaSharp.SKStrokeCap.Round,
                StrokeJoin  = SkiaSharp.SKStrokeJoin.Round
            };
            canvas.Translate(info.Width / 2, info.Height / 2);

            canvas.Scale(info.Width / (bounds.Width + paint.StrokeWidth),
                         info.Height / (bounds.Height + paint.StrokeWidth));

            canvas.Translate(-bounds.MidX, -bounds.MidY);

            canvas.DrawPath(path, paint);
        }
示例#2
0
        public void Example1()
        {
            var filePath = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources\\shannon.webp");

            // Use SkiaSharp to load a WEBP image:
            var bmp = MemoryBitmap.Load(filePath, Codecs.SkiaCodec.Default);

            // Use OpenCV to resize the image:

            /*
             * bmp = bmp
             *  .WithOpenCv()
             *  .ToResizedMemoryBitmap(50, 50, OpenCvSharp.InterpolationFlags.Lanczos4);
             */

            using (var proxy = bmp.UsingOpenCv())
            {
                proxy.Mat.Circle(new OpenCvSharp.Point(150, 150), 35, OpenCvSharp.Scalar.Red, 10);

                // proxy.Mat.Blur(new OpenCvSharp.Size(4, 4));
                // OpenCvSharp.Cv2.Blur(proxy.Mat, proxy.Mat, new OpenCvSharp.Size(4, 4));
            }

            using (var proxy = bmp.UsingGDI())
            {
                // Use GDI to draw a triangle:
                var a = new System.Drawing.Point(5, 5);
                var b = new System.Drawing.Point(50, 50);
                var c = new System.Drawing.Point(5, 50);

                proxy.Canvas.DrawPolygon(System.Drawing.Pens.Red, new[] { a, b, c });
            }

            using (var proxy = bmp.UsingImageSharp())
            {
                proxy.Image.Mutate(ipc => ipc.DrawPolygon(SixLabors.ImageSharp.Color.Blue, 2, (50, 5), (50, 50), (5, 5)));
            }

            using (var proxy = bmp.UsingSkiaSharp())
            {
                var p0 = new SkiaSharp.SKPoint(5, 25);
                var p1 = new SkiaSharp.SKPoint(45, 25);

                using var skiaPaint = new SkiaSharp.SKPaint
                      {
                          TextSize    = 64.0f,
                          IsAntialias = true,
                          StrokeWidth = 20,
                          Color       = new SkiaSharp.SKColor(0, 255, 0),
                          Style       = SkiaSharp.SKPaintStyle.Fill
                      };

                proxy.Canvas.DrawLine(p0, p1, skiaPaint);
                proxy.Canvas.DrawText("SkiaSharp", new SkiaSharp.SKPoint(5, 200), skiaPaint);
            }

            // Use Imagesharp to save to PNG
            bmp.Save(AttachmentInfo.From("shannon.png"));
        }
示例#3
0
        public override TSize Measure(double availableWidth, double availableHeight)
        {
            var   fontSize   = (float)(Material.Font.Button * DeviceInfo.ScalingFactor);
            float textLength = 0;

            using (var paint = new SkiaSharp.SKPaint
            {
                TextSize = fontSize
            })
            {
                textLength = paint.MeasureText(View?.Text ?? "");
            }

            return(new TSize(DeviceInfo.ScalingFactor * MaterialBackgroundHeight + textLength, DeviceInfo.ScalingFactor * MaterialBackgroundHeight));
        }
示例#4
0
        public void DrawPrimitivesWithMultipleAdapters()
        {
            void _drawUsingMultipleDevices(SpanBitmap <Pixel.BGRA32> img)
            {
                var slice = img.Slice((10, 10, img.Width - 20, img.Height - 20)); // crop the source image with a 10 pixels margin

                // cast to OpenCV adapter to blur and find edges in the image.
                slice
                .WithOpenCv()
                .ApplyBlur((4, 4))
                .ApplyCanny(100, 200);

                // cast to GDI Adapter to draw primitives.
                slice.MutateAsGDI(dc =>
                {
                    var a = new System.Drawing.Point(5, 5);
                    var b = new System.Drawing.Point(50, 50);
                    var c = new System.Drawing.Point(5, 50);

                    var f = new System.Drawing.Font("arial", 30);

                    // draw a triangle
                    dc.DrawPolygon(System.Drawing.Pens.Yellow, new[] { a, b, c });
                    // draw text
                    dc.DrawString("GDI Text", f, System.Drawing.Brushes.Yellow, new System.Drawing.PointF(5, 60));
                });

                // cast to SkiaSharp Adapter to draw primitives.
                slice
                .WithSkiaSharp()
                .Draw
                    (canvas =>
                {
                    var p0 = new SkiaSharp.SKPoint(5, 120);
                    var p1 = new SkiaSharp.SKPoint(250, 120);

                    using var skiaPaint = new SkiaSharp.SKPaint
                          {
                              TextSize    = 64.0f,
                              IsAntialias = true,
                              StrokeWidth = 20,
                              Color       = new SkiaSharp.SKColor(0, 0, 255),
                              Style       = SkiaSharp.SKPaintStyle.Fill
                          };

                    canvas.DrawLine(p0, p1, skiaPaint);
                    canvas.DrawText("SkiaSharp Text", new SkiaSharp.SKPoint(5, 200), skiaPaint);
                });

                // cast to imagesharp Adapter to draw primitives
                slice.MutateAsImageSharp(ipc =>
                {
                    ipc.FillPolygon(SixLabors.ImageSharp.Color.Green, (5, 250), (50, 250), (5, 300));
                    ipc.DrawText("ImageSharp Text", SixLabors.Fonts.SystemFonts.CreateFont("Arial", 40), SixLabors.ImageSharp.Color.Green, new SixLabors.ImageSharp.PointF(80, 250));
                });

                // wpf

                /* not working yet
                 * slice
                 *  .WithWPF()
                 *  .Draw
                 *  (dc =>
                 *  {
                 *      dc.DrawEllipse(System.Windows.Media.Brushes.Red, null, new System.Windows.Point(5, 5), 10, 10);
                 *      dc.DrawEllipse(System.Windows.Media.Brushes.Blue, null, new System.Windows.Point(50, 50), 100, 100);
                 *  }
                 *  );*/
            }

            // load an image with Sixlabors Imagesharp, notice we use BGRA32 because RGBA32 is NOT supported by GDI.
            var img = SixLabors.ImageSharp.Image.Load <SixLabors.ImageSharp.PixelFormats.Bgra32>(ResourceInfo.From("shannon.jpg"));

            // render using multiple devices

            img.WriteAsSpanBitmap(self => _drawUsingMultipleDevices(self));

            // save the result back with ImageSharp

            AttachmentInfo
            .From("result.jpg")
            .WriteObject(f => img.Save(f));

            img.Dispose();
        }
示例#5
0
        /// <summary>
        /// Calculates the dimensions of the Legend. This includes the maximum width
        /// and height of a single entry, as well as the total width and height of
        /// the Legend.
        public void CalculateDimensions(SkiaSharp.SKPaint paint, ViewPortHandler viewPortHandler)
        {
            var   maxEntrySize    = GetMaximumEntrySize(paint);
            float defaultFormSize = FormSize.DpToPixel();
            float stackSpace      = StackSpace.DpToPixel();
            float formToTextSpace = FormToTextSpace.DpToPixel();
            float xEntrySpace     = XEntrySpace.DpToPixel();
            float yEntrySpace     = YEntrySpace.DpToPixel();
            var   wordWrapEnabled = WordWrapEnabled;
            var   entries         = Entries;
            int   entryCount      = entries.Count;

            TextWidthMax  = maxEntrySize.Width;
            TextHeightMax = maxEntrySize.Height;

            switch (Orientation)
            {
            case Orientation.Vertical:
            {
                float maxWidth = 0f, maxHeight = 0f, width = 0f;
                float labelLineHeight = paint.LineHeight();
                bool  wasStacked      = false;

                for (int i = 0; i < entryCount; i++)
                {
                    LegendEntry e           = entries[i];
                    var         drawingForm = e.Form != Form.None;
                    float       formSize    = float.IsNaN(e.FormSize)
                                    ? defaultFormSize
                                    : e.FormSize.DpToPixel();
                    var label = e.Label;
                    if (!wasStacked)
                    {
                        width = 0.0f;
                    }

                    if (drawingForm)
                    {
                        if (wasStacked)
                        {
                            width += stackSpace;
                        }
                        width += formSize;
                    }

                    // grouped forms have null labels
                    if (label != null)
                    {
                        var size = paint.MeasureWidth(label);
                        // make a step to the left
                        if (drawingForm && !wasStacked)
                        {
                            width += formToTextSpace;
                        }
                        else if (wasStacked)
                        {
                            maxWidth   = Math.Max(maxWidth, width);
                            maxHeight += labelLineHeight + yEntrySpace;
                            width      = 0.0f;
                            wasStacked = false;
                        }

                        width += size;

                        maxHeight += labelLineHeight + yEntrySpace;
                    }
                    else
                    {
                        wasStacked = true;
                        width     += formSize;
                        if (i < entryCount - 1)
                        {
                            width += stackSpace;
                        }
                    }

                    maxWidth = Math.Max(maxWidth, width);
                }

                NeededWidth  = maxWidth;
                NeededHeight = maxHeight;

                break;
            }

            case Orientation.Horizontal:
            {
                float labelLineHeight  = paint.LineHeight();
                float labelLineSpacing = paint.LineSpacing() + yEntrySpace;
                float contentWidth     = viewPortHandler.ContentWidth * MaxSizePercent;

                // Start calculating layout
                float maxLineWidth      = 0.0f;
                float currentLineWidth  = 0.0f;
                float requiredWidth     = 0.0f;
                int   stackedStartIndex = -1;

                CalculatedLabelBreakPoints.Clear();
                CalculatedLabelSizes.Clear();
                CalculatedLineSizes.Clear();

                for (int i = 0; i < entryCount; i++)
                {
                    LegendEntry e           = entries[i];
                    var         drawingForm = e.Form != Form.None;
                    float       formSize    = float.IsNaN(e.FormSize)
                                    ? defaultFormSize
                                    : e.FormSize.DpToPixel();
                    var label = e.Label;

                    CalculatedLabelBreakPoints.Add(false);

                    if (stackedStartIndex == -1)
                    {
                        // we are not stacking, so required width is for this label
                        // only
                        requiredWidth = 0.0f;
                    }
                    else
                    {
                        // add the spacing appropriate for stacked labels/forms
                        requiredWidth += stackSpace;
                    }

                    // grouped forms have null labels
                    if (label != null)
                    {
                        CalculatedLabelSizes.Add(paint.Measure(label));
                        requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0f;
                        requiredWidth += CalculatedLabelSizes[i].Width;
                    }
                    else
                    {
                        CalculatedLabelSizes.Add(new ChartSize(0, 0));
                        requiredWidth += drawingForm ? formSize : 0.0f;

                        if (stackedStartIndex == -1)
                        {
                            // mark this index as we might want to break here later
                            stackedStartIndex = i;
                        }
                    }

                    if (label != null || i == entryCount - 1)
                    {
                        float requiredSpacing = currentLineWidth == 0.0f ? 0.0f : xEntrySpace;

                        if (!wordWrapEnabled         // No word wrapping, it must fit.
                                                     // The line is empty, it must fit
                            || currentLineWidth == 0.0f
                            // It simply fits
                            || (contentWidth - currentLineWidth >=
                                requiredSpacing + requiredWidth))
                        {
                            // Expand current line
                            currentLineWidth += requiredSpacing + requiredWidth;
                        }
                        else
                        {         // It doesn't fit, we need to wrap a line
                            // Add current line size to array
                            CalculatedLineSizes.Add(new ChartSize(currentLineWidth, labelLineHeight));
                            maxLineWidth = Math.Max(maxLineWidth, currentLineWidth);

                            // Start a new line
                            CalculatedLabelBreakPoints.Insert(
                                stackedStartIndex > -1 ? stackedStartIndex
                                                    : i, true);
                            currentLineWidth = requiredWidth;
                        }

                        if (i == entryCount - 1)
                        {
                            // Add last line size to array
                            CalculatedLineSizes.Add(new ChartSize(currentLineWidth, labelLineHeight));
                            maxLineWidth = Math.Max(maxLineWidth, currentLineWidth);
                        }
                    }

                    stackedStartIndex = label != null ? -1 : stackedStartIndex;
                }

                NeededWidth  = maxLineWidth;
                NeededHeight = labelLineHeight
                               * (float)(CalculatedLineSizes.Count)
                               + labelLineSpacing *
                               (float)(CalculatedLineSizes.Count == 0
                                        ? 0
                                        : (CalculatedLineSizes.Count - 1));

                break;
            }
            }

            NeededHeight += YOffset;
            NeededWidth  += XOffset;
        }
示例#6
0
        /// <summary>
        /// 生成二维码(320*320)
        /// </summary>
        /// <param name="text">文本内容</param>
        /// <param name="format">保存格式</param>
        /// <param name="logoImgae">Logo图片(缩放到真实二维码区域尺寸的1/6)</param>
        /// <param name="keepWhiteBorderPixelVal">白边处理(负值表示不做处理,最大值不超过真实二维码区域的1/10)</param>
        /// <returns></returns>
        public static byte[] QRCoder(string text, SkiaSharp.SKEncodedImageFormat format, byte[] logoImgae = null, int keepWhiteBorderPixelVal = -1)
        {
            byte[] reval        = null;
            int    width        = 320;
            int    height       = 320;
            var    qRCodeWriter = new ZXing.QrCode.QRCodeWriter();
            var    hints        = new Dictionary <ZXing.EncodeHintType, object>();

            hints.Add(ZXing.EncodeHintType.CHARACTER_SET, "utf-8");
            hints.Add(ZXing.EncodeHintType.QR_VERSION, 8);
            hints.Add(ZXing.EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.Q);
            var bitMatrix = qRCodeWriter.encode(text, ZXing.BarcodeFormat.QR_CODE, width, height, hints);
            var w         = bitMatrix.Width;
            var h         = bitMatrix.Height;
            var sKBitmap  = new SkiaSharp.SKBitmap(w, h);

            int blackStartPointX = 0;
            int blackStartPointY = 0;
            int blackEndPointX   = w;
            int blackEndPointY   = h;

            #region --绘制二维码(同时获取真实的二维码区域起绘点和结束点的坐标)--
            var sKCanvas     = new SkiaSharp.SKCanvas(sKBitmap);
            var sKColorBlack = SkiaSharp.SKColor.Parse("000000");
            var sKColorWihte = SkiaSharp.SKColor.Parse("ffffff");
            sKCanvas.Clear(sKColorWihte);
            bool blackStartPointIsNotWriteDown = true;
            for (var y = 0; y < h; y++)
            {
                for (var x = 0; x < w; x++)
                {
                    var flag = bitMatrix[x, y];
                    if (flag)
                    {
                        if (blackStartPointIsNotWriteDown)
                        {
                            blackStartPointX = x;
                            blackStartPointY = y;
                            blackStartPointIsNotWriteDown = false;
                        }
                        blackEndPointX = x;
                        blackEndPointY = y;
                        sKCanvas.DrawPoint(x, y, sKColorBlack);
                    }
                    else
                    {
                        //sKCanvas.DrawPoint(x, y, sKColorWihte);//不用绘制(背景是白色的)
                    }
                }
            }
            sKCanvas.Dispose();
            #endregion

            int qrcodeRealWidth  = blackEndPointX - blackStartPointX;
            int qrcodeRealHeight = blackEndPointY - blackStartPointY;

            #region -- 处理白边 --
            if (keepWhiteBorderPixelVal > -1)//指定了边框宽度
            {
                var borderMaxWidth = (int)Math.Floor((double)qrcodeRealWidth / 10);
                if (keepWhiteBorderPixelVal > borderMaxWidth)
                {
                    keepWhiteBorderPixelVal = borderMaxWidth;
                }
                var nQrcodeRealWidth  = width - keepWhiteBorderPixelVal - keepWhiteBorderPixelVal;
                var nQrcodeRealHeight = height - keepWhiteBorderPixelVal - keepWhiteBorderPixelVal;

                var sKBitmap2 = new SkiaSharp.SKBitmap(width, height);
                var sKCanvas2 = new SkiaSharp.SKCanvas(sKBitmap2);
                sKCanvas2.Clear(sKColorWihte);
                //二维码绘制到临时画布上时无需抗锯齿等处理(避免文件增大)
                sKCanvas2.DrawBitmap(
                    sKBitmap,
                    new SkiaSharp.SKRect
                {
                    Location = new SkiaSharp.SKPoint {
                        X = blackStartPointX, Y = blackStartPointY
                    },
                    Size = new SkiaSharp.SKSize {
                        Height = qrcodeRealHeight, Width = qrcodeRealWidth
                    }
                },
                    new SkiaSharp.SKRect
                {
                    Location = new SkiaSharp.SKPoint {
                        X = keepWhiteBorderPixelVal, Y = keepWhiteBorderPixelVal
                    },
                    Size = new SkiaSharp.SKSize {
                        Width = nQrcodeRealWidth, Height = nQrcodeRealHeight
                    }
                });

                blackStartPointX = keepWhiteBorderPixelVal;
                blackStartPointY = keepWhiteBorderPixelVal;
                qrcodeRealWidth  = nQrcodeRealWidth;
                qrcodeRealHeight = nQrcodeRealHeight;

                sKCanvas2.Dispose();
                sKBitmap.Dispose();
                sKBitmap = sKBitmap2;
            }
            #endregion

            #region -- 绘制LOGO --
            if (logoImgae != null && logoImgae.Length > 0)
            {
                SkiaSharp.SKBitmap sKBitmapLogo = SkiaSharp.SKBitmap.Decode(logoImgae);
                if (!sKBitmapLogo.IsEmpty)
                {
                    var sKPaint2 = new SkiaSharp.SKPaint
                    {
                        FilterQuality = SkiaSharp.SKFilterQuality.None,
                        IsAntialias   = true
                    };
                    var logoTargetMaxWidth  = (int)Math.Floor((double)qrcodeRealWidth / 6);
                    var logoTargetMaxHeight = (int)Math.Floor((double)qrcodeRealHeight / 6);
                    var qrcodeCenterX       = (int)Math.Floor((double)qrcodeRealWidth / 2);
                    var qrcodeCenterY       = (int)Math.Floor((double)qrcodeRealHeight / 2);
                    var logoResultWidth     = sKBitmapLogo.Width;
                    var logoResultHeight    = sKBitmapLogo.Height;
                    if (logoResultWidth > logoTargetMaxWidth)
                    {
                        var r = (double)logoTargetMaxWidth / logoResultWidth;
                        logoResultWidth  = logoTargetMaxWidth;
                        logoResultHeight = (int)Math.Floor(logoResultHeight * r);
                    }
                    if (logoResultHeight > logoTargetMaxHeight)
                    {
                        var r = (double)logoTargetMaxHeight / logoResultHeight;
                        logoResultHeight = logoTargetMaxHeight;
                        logoResultWidth  = (int)Math.Floor(logoResultWidth * r);
                    }
                    var pointX = qrcodeCenterX - (int)Math.Floor((double)logoResultWidth / 2) + blackStartPointX;
                    var pointY = qrcodeCenterY - (int)Math.Floor((double)logoResultHeight / 2) + blackStartPointY;

                    var sKCanvas3 = new SkiaSharp.SKCanvas(sKBitmap);
                    var sKPaint   = new SkiaSharp.SKPaint
                    {
                        FilterQuality = SkiaSharp.SKFilterQuality.Medium,
                        IsAntialias   = true
                    };
                    sKCanvas3.DrawBitmap(
                        sKBitmapLogo,
                        new SkiaSharp.SKRect
                    {
                        Location = new SkiaSharp.SKPoint {
                            X = 0, Y = 0
                        },
                        Size = new SkiaSharp.SKSize {
                            Height = sKBitmapLogo.Height, Width = sKBitmapLogo.Width
                        }
                    },
                        new SkiaSharp.SKRect
                    {
                        Location = new SkiaSharp.SKPoint {
                            X = pointX, Y = pointY
                        },
                        Size = new SkiaSharp.SKSize {
                            Height = logoResultHeight, Width = logoResultWidth
                        }
                    }, sKPaint);
                    sKCanvas3.Dispose();
                    sKPaint.Dispose();
                    sKBitmapLogo.Dispose();
                }
                else
                {
                    sKBitmapLogo.Dispose();
                }
            }
            #endregion

            SkiaSharp.SKImage sKImage = SkiaSharp.SKImage.FromBitmap(sKBitmap);
            sKBitmap.Dispose();
            var data = sKImage.Encode(format, 75);
            sKImage.Dispose();
            reval = data.ToArray();
            data.Dispose();

            return(reval);
        }
示例#7
0
        public static byte[] ImageScalingByOversized(string path, int maxWidth, int maxHeight, int quality)
        {
            byte[] bytes = null;
            if (!System.IO.File.Exists(path))
            {
                return(bytes);
            }
            var fileStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

            if (fileStream.Length > maxLength)
            {
                fileStream.Dispose();
                return(bytes);
            }
            var sKManagedStream = new SkiaSharp.SKManagedStream(fileStream, true);
            var sKBitmap        = SkiaSharp.SKBitmap.Decode(sKManagedStream);

            sKManagedStream.Dispose();

            if (sKBitmap.IsEmpty)
            {
                return(bytes);
            }

            if (maxWidth < 1)
            {
                maxWidth = 1;
            }
            if (maxHeight < 1)
            {
                maxHeight = 1;
            }
            if (quality < 1)
            {
                quality = 1;
            }
            if (quality > 100)
            {
                quality = 100;
            }

            int oW = sKBitmap.Width;
            int oH = sKBitmap.Height;
            int nW = oW;
            int nH = oH;

            if (oW > maxWidth || oH > maxHeight)
            {
                nW = maxWidth;
                nH = maxHeight;
                double ratio = 1;

                if (nW > 0 && nH > 0)
                {
                    ratio = (double)nW / oW;
                    nH    = Convert.ToInt32(oH * ratio);
                    if (maxHeight < nH)
                    {
                        ratio = (double)maxHeight / nH;
                        nW    = Convert.ToInt32(nW * ratio);
                        nH    = maxHeight;
                    }
                }
                if (nW < 1 && nH < 1)
                {
                    nW = oW;
                    nH = oH;
                }
                if (nW < 1)
                {
                    ratio = (double)nH / oH;
                    nW    = Convert.ToInt32(oW * ratio);
                }
                if (nH < 1)
                {
                    ratio = (double)nW / oW;
                    nH    = Convert.ToInt32(oH * ratio);
                }
                var sKBitmap2 = new SkiaSharp.SKBitmap(nW, nH);
                var sKCanvas  = new SkiaSharp.SKCanvas(sKBitmap2);
                var sKPaint   = new SkiaSharp.SKPaint
                {
                    FilterQuality = SkiaSharp.SKFilterQuality.Medium,
                    IsAntialias   = true
                };
                sKCanvas.DrawBitmap(
                    sKBitmap,
                    new SkiaSharp.SKRect
                {
                    Location = new SkiaSharp.SKPoint {
                        X = 0, Y = 0
                    },
                    Size = new SkiaSharp.SKSize {
                        Height = oH, Width = oW
                    }
                },
                    new SkiaSharp.SKRect
                {
                    Location = new SkiaSharp.SKPoint {
                        X = 0, Y = 0
                    },
                    Size = new SkiaSharp.SKSize {
                        Height = nH, Width = nW
                    }
                }, sKPaint);
                sKCanvas.Dispose();
                sKBitmap.Dispose();
                sKBitmap = sKBitmap2;
            }

            var sKImage = SkiaSharp.SKImage.FromBitmap(sKBitmap);

            sKBitmap.Dispose();
            var data = sKImage.Encode(GetImageFormatByPath(path), quality);

            sKImage.Dispose();
            bytes = data.ToArray();
            data.Dispose();

            return(bytes);
        }
示例#8
0
        public static byte[] ImageScalingToRange(string path, int maxWidth, int maxHeight, int quality)
        {
            byte[] bytes = null;
            if (!System.IO.File.Exists(path))
            {
                return(bytes);
            }
            var fileStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); //fileInfo.OpenRead();

            if (fileStream.Length > maxLength)
            {
                fileStream.Dispose();
                return(bytes);
            }
            var sKManagedStream = new SkiaSharp.SKManagedStream(fileStream, true);
            var sKBitmap        = SkiaSharp.SKBitmap.Decode(sKManagedStream);

            sKManagedStream.Dispose();

            if (sKBitmap.IsEmpty)
            {
                return(bytes);
            }

            if (maxWidth < 1)
            {
                maxWidth = 1;
            }
            if (maxHeight < 1)
            {
                maxHeight = 1;
            }
            if (quality < 1)
            {
                quality = 1;
            }
            if (quality > 100)
            {
                quality = 100;
            }

            int oW = sKBitmap.Width;
            int oH = sKBitmap.Height;
            int nW = oW;
            int nH = oH;

            if (nW < maxWidth && nH < maxHeight)//放大
            {
                if (nW < maxWidth)
                {
                    var r = (double)maxWidth / (double)nW;
                    nW = maxWidth;
                    nH = (int)Math.Floor((double)nH * r);
                }
                if (nH < maxHeight)
                {
                    var r = (double)maxHeight / (double)nH;
                    nH = maxHeight;
                    nW = (int)Math.Floor((double)nW * r);
                }
            }
            //限制超出(缩小)
            if (nW > maxWidth)
            {
                var r = (double)maxWidth / (double)nW;
                nW = maxWidth;
                nH = (int)Math.Floor((double)nH * r);
            }
            if (nH > maxHeight)
            {
                var r = (double)maxHeight / (double)nH;
                nH = maxHeight;
                nW = (int)Math.Floor((double)nW * r);
            }


            var sKBitmap2 = new SkiaSharp.SKBitmap(nW, nH);
            var sKCanvas  = new SkiaSharp.SKCanvas(sKBitmap2);
            var sKPaint   = new SkiaSharp.SKPaint
            {
                FilterQuality = SkiaSharp.SKFilterQuality.Medium,
                IsAntialias   = true
            };

            sKCanvas.DrawBitmap(
                sKBitmap,
                new SkiaSharp.SKRect
            {
                Location = new SkiaSharp.SKPoint {
                    X = 0, Y = 0
                },
                Size = new SkiaSharp.SKSize {
                    Height = oH, Width = oW
                }
            },
                new SkiaSharp.SKRect
            {
                Location = new SkiaSharp.SKPoint {
                    X = 0, Y = 0
                },
                Size = new SkiaSharp.SKSize {
                    Height = nH, Width = nW
                }
            }, sKPaint);
            sKCanvas.Dispose();
            var sKImage2 = SkiaSharp.SKImage.FromBitmap(sKBitmap2);

            sKBitmap2.Dispose();
            var data = sKImage2.Encode(GetImageFormatByPath(path), quality);

            sKImage2.Dispose();
            bytes = data.ToArray();
            data.Dispose();

            return(bytes);
        }
示例#9
0
        public static byte[] ImageMaxCutByCenter(string path, int saveWidth, int saveHeight, int quality)
        {
            byte[] bytes = null;
            if (!System.IO.File.Exists(path))
            {
                return(bytes);
            }
            var fileStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); //fileInfo.OpenRead();

            if (fileStream.Length > maxLength)
            {
                fileStream.Dispose();
                return(bytes);
            }
            var sKManagedStream = new SkiaSharp.SKManagedStream(fileStream, true);
            var sKBitmap        = SkiaSharp.SKBitmap.Decode(sKManagedStream);

            sKManagedStream.Dispose();

            if (sKBitmap.IsEmpty)
            {
                return(bytes);
            }

            if (saveWidth < 1)
            {
                saveWidth = 1;
            }
            if (saveHeight < 1)
            {
                saveHeight = 1;
            }
            if (quality < 1)
            {
                quality = 1;
            }
            if (quality > 100)
            {
                quality = 100;
            }

            int    oW    = sKBitmap.Width;
            int    oH    = sKBitmap.Height;
            int    cutW  = saveWidth;
            int    cutH  = saveHeight;
            double ratio = 1;

            if (cutW > oW)
            {
                ratio = (double)oW / (double)cutW;
                cutH  = Convert.ToInt32((double)cutH * ratio);
                cutW  = oW;
                if (cutH > oH)
                {
                    ratio = (double)oH / (double)cutH;
                    cutW  = Convert.ToInt32((double)cutW * ratio);
                    cutH  = oH;
                }
            }
            else if (cutW < oW)
            {
                ratio = (double)oW / (double)cutW;
                cutH  = Convert.ToInt32(Convert.ToDouble(cutH) * ratio);
                cutW  = oW;
                if (cutH > oH)
                {
                    ratio = (double)oH / (double)cutH;
                    cutW  = Convert.ToInt32((double)cutW * ratio);
                    cutH  = oH;
                }
            }
            else
            {
                if (cutH > oH)
                {
                    ratio = (double)oH / (double)cutH;
                    cutW  = Convert.ToInt32((double)cutW * ratio);
                    cutH  = oH;
                }
            }
            int startX = oW > cutW ? (oW / 2 - cutW / 2) : (cutW / 2 - oW / 2);
            int startY = oH > cutH ? (oH / 2 - cutH / 2) : (cutH / 2 - oH / 2);

            var sKBitmap2 = new SkiaSharp.SKBitmap(saveWidth, saveHeight);
            var sKCanvas  = new SkiaSharp.SKCanvas(sKBitmap2);
            var sKPaint   = new SkiaSharp.SKPaint
            {
                FilterQuality = SkiaSharp.SKFilterQuality.Medium,
                IsAntialias   = true
            };

            sKCanvas.DrawBitmap(
                sKBitmap,
                new SkiaSharp.SKRect
            {
                Location = new SkiaSharp.SKPoint {
                    X = startX, Y = startY
                },
                Size = new SkiaSharp.SKSize {
                    Height = cutH, Width = cutW
                }
            },
                new SkiaSharp.SKRect
            {
                Location = new SkiaSharp.SKPoint {
                    X = 0, Y = 0
                },
                Size = new SkiaSharp.SKSize {
                    Height = saveHeight, Width = saveWidth
                }
            }, sKPaint);
            sKCanvas.Dispose();
            var sKImage2 = SkiaSharp.SKImage.FromBitmap(sKBitmap2);

            sKBitmap2.Dispose();
            var data = sKImage2.Encode(GetImageFormatByPath(path), quality);

            sKImage2.Dispose();
            bytes = data.ToArray();
            data.Dispose();

            return(bytes);
        }
示例#10
0
 public static void DrawVerticalLine(this SkiaSharp.SKCanvas canvas, System.Windows.Point begin, System.Windows.Point end, SkiaSharp.SKPaint paint)
 {
 }
示例#11
0
 public static void DrawLineThroughPoints(this SkiaSharp.SKCanvas canvas, System.Collections.Generic.IEnumerable <System.Windows.Point> points, SkiaSharp.SKPaint paint)
 {
 }
示例#12
0
 public ChartFont(SkiaSharp.SKFont font)
 {
     Value = new SkiaSharp.SKPaint(font);
 }