Beispiel #1
0
        public System.IO.Stream CombineImages(System.IO.Stream sourceImageStream, System.IO.Stream detailImageStream, Rect detailImageRect)
        {
            #region validation

            if (sourceImageStream == null)
            {
                throw new ArgumentNullException(nameof(sourceImageStream));
            }

            if (detailImageStream == null)
            {
                throw new ArgumentNullException(nameof(detailImageStream));
            }

            #endregion

            using (Image <Rgba32> sourceImage = LoadImageFromStream(sourceImageStream))
                using (Image <Rgba32> detailImage = LoadImageFromStream(detailImageStream))
                {
                    SixLabors.Primitives.Point detailImagePosition = new SixLabors.Primitives.Point(0, 0);
                    if (detailImageRect != null)
                    {
                        SixLabors.Primitives.Size detailImageSize = new SixLabors.Primitives.Size(detailImageRect.Width, detailImageRect.Height);
                        detailImage.Mutate(x => x.Resize(detailImageSize));

                        detailImagePosition = new SixLabors.Primitives.Point(detailImageRect.X, detailImageRect.Y);
                    }

                    sourceImage.Mutate(x => x.DrawImage(detailImage, 1.0f, detailImagePosition));

                    return(SaveAsStream(sourceImage));
                }
        }
        //public static IImageProcessingContext DrawTextWithHebrew(
        //    this IImageProcessingContext source,
        //    TextGraphicsOptions options,
        //    string text,
        //    Font font,
        //    Color color,
        //    PointF location)
        //{
        //    var textToApply = text;
        //    return source.DrawText(options, textToApply, font, color, location);
        //}


        public static IImageProcessingContext DrawText(
            this IImageProcessingContext source,
            string text,
            int fontSize,
            string color,
            Size size,
            SixLabors.Primitives.Point location)
        {
            using var myBitmap = new Bitmap(size.Width, size.Height + 10);

            var x = new Span <char>(text.ToCharArray());

            for (int i = x.Length - 1; i >= 0; i--)
            {
                if (char.IsPunctuation(x[i]) || char.IsSeparator(x[i]) || char.IsSymbol(x[i]))
                {
                    x = x.Slice(0, i);
                }
                else
                {
                    break;
                }
            }

            var textToDraw = new string(x);
            //pfcoll.AddFontFile(Server.MapPath("~/Fonts/" + fontName));
            //FontFamily ff = pfcoll.Families[0];
            var colorToWorkWith = ColorTranslator.FromHtml(color);

            using (var g = Graphics.FromImage(myBitmap))
            {
                g.SmoothingMode     = SmoothingMode.AntiAlias;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;

                //var colorToWorkWith = System.Drawing.Color.FromArgb(color.ToArgb());


                var brush = new System.Drawing.SolidBrush(colorToWorkWith);
                g.DrawString(textToDraw,
                             new Font("Calibri", fontSize, FontStyle.Regular, GraphicsUnit.Pixel),
                             brush,
                             new RectangleF(0, 0, size.Width, size.Height),
                             new StringFormat()
                {
                    Alignment = StringAlignment.Center,
                    Trimming  = StringTrimming.Word,
                });
                //g.DrawString("My Text very very nice",
                //    new Font("Tahoma", 20),
                //    Brushes.White,
                //    new PointF(0, 0));
            }

            using var ms = new MemoryStream();
            myBitmap.Save(ms, ImageFormat.Png);
            var image = Image.Load(ms.ToArray());

            return(source.DrawImage(image, location, GraphicsOptions.Default));
        }
Beispiel #3
0
        public void DrawImage(PointF position, SizeF size, ImageSharpTexture texture, float opacity)
        {
            var rect = ToRectangleF(new RectangleF(position, size), world);
            var s    = new SixLabors.Primitives.Size((int)rect.Width, (int)rect.Height);
            var p    = new SixLabors.Primitives.Point((int)rect.X, (int)rect.Y);

            commandQueue.Enqueue(ctx =>
            {
                ctx.DrawImage(texture.Image, opacity, s, p);
            });
        }
        public void RotatedEllipsesWithDifferentRatio <TPixel>(
            TestImageProvider <TPixel> provider,
            float ratio,
            float rotationInDegree)
            where TPixel : struct, IPixel <TPixel>
        {
            FormattableString variant = $"{ratio:F2}_AT_{rotationInDegree:00}deg";

            provider.VerifyOperation(
                TolerantComparer,
                image =>
            {
                TPixel yellow = NamedColors <TPixel> .Yellow;
                TPixel red    = NamedColors <TPixel> .Red;
                TPixel black  = NamedColors <TPixel> .Black;

                var center = new SixLabors.Primitives.Point(image.Width / 2, image.Height / 2);

                double rotation = (Math.PI * rotationInDegree) / 180.0;
                double cos      = Math.Cos(rotation);
                double sin      = Math.Sin(rotation);

                int offsetY = image.Height / 6;
                int axisX   = center.X + (int)-(offsetY * sin);
                int axisY   = center.Y + (int)(offsetY * cos);

                var unicolorLinearGradientBrush = new EllipticGradientBrush <TPixel>(
                    center,
                    new SixLabors.Primitives.Point(axisX, axisY),
                    ratio,
                    GradientRepetitionMode.None,
                    new ColorStop <TPixel>(0, yellow),
                    new ColorStop <TPixel>(1, red),
                    new ColorStop <TPixel>(1, black));

                image.Mutate(x => x.Fill(unicolorLinearGradientBrush));
            },
                variant,
                false,
                false);
        }
