Exemplo n.º 1
0
        static ImageSharp.Image ISImageFromDDS(Dds dds)
        {
            var isi = new ImageSharp.Image(dds.Width, dds.Height);

            isi.SetPixels(dds.Width, dds.Height, DataToColors(dds.Data, dds.BytesPerPixel));
            return(isi);
        }
        internal static void ImageSharpResize(string path, int size, string outputDirectory)
        {
            using (var input = File.OpenRead(path))
            {
                using (var output = File.Open(OutputPath(path, outputDirectory, ImageSharp), FileMode.Create))
                {
                    // Resize it to fit a 150x150 square
                    using (var image = new ImageSharpImage(input))
                    {
                        image.Resize(new ResizeOptions
                        {
                            Size = new ImageSharpSize(size, size),
                            Mode = ResizeMode.Max
                        });

                        // Reduce the size of the file
                        image.MetaData.ExifProfile = null;

                        // Set the quality
                        image.MetaData.Quality = Quality;

                        // Save the results
                        image.Save(output);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public async Task RotateRoleColor(int timeout, IRole role, params string[] hexes)
        {
            var channel = (ITextChannel)Context.Channel;

            if ((timeout < 60 && timeout != 0) || timeout > 3600)
                return;

            Timer t;
            if (timeout == 0 || hexes.Length == 0)
            {
                if (_rotatingRoleColors.TryRemove(role.Id, out t))
                {
                    t.Change(Timeout.Infinite, Timeout.Infinite);
                    await ReplyConfirmLocalized("rrc_stop", Format.Bold(role.Name)).ConfigureAwait(false);
                }
                return;
            }
            
            var hexColors = hexes.Select(hex =>
            {
                try { return (ImageSharp.Color?)ImageSharp.Color.FromHex(hex.Replace("#", "")); } catch { return null; }
            })
            .Where(c => c != null)
            .Select(c => c.Value)
            .ToArray();

            if (!hexColors.Any())
            {
                await ReplyErrorLocalized("rrc_no_colors").ConfigureAwait(false);
                return;
            }

            var images = hexColors.Select(color =>
            {
                var img = new ImageSharp.Image(50, 50);
                img.BackgroundColor(color);
                return img;
            }).Merge().ToStream();

            var i = 0;
            t = new Timer(async (_) =>
            {
                try
                {
                    var color = hexColors[i];
                    await role.ModifyAsync(r => r.Color = new Discord.Color(color.R, color.G, color.B)).ConfigureAwait(false);
                    ++i;
                    if (i >= hexColors.Length)
                        i = 0;
                }
                catch { }
            }, null, 0, timeout * 1000);

            _rotatingRoleColors.AddOrUpdate(role.Id, t, (key, old) =>
            {
                old.Change(Timeout.Infinite, Timeout.Infinite);
                return t;
            });
            await channel.SendFileAsync(images, "magicalgirl.jpg", GetText("rrc_start", Format.Bold(role.Name))).ConfigureAwait(false);
        }
Exemplo n.º 4
0
            public async Task Flip(int count = 1)
            {
                if (count == 1)
                {
                    if (rng.Next(0, 2) == 1)
                    {
                        await Context.Channel.SendFileAsync(File.Open(headsPath, FileMode.OpenOrCreate), "heads.jpg", $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false);
                    }
                    else
                    {
                        await Context.Channel.SendFileAsync(File.Open(tailsPath, FileMode.OpenOrCreate), "tails.jpg", $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false);
                    }
                    return;
                }
                if (count > 10 || count < 1)
                {
                    await Context.Channel.SendErrorAsync("`Invalid number specified. You can flip 1 to 10 coins.`");

                    return;
                }
                var imgs = new Image[count];

                for (var i = 0; i < count; i++)
                {
                    imgs[i] = rng.Next(0, 10) < 5 ?
                              new Image(File.OpenRead(headsPath)) :
                              new Image(File.OpenRead(tailsPath));
                }
                await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false);
            }
Exemplo n.º 5
0
        public async Task <Image <Rgba32> > GetRipPictureAsync(string text, string imgUrl)
        {
            var(succ, data) = await _cache.TryGetImageDataAsync(imgUrl);

            if (!succ)
            {
                using (var temp = await Http.GetAsync(imgUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    if (temp.Content.Headers.ContentType.MediaType != "image/png" &&
                        temp.Content.Headers.ContentType.MediaType != "image/jpeg" &&
                        temp.Content.Headers.ContentType.MediaType != "image/gif")
                    {
                        data = null;
                    }
                    else
                    {
                        using (var tempDraw = ImageSharp.Image.Load(await temp.Content.ReadAsStreamAsync()).Resize(69, 70))
                        {
                            tempDraw.ApplyRoundedCorners(35);
                            data = tempDraw.ToStream().ToArray();
                        }
                    }
                }

                await _cache.SetImageDataAsync(imgUrl, data);
            }
            var bg = ImageSharp.Image.Load(_imgs.Rip.ToArray());

            //avatar 82, 139
            if (data != null)
            {
                using (var avatar = Image.Load(data).Resize(85, 85))
                {
                    bg.DrawImage(avatar,
Exemplo n.º 6
0
 private Size LoadPng(MemoryStream stream)
 {
     using (Image <Rgba32> image = CoreImage.Load <Rgba32>(stream))
     {
         return(new Size(image.Width, image.Height));
     }
 }
Exemplo n.º 7
0
        public static Stream ToStream(this ImageSharp.Image img)
        {
            var imageStream = new MemoryStream();

            img.Save(imageStream);
            imageStream.Position = 0;
            return(imageStream);
        }
Exemplo n.º 8
0
 public ImageSharpSize ResizeImageSharp()
 {
     using (var image = new ImageSharpImage(Width, Height))
     {
         image.Resize(ResizedWidth, ResizedHeight);
     }
     return(new ImageSharpSize(ResizedWidth, ResizedHeight));
 }
Exemplo n.º 9
0
 public void ReadImages()
 {
     if (this.bmpStream == null)
     {
         string path = this.LargeImage
                           ? "../ImageSharp.Tests/TestImages/Formats/Jpg/baseline/jpeg420exif.jpg"
                           : "../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp";
         this.bmpStream          = File.OpenRead(path);
         this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
         this.bmpStream.Position = 0;
     }
 }
Exemplo n.º 10
0
        public async Task Color([Remainder] string color = null)
        {
            color = color?.Trim().Replace("#", "");
            if (string.IsNullOrWhiteSpace(color))
            {
                return;
            }
            var img = new ImageSharp.Image(50, 50);

            img.BackgroundColor(new ImageSharp.Color(color));

            await Context.Channel.SendFileAsync(img.ToStream(), $"{color}.png").ConfigureAwait(false);;
        }
Exemplo n.º 11
0
        public MemoryStream SpoilerTxt(string spoil)
        {
            var             fill  = Brushes.Solid <Rgba32>(Rgba32.Black);
            var             brush = Brushes.Solid <Rgba32>(Rgba32.White);
            RendererOptions op    = new RendererOptions(_Spoiltxt);
            var             text  = WordWrap(spoil, 120);
            var             tsize = TextMeasurer.MeasureBounds(text, op);

            int[] size = { Convert.ToInt32(tsize.Width) + 20, Convert.ToInt32(tsize.Height) + 20 };
            var   img2 = new Image <Rgba32>(size[0], size[1]);

            img2.DrawText(text, _Spoiltxt, brush, new PointF(0, 0), new TextGraphicsOptions(true));
            img2.BackgroundColor(Rgba32.Black);
            var img1 = new Image <Rgba32>(img2.Width, img2.Height);

            _Spoil = _fonts.Find("Whitney-Bold").CreateFont(img2.Width * 0.064f);
            var rect = new Rectangle(0, 0, img2.Width, img2.Height);

            img1.BackgroundColor(Rgba32.Black, rect);
            img1.DrawText("Spoiler Warning" + "\r\n" + "(Mouse over to view)", _Spoil, brush, new PointF(0, 0), new TextGraphicsOptions(true)
            {
                WrapTextWidth = img1.Width - 20
            });
            MagickImage f1 = new MagickImage(img1.ToStream());
            MagickImage f2 = new MagickImage(img2.ToStream());

            MagickImage[] frames = { f1, f2 };
            MemoryStream  ms     = new MemoryStream();

            using (MagickImageCollection gif = new MagickImageCollection())
            {
                gif.Add(f1);
                gif.Add(f2);

                for (int i = 0; i < gif.Count; i++)
                {
                    gif[i].AnimationDelay      = 50;
                    gif[i].AnimationIterations = 1;
                }
                QuantizeSettings settings = new QuantizeSettings
                {
                    Colors       = 256,
                    DitherMethod = DitherMethod.No
                };
                gif.Quantize(settings);
                gif.Optimize();
                gif.Write(ms, MagickFormat.Gif);
                ms.Position = 0;
            }
            return(ms);
        }
Exemplo n.º 12
0
            public GirlRating(double crazy, double hot, int roll, string advice)
            {
                Crazy  = crazy;
                Hot    = hot;
                Roll   = roll;
                Advice = advice; // convenient to have it here, even though atm there are only few different ones.

                Url = new AsyncLazy <string>(async() =>
                {
                    try
                    {
                        using (var ms = new MemoryStream(NadekoBot.Images.WifeMatrix.ToArray(), false))
                            using (var img = new ImageSharp.Image(ms))
                            {
                                var clr          = new ImageSharp.Color(0x0000ff);
                                const int minx   = 35;
                                const int miny   = 385;
                                const int length = 345;

                                var pointx = (int)(minx + length * (Hot / 10));
                                var pointy = (int)(miny - length * ((Crazy - 4) / 6));

                                var p = new Pen(ImageSharp.Color.Red, 5);
                                //using (var pointMs = File.ReadAllBytes("data/images/point.png").ToStream())
                                //using (var pointIMg = new ImageSharp.Image(pointMs))
                                //{
                                //    img.DrawImage(pointIMg, 100, new ImageSharp.Size(100, 100), new Point(pointx, pointy));
                                //}

                                string url;
                                using (var http = new HttpClient())
                                    using (var imgStream = new MemoryStream())
                                    {
                                        img.Save(imgStream);
                                        var byteContent = new ByteArrayContent(imgStream.ToArray());
                                        http.AddFakeHeaders();

                                        var reponse = await http.PutAsync("https://transfer.sh/img.png", byteContent);
                                        url         = await reponse.Content.ReadAsStringAsync();
                                    }
                                return(url);
                            }
                    }
                    catch (Exception ex)
                    {
                        _log.Warn(ex);
                        return(null);
                    }
                });
            }
Exemplo n.º 13
0
        static unsafe int MakeMipLevel(ImageSharp.Image isi, uint *odata, int miplevel, int offset, bool resampleAlpha)
        {
            var colors = (miplevel == 0 ? isi : isi.Resize(isi.Width >> 1, isi.Height >> 1, new Lanczos2Resampler(), true)).Pixels;

            for (var i = 0; i < colors.Length; ++i)
            {
                if (resampleAlpha && miplevel > 0)
                {
                    colors[i].A = (byte)(colors[i].A * .9);
                }
                odata[i + offset] = colors[i].PackedValue;
            }
            return(colors.Length);
        }
Exemplo n.º 14
0
        public static ImageSharp.Image Merge(this IEnumerable <ImageSharp.Image> images)
        {
            var imgs = images.ToArray();

            var canvas = new ImageSharp.Image(imgs.Sum(img => img.Width), imgs.Max(img => img.Height));

            var xOffset = 0;

            for (int i = 0; i < imgs.Length; i++)
            {
                canvas.DrawImage(imgs[i], 100, default(Size), new Point(xOffset, 0));
                xOffset += imgs[i].Bounds.Width;
            }

            return(canvas);
        }
Exemplo n.º 15
0
            public async Task Flip(int count = 1)
            {
                if (count == 1)
                {
                    var coins = _images.ImageUrls.Coins;
                    if (rng.Next(0, 2) == 1)
                    {
                        await Context.Channel.EmbedAsync(new EmbedBuilder()
                                                         .WithOkColor()
                                                         .WithImageUrl(coins.Heads[rng.Next(0, coins.Heads.Length)])
                                                         .WithDescription(Context.User.Mention + " " + GetText("flipped", Format.Bold(GetText("heads")))));
                    }
                    else
                    {
                        await Context.Channel.EmbedAsync(new EmbedBuilder()
                                                         .WithOkColor()
                                                         .WithImageUrl(coins.Tails[rng.Next(0, coins.Tails.Length)])
                                                         .WithDescription(Context.User.Mention + " " + GetText("flipped", Format.Bold(GetText("tails")))));
                    }
                    return;
                }
                if (count > 10 || count < 1)
                {
                    await ReplyErrorLocalized("flip_invalid", 10).ConfigureAwait(false);

                    return;
                }
                var imgs = new Image <Rgba32> [count];

                for (var i = 0; i < count; i++)
                {
                    using (var heads = _images.Heads[rng.Next(0, _images.Heads.Length)].ToStream())
                        using (var tails = _images.Tails[rng.Next(0, _images.Tails.Length)].ToStream())
                        {
                            if (rng.Next(0, 10) < 5)
                            {
                                imgs[i] = Image.Load(heads);
                            }
                            else
                            {
                                imgs[i] = Image.Load(tails);
                            }
                        }
                }
                await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false);
            }
Exemplo n.º 16
0
        public async Task Color([Remainder] string color = null)
        {
            color = color?.Trim().Replace("#", "");
            if (string.IsNullOrWhiteSpace((string)color))
            {
                return;
            }
            var img = new ImageSharp.Image(50, 50);

            var red   = Convert.ToInt32(color.Substring(0, 2), 16);
            var green = Convert.ToInt32(color.Substring(2, 2), 16);
            var blue  = Convert.ToInt32(color.Substring(4, 2), 16);

            img.BackgroundColor(new ImageSharp.Color(color));

            await Context.Channel.SendFileAsync(img.ToStream(), $"{color}.png");
        }
Exemplo n.º 17
0
            public async Task Flip(int count = 1)
            {
                if (count == 1)
                {
                    if (rng.Next(0, 2) == 1)
                    {
                        using (var heads = _images.Heads.ToStream())
                        {
                            await Context.Channel.SendFileAsync(heads, "heads.jpg", Context.User.Mention + " " + GetText("flipped", Format.Bold(GetText("heads")))).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        using (var tails = _images.Tails.ToStream())
                        {
                            await Context.Channel.SendFileAsync(tails, "tails.jpg", Context.User.Mention + " " + GetText("flipped", Format.Bold(GetText("tails")))).ConfigureAwait(false);
                        }
                    }
                    return;
                }
                if (count > 10 || count < 1)
                {
                    await ReplyErrorLocalized("flip_invalid", 10).ConfigureAwait(false);

                    return;
                }
                var imgs = new Image <Rgba32> [count];

                for (var i = 0; i < count; i++)
                {
                    using (var heads = _images.Heads.ToStream())
                        using (var tails = _images.Tails.ToStream())
                        {
                            if (rng.Next(0, 10) < 5)
                            {
                                imgs[i] = Image.Load(heads);
                            }
                            else
                            {
                                imgs[i] = Image.Load(tails);
                            }
                        }
                }
                await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false);
            }
Exemplo n.º 18
0
            private async Task <(Stream ImageStream, string ToSend)> InternalDraw(int num, ulong?guildId = null)
            {
                if (num < 1 || num > 10)
                {
                    throw new ArgumentOutOfRangeException(nameof(num));
                }

                Deck cards       = guildId == null ? new Deck() : _allDecks.GetOrAdd(Context.Guild, (s) => new Deck());
                var  images      = new List <Image <Rgba32> >();
                var  cardObjects = new List <Deck.Card>();

                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        try
                        {
                            await ReplyErrorLocalized("no_more_cards").ConfigureAwait(false);
                        }
                        catch
                        {
                            // ignored
                        }
                        break;
                    }
                    var currentCard = cards.Draw();
                    cardObjects.Add(currentCard);
                    using (var stream = File.OpenRead(Path.Combine(_cardsPath, currentCard.ToString().ToLowerInvariant() + ".jpg").Replace(' ', '_')))
                        images.Add(Image.Load(stream));
                }
                MemoryStream bitmapStream = new MemoryStream();

                images.Merge().SaveAsPng(bitmapStream);
                bitmapStream.Position = 0;

                var toSend = $"{Context.User.Mention}";

                if (cardObjects.Count == 5)
                {
                    toSend += $" drew `{Deck.GetHandValue(cardObjects)}`";
                }

                return(bitmapStream, toSend);
            }
Exemplo n.º 19
0
            private Image GetDice(int num)
            {
                const string pathToImage = "data/images/dice";

                if (num != 10)
                {
                    using (var stream = File.OpenRead(Path.Combine(pathToImage, $"{num}.png")))
                        return(new Image(stream));
                }

                using (var one = File.OpenRead(Path.Combine(pathToImage, "1.png")))
                    using (var zero = File.OpenRead(Path.Combine(pathToImage, "0.png")))
                    {
                        Image imgOne  = new Image(one);
                        Image imgZero = new Image(zero);

                        return(new[] { imgOne, imgZero }.Merge());
                    }
            }
Exemplo n.º 20
0
            public async Task Flip(int count = 1)
            {
                if (count == 1)
                {
                    if (rng.Next(0, 2) == 1)
                    {
                        using (var heads = _images.Heads.ToStream())
                        {
                            await Context.Channel.SendFileAsync(heads, "heads.jpg", $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        using (var tails = _images.Tails.ToStream())
                        {
                            await Context.Channel.SendFileAsync(tails, "tails.jpg", $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false);
                        }
                    }
                    return;
                }
                if (count > 10 || count < 1)
                {
                    await Context.Channel.SendErrorAsync("`Invalid number specified. You can flip 1 to 10 coins.`").ConfigureAwait(false);

                    return;
                }
                var imgs = new Image[count];

                using (var heads = _images.Heads.ToStream())
                    using (var tails = _images.Tails.ToStream())
                    {
                        for (var i = 0; i < count; i++)
                        {
                            imgs[i] = rng.Next(0, 10) < 5 ?
                                      new Image(heads) :
                                      new Image(tails);
                        }
                        await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false);
                    }
            }
Exemplo n.º 21
0
 public Task <MagickImageCollection> SpoilerImg(string uri) => Task.Run(async() =>
 {
     //load image
     var img2 = await DownloadImageAsync(uri);
     //create spoiler warning image
     Image <Rgba32> img1 = new Image <Rgba32>(img2.Width, img2.Height);
     _Spoil    = _fonts.Find("Whitney-Bold").CreateFont(img2.Width * 0.064f);
     var fill  = Brushes.Solid <Rgba32>(Rgba32.Black);
     var brush = Brushes.Solid <Rgba32>(Rgba32.White);
     var rect  = new Rectangle(0, 0, img2.Width, img2.Height);
     img1.BackgroundColor(Rgba32.Black, rect);
     img1.DrawText("Spoiler Warning" + "\r\n" + "(Mouse over to view)", _Spoil, brush, new PointF(10, 10), new TextGraphicsOptions(true)
     {
         WrapTextWidth = img1.Width - 20
     });
     MagickImage f1       = new MagickImage(img1.ToStream());
     MagickImage f2       = new MagickImage(img2.ToStream());
     MagickImage[] frames = { f1, f2 };
     var gifs             = GetGif(frames);
     var gif = new MagickImageCollection(gifs);
     return(gif);
 });
Exemplo n.º 22
0
        public FileStream QrcodeImg()
        {
            var tempName        = DateTime.Now.Ticks.ToString();
            var tempTemple      = $"{tempName}-qrtemple.jpg";
            var tempTTFName     = $"{tempName}.ttf";
            var tempMyrcodeName = $"{tempName}-myqrcode.jpg";

            System.IO.File.Copy("qrtemple.jpg", tempTemple);
            System.IO.File.Copy("hyqh.ttf", tempTTFName);
            System.IO.File.Copy("qrcode.jpg", tempMyrcodeName);
            var qrcodeName = $"{tempName}-qrcode.jpg";

            using (FileStream streamTemple = System.IO.File.OpenRead(tempTemple))
                using (FileStream streamQrcode = System.IO.File.OpenRead(tempMyrcodeName))
                    using (FileStream output = System.IO.File.OpenWrite(qrcodeName))
                    {
                        var imageTemple = new ImageSharp.Image(streamTemple);
                        var imageQrcode = new ImageSharp.Image(streamQrcode);
                        //imageFoo.Blend(imageBar, 100);
                        imageTemple.DrawImage(imageQrcode, 100, new ImageSharp.Size(imageQrcode.Width, imageQrcode.Height), new ImageSharp.Point(imageTemple.Width / 3, imageTemple.Height / 2));
                        var fontCollection = new FontCollection();
                        var font           = fontCollection.Install(tempTTFName);
                        imageTemple.DrawText($"生成日期{DateTime.Now.ToString("yyyy.MM.dd")}", new SixLabors.Fonts.Font(font, imageTemple.Width / 40, FontStyle.Regular), new ImageSharp.Color(0, 0, 0), new System.Numerics.Vector2(imageTemple.Width * 1 / 3, imageTemple.Height * 9 / 10));
                        imageTemple.Save(output);
                    }
            if (System.IO.File.Exists(tempTemple))
            {
                System.IO.File.Delete(tempTemple);
            }
            if (System.IO.File.Exists(tempTTFName))
            {
                System.IO.File.Delete(tempTTFName);
            }
            if (System.IO.File.Exists(tempMyrcodeName))
            {
                System.IO.File.Delete(tempMyrcodeName);
            }
            return(System.IO.File.OpenRead(qrcodeName));
        }
Exemplo n.º 23
0
        public static ImageSharp.Image Merge(this IEnumerable <ImageSharp.Image> images)
        {
            var imgList = images.ToList();

            var canvas = new ImageSharp.Image(imgList.Sum(img => img.Width), imgList.Max(img => img.Height));

            var canvasPixels = canvas.Lock();
            int offsetX      = 0;

            foreach (var img in imgList.Select(img => img.Lock()))
            {
                for (int i = 0; i < img.Width; i++)
                {
                    for (int j = 0; j < img.Height; j++)
                    {
                        canvasPixels[i + offsetX, j] = img[i, j];
                    }
                }
                offsetX += img.Width;
            }

            return(canvas);
        }
Exemplo n.º 24
0
        public static Stream Resize(byte[] inStream, int?width = null, int?height = null)
        {
            var outStream = new MemoryStream();

            using (var stream = new MemoryStream(inStream))
            {
                var img = new ImageSharp.Image(stream);

                var w = width ?? img.Width;
                var h = height ?? img.Height;

                var result = img.Resize(new ResizeOptions
                {
                    Mode = ResizeMode.Pad,
                    Size = new Size(w, h)
                });


                result.SaveAsPng(outStream);

                return(outStream);
            }
        }
Exemplo n.º 25
0
        public Stream ScaleLogo2(Stream file, float maxWidthInInches, float maxHeightInInches)
        {
            ImageSharp.Configuration.Default.AddImageFormat(new JpegFormat());

            var image = new ImageSharp.Image(file);

            var maxWidthInPixels  = maxWidthInInches * image.MetaData.HorizontalResolution;
            var maxHeightInPixels = maxHeightInInches * image.MetaData.VerticalResolution;

            image.Resize(new ResizeOptions {
                Size = new ImageSharp.Size((int)maxWidthInPixels, (int)maxHeightInPixels),
                Mode = ResizeMode.Max
            });
            image.MetaData.Quality     = 100;
            image.MetaData.ExifProfile = null;

            var memStream = new MemoryStream();

            image.Save(memStream);

            memStream.Position = 0;
            return(memStream);
        }
Exemplo n.º 26
0
            private Image <Rgba32> GetDice(int num)
            {
                if (num < 0 || num > 10)
                {
                    throw new ArgumentOutOfRangeException(nameof(num));
                }

                if (num == 10)
                {
                    var images = _images.Dice;
                    using (var imgOneStream = images[1].ToStream())
                        using (var imgZeroStream = images[0].ToStream())
                        {
                            var imgOne  = Image.Load(imgOneStream);
                            var imgZero = Image.Load(imgZeroStream);

                            return(new[] { imgOne, imgZero }.Merge());
                        }
                }
                using (var die = _images.Dice[num].ToStream())
                {
                    return(Image.Load(die));
                }
            }
Exemplo n.º 27
0
            private Image GetDice(int num)
            {
                if (num < 0 || num > 10)
                {
                    throw new ArgumentOutOfRangeException(nameof(num));
                }

                if (num == 10)
                {
                    var images = NadekoBot.Images.Dice;
                    using (var imgOneStream = images[1].Value.ToStream())
                        using (var imgZeroStream = images[0].Value.ToStream())
                        {
                            Image imgOne  = new Image(imgOneStream);
                            Image imgZero = new Image(imgZeroStream);

                            return(new[] { imgOne, imgZero }.Merge());
                        }
                }
                using (var die = NadekoBot.Images.Dice[num].Value.ToStream())
                {
                    return(new Image(die));
                }
            }
Exemplo n.º 28
0
        private static void ProcessImages()
        {
            while (_repos.Queue.Count > 0)
            {
                var download = _repos.Queue.Dequeue();
                if (download == null)
                {
                    continue;
                }
                using (var sha512 = SHA512.Create())
                {
                    using (var md5 = MD5.Create())
                    {
                        //Helpers.LogMessage($"Starting Image : {download.ImageId}");
                        if (download.ImageExtension == "webm")
                        {
                            continue;
                        }
                        try
                        {
                            var image = GetImageContents(download.ImageUrl.StartsWith("http")
                                ? download.ImageUrl
                                : "http:" + download.ImageUrl);

                            if (image == null)
                            {
                                continue;
                            }

                            download.Hash = Core.Helpers.ByteToString(sha512.ComputeHash(image));

                            //Helpers.LogMessage($"{download.ImageId} : Processing Image");

                            if (_repos.ImageScrapeRepository.HashExistsAsync(download.Hash, CancellationToken.None)
                                .GetAwaiter().GetResult())
                            {
                                //hash already exists
                                //Helpers.LogMessage($"{download.ImageId} : O Crap Duplicate");
                                //add to scrape repo
                                if (!_repos.ImageScrapeRepository
                                    .ExistsAsync(download.ImageId, download.IndexSource, CancellationToken.None)
                                    .GetAwaiter().GetResult())
                                {
                                    _repos.ImageScrapeRepository.AddAsync(new ImageScrape
                                    {
                                        ImageId  = download.ImageId,
                                        Source   = download.IndexSource,
                                        Hash     = download.Hash,
                                        ScrapeId = ScrapeId
                                    }, CancellationToken.None).GetAwaiter().GetResult();
                                }
                                continue;
                            }

                            var sanitizedId = Core.Helpers.ByteToString(md5.ComputeHash(image));

                            var filename = $"{sanitizedId}.{download.ImageExtension}";

                            //if hash doesnt exists
                            if (!File.Exists($"{_globalSettings.Scraper.ImageLocation}{filename}"))
                            {
                                File.WriteAllBytes($"{_globalSettings.Scraper.ImageLocation}{filename}",
                                                   image);
                            }

                            if (!File.Exists($"{_globalSettings.Scraper.ThumbnailLocation}{filename}") ||
                                string.IsNullOrWhiteSpace(download.Resolution))
                            {
                                using (var imageData = new Image(image))
                                {
                                    if (string.IsNullOrWhiteSpace(download.Resolution))
                                    {
                                        download.Resolution = $"{imageData.Width}x{imageData.Height}";
                                    }

                                    if (imageData.Height < 720 || imageData.Width < 1024)
                                    {
                                        Helpers.LogMessage($"Image is too Small: {imageData.Width}x{imageData.Height}");
                                        _repos.ImageScrapeRepository.AddAsync(new ImageScrape
                                        {
                                            ImageId  = download.ImageId,
                                            Source   = download.IndexSource,
                                            Hash     = download.Hash,
                                            ScrapeId = ScrapeId
                                        }, CancellationToken.None);
                                        continue;
                                    }

                                    if (!File.Exists(
                                            $"{_globalSettings.Scraper.ThumbnailLocation}{filename}"))
                                    {
                                        int newHeight, newWidth;
                                        try
                                        {
                                            if (imageData.Height > imageData.Width)
                                            {
                                                newHeight = Constants.ThumbnailSize;
                                                newWidth  = imageData.Width /
                                                            (imageData.Height / Constants.ThumbnailSize);
                                            }
                                            else
                                            {
                                                newWidth  = Constants.ThumbnailSize;
                                                newHeight = imageData.Height /
                                                            (imageData.Width / Constants.ThumbnailSize);
                                            }
                                        }
                                        catch
                                        {
                                            Helpers.LogMessage($"Thumbnail attempted to divide by zero?");
                                            newWidth  = Constants.ThumbnailSize;
                                            newHeight = Constants.ThumbnailSize;
                                        }

                                        //thumbnail doesnt exists make it
                                        imageData.Resize(newWidth, newHeight);
                                        imageData.Save(
                                            $"{_globalSettings.Scraper.ThumbnailLocation}{filename}");
                                        imageData.Dispose();
                                        //Helpers.LogMessage($"{download.ImageId} :: Saved Thumbnail!");
                                    }
                                }
                            }


                            //add to scrape repo
                            _repos.ImageScrapeRepository.AddAsync(new ImageScrape
                            {
                                ImageId  = download.ImageId,
                                Source   = download.IndexSource,
                                Hash     = download.Hash,
                                ScrapeId = ScrapeId
                            }, CancellationToken.None);
                            //Helpers.LogMessage($"{download.ImageId} :: Marked as Scraped!");

                            //build new image
                            var newImage = new Models.Image
                            {
                                ImageId        = sanitizedId,
                                Class          = download.Class,
                                IndexSource    = download.IndexSource,
                                Who            = download.Who,
                                Tripcode       = download.TripCode,
                                ResolutionX    = int.Parse(download.Resolution.Split('x').First()),
                                ResolutionY    = int.Parse(download.Resolution.Split('x').Last()),
                                TagsString     = download.Tag,
                                DateDownloaded = DateTime.UtcNow,
                                Reported       = Enums.Reported.Unreported,
                                Hash           = download.Hash,
                                FileExtension  = download.ImageUrl.Split('.').Last(),
                                ServerId       = _globalSettings.Scraper.ScrapeServer,
                                Size           = image.Length / 1024m
                            };

                            //calculate ratio
                            var r = Core.Helpers.RatioCalculate(newImage.ResolutionX, newImage.ResolutionY);


                            try
                            {
                                newImage.Ratio = $"{newImage.ResolutionX / r}:{newImage.ResolutionY / r}";
                            }
                            catch
                            {
                                Helpers.LogMessage($"Ratio attempted to divide by zero?");
                            }

                            //add to imageRepo?
                            _repos.ImageRepository.AddAsync(newImage, CancellationToken.None);
                            //Helpers.LogMessage($"{download.ImageId} :: Added to Repo!");
                        }
                        catch (Exception ex)
                        {
                            Helpers.LogMessage($"Processing Image {download.ImageId} : Error {ex.Message}!");
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        public async Task MemeAsync(int memeNumber, [Remainder] string text)
        {
            var task = Task.Run(async() =>
            {
                if (memeNumber > memeImage.Length)
                {
                    await ReplyAsync($"`ERROR: INCORRECT INTERGER VALUE DETECTED, THE NUMBER MUST BE {memeImage.Length} OR LESS`");
                    return;
                }
                await ReplyAsync("");
                string top    = null;
                string bottom = null;
                int charsIn   = 0;
                var botStart  = await ReplyAsync($"*BLEEP BLOOP*\n`GENERATING DANK MEME FOR USER: {Context.User.Username}`");
                foreach (char x in text)
                {
                    if (x != '|')
                    {
                        top     += x;
                        charsIn += 1;
                    }
                    else
                    {
                        for (int i = charsIn + 1; i < text.Length; i++)
                        {
                            bottom += text.ElementAt(i);
                        }
                        break;
                    }
                }
                top    = top.Trim();
                bottom = bottom.Trim();
                ImageSharp.Image image       = null;
                HttpClient httpClient        = new HttpClient();
                HttpResponseMessage response = await httpClient.GetAsync(memeImage[memeNumber - 1]);
                Stream inputStream           = await response.Content.ReadAsStreamAsync();
                image                     = ImageSharp.Image.Load(inputStream);
                Rgba32 white              = new Rgba32(255, 255, 255, 255);
                Rgba32 black              = new Rgba32(0, 0, 0, 255);
                FontCollection fonts      = new FontCollection();
                Font font1                = fonts.Install("Images/impact.ttf");
                Font font2                = new Font(font1, 50f, FontStyle.Regular);
                TextMeasurer measurer     = new TextMeasurer();
                SixLabors.Fonts.Size size = measurer.MeasureText(top, font2, 72);
                float scalingFactor       = Math.Min((image.Width - 10) / size.Width, ((image.Height - 10) / 4) / (size.Height));
                Font scaledFont           = new Font(font2, scalingFactor * font2.Size);

                SixLabors.Fonts.Size size2 = measurer.MeasureText(bottom, font2, 72);
                float scalingFactor2       = Math.Min((image.Width - 10) / size2.Width, ((image.Height - 10) / 4) / (size2.Height));
                Font scaledFont2           = new Font(font2, scalingFactor2 * font2.Size);

                Vector2 posTop    = new Vector2(5, 5);
                Vector2 posBottom = new Vector2(5, (image.Height * (float)(.65)));

                var pen      = new Pen(black, scalingFactor);
                var pen2     = new Pen(black, scalingFactor2);
                var brush    = new SolidBrush(white);
                var topWidth = measurer.MeasureText(top, scaledFont, 72).Width;
                var botWidth = measurer.MeasureText(bottom, scaledFont2, 72).Width;
                if (topWidth < image.Width - 15)
                {
                    posTop.X += ((image.Width - topWidth) / 2);
                }
                if (botWidth < image.Width - 15)
                {
                    posBottom.X += ((image.Width - botWidth) / 2);
                }
                image.DrawText(top, scaledFont, brush, pen, posTop);
                image.DrawText(bottom, scaledFont2, brush, pen2, posBottom);
                Stream outputStream = new MemoryStream();
                image.SaveAsPng(outputStream);
                outputStream.Position = 0;
                string input          = "abcdefghijklmnopqrstuvwxyz0123456789";
                char ch;
                string randomString = "";
                Random rand         = new Random();
                for (int i = 0; i < 8; i++)
                {
                    ch            = input[rand.Next(0, input.Length)];
                    randomString += ch;
                }
                var file = File.Create($"Images/{randomString}.png");
                await outputStream.CopyToAsync(file);
                file.Dispose();
                await Context.Channel.SendFileAsync(file.Name);
                var botDone = await ReplyAsync($"`IMAGE HES BEEN GENERATED FOR USER: {Context.User.Username}\nENJOY!!`\n*MURP*\n`BOT MESSAGES WILL DELETE IN 10 SECONDS.`");
                File.Delete(file.Name);
                await Task.Delay(10000);
                await botStart.DeleteAsync();
                await botDone.DeleteAsync();
            });
        }
Exemplo n.º 30
0
            public async Task Slot(int amount = 0)
            {
                if (!_runningUsers.Add(Context.User.Id))
                {
                    return;
                }
                try
                {
                    if (amount < 1)
                    {
                        await ReplyErrorLocalized("min_bet_limit", 1 + CurrencySign).ConfigureAwait(false);

                        return;
                    }

                    if (amount > 999)
                    {
                        GetText("slot_maxbet", 999 + CurrencySign);
                        await ReplyErrorLocalized("max_bet_limit", 999 + CurrencySign).ConfigureAwait(false);

                        return;
                    }

                    if (!await CurrencyHandler.RemoveCurrencyAsync(Context.User, "Slot Machine", amount, false))
                    {
                        await ReplyErrorLocalized("not_enough", CurrencySign).ConfigureAwait(false);

                        return;
                    }
                    Interlocked.Add(ref _totalBet, amount);
                    using (var bgFileStream = NadekoBot.Images.SlotBackground.ToStream())
                    {
                        var bgImage = new ImageSharp.Image(bgFileStream);

                        var   result  = SlotMachine.Pull();
                        int[] numbers = result.Numbers;

                        for (int i = 0; i < 3; i++)
                        {
                            using (var file = _images.SlotEmojis[numbers[i]].ToStream())
                                using (var randomImage = new ImageSharp.Image(file))
                                {
                                    bgImage.DrawImage(randomImage, 100, default(Size), new Point(95 + 142 * i, 330));
                                }
                        }

                        var won      = amount * result.Multiplier;
                        var printWon = won;
                        var n        = 0;
                        do
                        {
                            var digit = printWon % 10;
                            using (var fs = NadekoBot.Images.SlotNumbers[digit].ToStream())
                                using (var img = new ImageSharp.Image(fs))
                                {
                                    bgImage.DrawImage(img, 100, default(Size), new Point(230 - n * 16, 462));
                                }
                            n++;
                        } while ((printWon /= 10) != 0);

                        var printAmount = amount;
                        n = 0;
                        do
                        {
                            var digit = printAmount % 10;
                            using (var fs = _images.SlotNumbers[digit].ToStream())
                                using (var img = new ImageSharp.Image(fs))
                                {
                                    bgImage.DrawImage(img, 100, default(Size), new Point(395 - n * 16, 462));
                                }
                            n++;
                        } while ((printAmount /= 10) != 0);

                        var msg = GetText("better_luck");
                        if (result.Multiplier != 0)
                        {
                            await CurrencyHandler.AddCurrencyAsync(Context.User, $"Slot Machine x{result.Multiplier}", amount *result.Multiplier, false);

                            Interlocked.Add(ref _totalPaidOut, amount * result.Multiplier);
                            if (result.Multiplier == 1)
                            {
                                msg = GetText("slot_single", CurrencySign, 1);
                            }
                            else if (result.Multiplier == 4)
                            {
                                msg = GetText("slot_two", CurrencySign, 4);
                            }
                            else if (result.Multiplier == 10)
                            {
                                msg = GetText("slot_three", 10);
                            }
                            else if (result.Multiplier == 30)
                            {
                                msg = GetText("slot_jackpot", 30);
                            }
                        }

                        await Context.Channel.SendFileAsync(bgImage.ToStream(), "result.png", Context.User.Mention + " " + msg + $"\n`{GetText("slot_bet")}:`{amount} `{GetText("slot_won")}:` {amount * result.Multiplier}{NadekoBot.BotConfig.CurrencySign}").ConfigureAwait(false);
                    }
                }
                finally
                {
                    var _ = Task.Run(async() =>
                    {
                        await Task.Delay(1500);
                        _runningUsers.Remove(Context.User.Id);
                    });
                }
            }