Beispiel #5
0
        /// <summary>
        /// 添加icon
        /// </summary>
        public static byte[] AddIcon(this QrCode coder, byte[] bs, string icon_path)
        {
            using (var ms = new MemoryStream())
            {
                using (var img = SixLabors.ImageSharp.Image.Load(bs))
                {
                    using (var icon = SixLabors.ImageSharp.Image.Load(icon_path))
                    {
                        icon.Mutate(x => x.Resize(width: img.Width / 5, height: img.Height / 5));

                        var location = new SixLabors.Primitives.Point()
                        {
                            X = (img.Width - icon.Width) / 2,
                            Y = (img.Height - icon.Height) / 2
                        };
                        img.Mutate(x => x.DrawImage(icon, 1, location));
                        img.Save(ms, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
                    }
                }
                return(ms.ToArray());
            }
        }
        /// <summary>
        /// Tries to allocate space for the given image
        /// If there is not enough space, returns null
        /// </summary>
        /// <param name="newImageData"></param>
        /// <returns></returns>
        public Vector2?TryAllocate(Image <Rgba32> newImageData)
        {
            if (newImageData == null)
            {
                throw new ArgumentException(nameof(newImageData));
            }

            if (newImageData.Width > _image.Width)
            {
                throw new ArgumentOutOfRangeException(nameof(newImageData), "Requested image width is too large");
            }

            if (newImageData.Height > _image.Height)
            {
                throw new ArgumentOutOfRangeException(nameof(newImageData), "Requested image height is too large");
            }

            var coordinates = new SixLabors.Primitives.Point();

            int mostAllocatedWholeImage = _image.Height;

            for (var startWidth = 0; startWidth < _allocated.Length - newImageData.Width; ++startWidth)
            {
                //Tracks the most allocations in a line; this is the starting point for the data if this section is valid
                int mostAllocated = 0;

                int currentWidth;

                for (currentWidth = 0; currentWidth < newImageData.Width; ++currentWidth)
                {
                    //Line is full
                    if (_allocated[startWidth + currentWidth] >= _image.Height)
                    {
                        break;
                    }

                    if (_allocated[startWidth + currentWidth] >= mostAllocated)
                    {
                        mostAllocated = _allocated[startWidth + currentWidth];
                    }
                }

                if (currentWidth == newImageData.Width)
                {
                    coordinates.X = startWidth;
                    coordinates.Y = mostAllocatedWholeImage = mostAllocated;
                }
            }

            if (mostAllocatedWholeImage + newImageData.Height <= _image.Height)
            {
                //There's room

                //Update allocated to cover image and padding between previous data on each line
                for (var x = 0; x < newImageData.Width; ++x)
                {
                    _allocated[coordinates.X + x] = mostAllocatedWholeImage + newImageData.Height;
                }

                var graphicsOptions = GraphicsOptions.Default;

                graphicsOptions.BlenderMode = PixelBlenderMode.Src;

                //Add the image data to the current lightmap image
                _image.Mutate(context => context.DrawImage(graphicsOptions, newImageData, coordinates));

                return(new Vector2(coordinates.X, coordinates.Y));
            }

            return(null);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public byte[] GetCaptcha(int length = 4)
        {
            var httpContext = _httpContextAccessor.HttpContext;

            if (httpContext == null)
            {
                throw new Exception("RecaptchaValidator should be used in a valid HTTP context!");
            }

            var random  = new Random();
            var captcha = random.Next((int)Math.Pow(10, length), (int)Math.Pow(10, length + 1))
                          .ToString()
                          .Substring(1);

            httpContext.Session.SetString(SessionKey, captcha);

            //颜色列表,用于验证码、噪线、噪点
            var colors = new[] { Rgba32.Black, Rgba32.Red, Rgba32.DarkBlue, Rgba32.Green, Rgba32.Orange, Rgba32.Brown, Rgba32.DarkCyan, Rgba32.Purple };
            //创建画布
            var imageWidth = captcha.Length * 13;

            using (var image = new Image <Rgba32>(imageWidth, 28))
            {
                //背景设为白色
                image.Mutate(x => x.BackgroundColor(Rgba32.White));

                //向画板中绘制贝塞尔样条
                for (var i = 0; i < 2; i++)
                {
                    var p1  = new PointF(0, random.Next(image.Height));
                    var p2  = new PointF(random.Next(image.Width), random.Next(image.Height));
                    var p3  = new PointF(random.Next(image.Width), random.Next(image.Height));
                    var p4  = new PointF(image.Width, random.Next(image.Height));
                    var clr = colors[random.Next(colors.Length)];
                    image.Mutate(x => x.DrawBeziers(
                                     GraphicsOptions.Default,
                                     new SolidBrush <Rgba32>(clr),
                                     1f,
                                     p1, p2, p3, p4));
                }
                //画噪点
                for (var i = 0; i < 50; i++)
                {
                    IBrush <Rgba32> brush = new SolidBrush <Rgba32>(Rgba32.LightGray);
                    Path            path  = new RegularPolygon(new PointF(random.Next(image.Width), random.Next(image.Height)), 3, 1);
                    image.Mutate(x => x.Draw(GraphicsOptions.Default, brush, 1f, path));
                }
                //画验证码字符串
                image.Mutate(x =>
                {
                    for (var i = 0; i < captcha.Length; i++)
                    {
                        var cindex = random.Next(colors.Length - 1);          //随机颜色索引值
                        var brush  = new SolidBrush <Rgba32>(colors[cindex]); //颜色
                        var ii     = random.Next(4, 8);                       // 控制验证码不在同一高度

                        x.DrawText(captcha[i].ToString(), _defaultFont, brush, new PointF(3 + (i * 12), ii));
                    }
                });
                using (var stream = new MemoryStream())
                {
                    image.Save(stream, new JpegEncoder());
                    stream.Seek(0, SeekOrigin.Begin);
                    return(stream.ToArray());
                }
            }
        }