コード例 #1
0
        /// <summary>
        /// Initialises and installs the font for the watermarking.
        /// TODO: In future we'll make the font configurable.
        /// </summary>
        /// <param name="folder"></param>
        public void SetFontPath(string folder)
        {
            try
            {
                fontCollection = new FontCollection();

                string fontPath = Path.Combine(folder, "arial.ttf");

                fontCollection.Install(fontPath);

                Logging.Log("Watermark font installed: {0}", fontPath);
            }
            catch (Exception ex)
            {
                Logging.LogError($"Exception installing watermark font: {ex.Message}");
            }
        }
コード例 #2
0
        public ImageConverterWallpaperHandler(ILogger logger,
                                              Common.Model.Wallpaper wallpaper,
                                              IWallpaperManager wallpaperManager)
        {
            _logger           = logger;
            _wallpaper        = wallpaper;
            _wallpaperManager = wallpaperManager;

            _generatedFiles = new List <WallpaperFileGenerated>();
            _images         = new List <WallpaperFileImage>();

            using (var fontStream = GetType().Assembly.GetManifestResourceStream("Wallpaper.Service.Roboto-Regular.ttf"))
            {
                _fonts      = new FontCollection();
                _robotoFont = _fonts.Install(fontStream);
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: evermeire/Samples
        static void Main(string[] args)
        {
            System.IO.Directory.CreateDirectory("output");
            using (var img = Image.Load("fb.jpg"))
            {
                SixLabors.Fonts.FontCollection fontCollection = new FontCollection();
                SixLabors.Fonts.Font           carlitoFont    = fontCollection.Install(Directory.GetCurrentDirectory() + "/font/Carlito-Regular.ttf")
                                                                .CreateFont(14, FontStyle.Regular);

                using (var img2 = img.Clone(ctx => ctx.ApplyScalingWaterMark(carlitoFont, longText, Rgba32.HotPink, 5, true)))
                {
                    img2.Save("output/watermarked.png");
                }

                // the original `img` object has not been altered at all.
            }
        }
コード例 #4
0
        public Image Generate()
        {
            Drawer draw       = null;
            var    collection = new FontCollection();
            var    family     = collection.Install($"./Static/fonts/{Roboto.Medium}");

            // Rendering background and templates for score stats
            CreateTemplate();

            // Drawing data on the image
            draw += DrawBeatmapStats;
            draw += DrawUserStats;
            draw += DrawScoreStats;
            draw.Invoke(family);

            return(_image);
        }
コード例 #5
0
        public TextRenderer(GraphicsDevice gd)
        {
            _gd = gd;
            uint width  = 250;
            uint height = 100;

            _texture = gd.ResourceFactory.CreateTexture(
                TextureDescription.Texture2D(width, height, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled));
            TextureView = gd.ResourceFactory.CreateTextureView(_texture);

            FontCollection fc     = new FontCollection();
            FontFamily     family = fc.Install(Path.Combine(AppContext.BaseDirectory, "Assets", "Fonts", "Sunflower-Medium.ttf"));

            _font = family.CreateFont(28);

            _image = new Image <Rgba32>(250, 100);
        }
コード例 #6
0
        private async Task DrawWelcomeScreen()
        {
            Image <Rgba32> image = new Image <Rgba32>(400, 300);
            FontCollection fc    = new FontCollection();

            fc.Install("DigitalDream.ttf");
            var             f       = fc.CreateFont("Digital Dream", 18);
            GraphicsOptions options = new GraphicsOptions(false);

            image.Mutate((ctx) =>
            {
                ctx.Fill(Rgba32.White);
                ctx.DrawText($"{GetCurrentIpv4Address()}:8800", f, Rgba32.Black, new PointF(0, 0), options);
                ctx.DrawText($"{DateTime.Now.ToString()}", f, Rgba32.Black, new PointF(0, 100), options);
                ctx.Dither(new SixLabors.ImageSharp.Dithering.FloydSteinbergDiffuser(), 0.5f);
            });
            await Renderer.RenderAsync(image, Task.Factory.CancellationToken);
        }
コード例 #7
0
ファイル: ImageHelper.cs プロジェクト: Naamloos/NSchedule
        public async Task ShareAppointmentImageAsync(CalendarEvent c)
        {
            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = "NSchedule.Fonts.font.ttf";

            FontFamily font;

            FontCollection fonts = new FontCollection();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                font = fonts.Install(stream);
            }

            var Data = DependencyService.Get <DataHelper>();
            var att  = c.Appointment.Attendees;

            var rooms    = Data.Schedulables.Where(x => x.GetType() == typeof(Room) && att.Contains(x.Id)).Cast <Room>().Select(x => x.Code);
            var teachers = Data.Schedulables.Where(x => x.GetType() == typeof(Teacher) && att.Contains(x.Id)).Cast <Teacher>().Select(x => x.Code);
            var groups   = Data.Schedulables.Where(x => x.GetType() == typeof(Group) && att.Contains(x.Id)).Cast <Group>().Select(x => x.Code);

            string yourText = $"{c.Name}\n{c.ScheduleableCode} ({c.Times})\n\n\nRooms:\n{JoinPerTwo(rooms)}\n\nTeachers:\n{JoinPerTwo(teachers)}\n\nGroups:\n{JoinPerTwo(groups)}\n\n{Constants.SHARED_WITH}";

            var f        = font.CreateFont(25f);
            var measures = TextMeasurer.Measure(yourText, new RendererOptions(f));
            var img      = new Image <Rgba32>((int)measures.Width + 50, (int)measures.Height + 50);

            img.Mutate(x => x.Fill(Color.White));

            IPath rect = new RectangularPolygon(15, 15, measures.Width + 20, measures.Height + 20);

            img.Mutate(x => x.Draw(Color.Gray, 5f, rect));

            img.Mutate(x => x.DrawText(yourText, f, Color.Black, new PointF(25f, 25f)));

            var basePath = System.IO.Path.GetTempPath();
            var path     = System.IO.Path.Combine(basePath, "share.png");
            await img.SaveAsPngAsync(path).ConfigureAwait(false);

            await Share.RequestAsync(new ShareFileRequest(c.Name, new ShareFile(path))).ConfigureAwait(false);

            // cleanup after share..
            //File.Delete(path);
        }
コード例 #8
0
        private static IImageProcessingContext AddCaption(this IImageProcessingContext processingContext, string text, Color color, Color backgroundColor)
        {
            Size imgSize = processingContext.GetCurrentSize();

            float defaultFontSize   = 12;
            float defaultResolution = 645;
            float defaultPadding    = 10;

            float fontSize     = imgSize.Width * defaultFontSize / defaultResolution;
            float padding      = imgSize.Width * defaultPadding / defaultResolution;
            float captionWidth = imgSize.Width - (2 * padding);


            FontCollection collection = new FontCollection();
            FontFamily     family     = collection.Install("Roboto/Roboto-Regular.ttf");
            Font           font       = family.CreateFont(fontSize, FontStyle.Regular);

            // measure the text size
            FontRectangle fontRectangle = TextMeasurer.Measure(text, new RendererOptions(font)
            {
                WrappingWidth = captionWidth
            });

            var location           = new PointF(padding, imgSize.Height + padding);
            var textGraphicOptions = new TextGraphicsOptions()
            {
                TextOptions = { WrapTextWidth = captionWidth }
            };

            var resizeOptions = new ResizeOptions()
            {
                // increse image height to include caption height
                Size     = new Size(imgSize.Width, imgSize.Height + (int)fontRectangle.Height + (int)(2 * padding)),
                Mode     = ResizeMode.BoxPad,
                Position = AnchorPositionMode.Top
            };

            return(processingContext
                   .Resize(resizeOptions)
                   .BackgroundColor(backgroundColor)
                   .DrawText(textGraphicOptions, text, font, color, location));
        }
コード例 #9
0
        static void Main(string[] args)
        {
            var fontCollection = new FontCollection();
            var fontFamily     = fontCollection.Install("Font/LinLibertine_RZah.ttf");

            font = fontFamily.CreateFont(55);

            var fontCollectionAuthor = new FontCollection();
            var fontFamilyAuthor     = fontCollectionAuthor.Install("Font/LinLibertine_RZIah.ttf");

            fontAuthor = fontFamilyAuthor.CreateFont(24);


            //String quote = "It was 11:55 a.m. on April 30.";
            String quote     = @"... You had no reason to think the times important. Indeed how suspicious it would be if you had been completely accurate. ""Haven't I been?"" Not quite. It was five to seven that you talked to Wilkins. ""Another ten minutes.""";
            String highlight = "five to seven";
            String footer    = "The Quiet American, Graham Greene";

            CreateImage(quote, highlight, footer);
        }
コード例 #10
0
        public FontProvider()
        {
            _fonts = new FontCollection();
            if (Directory.Exists("data/fonts"))
            {
                foreach (var file in Directory.GetFiles("data/fonts"))
                {
                    _fonts.Install(file);
                }
            }

            UsernameFontFamily = _fonts.Find("Whitney-Bold");
            ClubFontFamily     = _fonts.Find("Whitney-Bold");
            LevelFont          = _fonts.Find("Whitney-Bold").CreateFont(20);
            XpFont             = _fonts.Find("Whitney-Bold").CreateFont(25);
            //AwardedFont = _fonts.Find("Whitney-Bold").CreateFont(25);
            RankFont    = _fonts.Find("Whitney-Bold").CreateFont(20);
            TimeFont    = _fonts.Find("Whitney-Bold").CreateFont(20);
            RipNameFont = _fonts.Find("Whitney-Bold").CreateFont(20);
        }
コード例 #11
0
        public bool DrawText(int x, int y, Color pColor, string text, Font font = null, int fontSize = 18, bool left = true, bool bottom = true)
        {
            if (_imageObj == null)
            {
                return(false);
            }
            if (font == null)
            {
                FontCollection fonts      = new FontCollection();
                FontFamily     fontfamily = fonts.Install("Fonts/OpenSans-Regular.TTF"); //装载字体(ttf)
                font = new Font(fontfamily, fontSize, FontStyle.Regular);                //20号,加粗
            }

            //获取该文件绘制所需的大小,精确绘制
            var size   = TextMeasurer.Measure(text, new RendererOptions(font));
            var deltaX = left ? 0 : -size.Width;
            var deltaY = !bottom ? 0 : -size.Height;

            _imageObj.Mutate(xx => xx.DrawText(text, font, pColor, new PointF(x + deltaX, y + deltaY)));
            return(true);
        }
コード例 #12
0
ファイル: Text.cs プロジェクト: salslab/LittlePdf
        internal override void Paint(Page page, StringBuilder output)
        {
            var(x, y) = page.Axes.GetPoint(AbsoluteX, AbsoluteY);
            var valueBytes = PdfString.Encode(Value);
            var value      = Encoding.ASCII.GetString(valueBytes);

            FontCollection fonts       = new FontCollection();
            FontFamily     font1Family = fonts.Install(@"C:\Users\sal\AppData\Local\Microsoft\Windows\Fonts\Helvetica.ttf");
            var            font1       = font1Family.CreateFont(24);

            var m          = TextMeasurer.Measure(Value, new RendererOptions(font1));
            var textHeight = m.Height;
            var textWidth  = m.Width;

            //var h = new System.Drawing.Font("Helvetica", 24);
            //var s = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).MeasureString(Value, h);
            //var textHeight = s.Height * 0.75;

            //output.Append($"BT /F1 24 Tf {x} {y - textHeight} Td {value} Tj ET ");
            output.Append($"BT /F1 24 Tf 1 0 0 1 {x} {y - textHeight} Tm {value} Tj ET ");
        }
コード例 #13
0
        private static Image GenerateThumbnail(string path, int thumbnailOneDimensionSize, string price)
        {
            using (var img = Image.Load(path))
            {
                // as generate returns a new IImage make sure we dispose of it
                var thumbnail = img.Clone(x =>
                                          x.Crop(new Size(thumbnailOneDimensionSize, thumbnailOneDimensionSize))
                                          .ApplyRoundedCorners(15)
                                          );

                var fonts = new FontCollection();
                var bebasNeueFontFamily = fonts.Install($"{RootFolder}/input/BebasNeue-Regular.ttf");

                var font = new Font(bebasNeueFontFamily, 85);

                using (var priceBg = Image.Load($"{RootFolder}/input/pricebg.png"))
                {
                    thumbnail.Mutate(x => x.DrawImage(priceBg, new Point(0, thumbnailOneDimensionSize - 120), 1f));
                }

                var finalPrice = $"${price}";

                if (finalPrice.Length < 4)
                {
                    for (var i = 0; i <= 4 - finalPrice.Length; i++)
                    {
                        finalPrice = $" {finalPrice}";
                    }
                }

                thumbnail.Mutate(x => x.DrawText(
                                     finalPrice,
                                     font,
                                     Rgba32.White,
                                     new Point(15, thumbnailOneDimensionSize - 105))
                                 );

                return(thumbnail);
            }
        }
コード例 #14
0
        public FontProvider()
        {
            _fonts = new FontCollection();
            if (Directory.Exists("data/fonts"))
            {
                foreach (var file in Directory.GetFiles("data/fonts"))
                {
                    _fonts.Install(file);
                }
            }

            ///UsernameFontFamily = _fonts.Find("Whitney-Bold");
            ///ClubFontFamily = _fonts.Find("Whitney-Bold");
            ///LevelFont = _fonts.Find("Whitney-Bold").CreateFont(45);
            ///XpFont = _fonts.Find("Whitney-Bold").CreateFont(50);
            ///AwardedFont = _fonts.Find("Whitney-Bold").CreateFont(25);
            ///RankFont = _fonts.Find("Uni Sans Thin CAPS").CreateFont(30);
            ///TimeFont = _fonts.Find("Whitney-Bold").CreateFont(20);
            ///RipNameFont = _fonts.Find("Whitney-Bold").CreateFont(20);
            NotoSans       = _fonts.Find("Noto Sans");
            RankFontFamily = _fonts.Find("Uni Sans Thin CAPS");
        }
コード例 #15
0
ファイル: ImageController.cs プロジェクト: youdang227/ZHS
        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));
        }
コード例 #16
0
ファイル: ImageGenerator.cs プロジェクト: zumpanik/SoraBot-v2
        public ImageGenerator()
        {
            ImageGenPath = Path.Combine(Directory.GetCurrentDirectory(), "ImageGenerationFiles");
            string pCreationPath = Path.Combine(ImageGenPath, PROFILE_CREATION);

            // Load template into memory so it's faster in the future :D
            _templateOverlay = Image.Load <Rgba32>(Path.Combine(pCreationPath, "profileTemplate.png"));
            _templateOverlay.Mutate(x => x.Resize(new Size(470, 265)));

            // Add and load fonts
            var fc        = new FontCollection();
            var fontHeavy = fc.Install(Path.Combine(pCreationPath, "AvenirLTStd-Heavy.ttf"));

            _heavyTitleFont = new Font(fontHeavy, 20.31f, FontStyle.Bold);
            _statsLightFont = new Font(fontHeavy, 13.4f, FontStyle.Bold);
            _statsTinyFont  = new Font(fontHeavy, 10.52f, FontStyle.Bold);

            // Create accessory directories
            this.CreateImageGenDirectoryIfItDoesntExist(AVATAR_CACHE);
            this.CreateImageGenDirectoryIfItDoesntExist(PROFILE_BG);
            this.CreateImageGenDirectoryIfItDoesntExist(PROFILE_CARDS);
        }
コード例 #17
0
        public static Pixels Create(string text)
        {
            var width = text.Length * 10;

            using (var image = new Image <Rgba32>(Configuration.Default, width, 10))
            {
                var fontCollection = new FontCollection();
                var assemblyDir    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var fontStream     = Assembly.GetExecutingAssembly()
                                     .GetManifestResourceStream("Sense.Resources.SCUMM-8px-unicode.ttf");
                var fontFamily = fontCollection.Install(fontStream);
                var font       = fontFamily.CreateFont(8, FontStyle.Regular);
                image.Mutate(ctx => ctx.DrawText(text, font, Rgba32.Black, PointF.Empty));
                // using (var stream = System.IO.File.OpenWrite(@"output.png"))
                // {
                //     image.SaveAsPng(stream);
                // }
                var pixelSpan = image.GetPixelSpan();
                var textCells = new List <CellColor>();

                for (var idx = 0; idx < pixelSpan.Length; idx++)
                {
                    var pixel = pixelSpan[idx];
                    if (pixel.A > 200)
                    {
                        textCells.Add(new CellColor(
                                          new Cell(idx / width, idx % width),
                                          new Color(pixel.R, pixel.G, pixel.B)
                                          ));
                    }
                }
                var minRow    = textCells.Min(p => p.Cell.Row);
                var minColumn = textCells.Min(p => p.Cell.Column);
                return(new Pixels(textCells.ToImmutableList())
                       .Shift(-minRow, -minColumn)
                       .SetColor(new Color(255, 255, 255)));
            }
        }
コード例 #18
0
        public KomiPaperMemeGen(BotState state)
        {
            _botState = state;
            var fontCollection = new FontCollection();

            fontCollection.Install(@"Fonts\mangat.ttf", out var fontDescription);
            _template = new MemeTemplate("KomiPaper.png",
                                         new TextBoundingBox()
            {
                TopLeft      = new PointF(245, 479),
                TopRight     = new PointF(708, 558),
                BottomLeft   = new PointF(168, 728),
                BottomRight  = new PointF(632, 810),
                CenterHeight = false,
                CenterWidth  = false,
                Font         = fontCollection.CreateFont(fontDescription.FontFamily, 20)
            },
                                         new MultiBoundingBox(new ImageBoundingBox()
            {
                TopLeft              = new PointF(245, 479),
                TopRight             = new PointF(708, 558),
                BottomLeft           = new PointF(94, 988),
                BottomRight          = new PointF(557, 1067),
                LandscapeScalingMode = ImageScalingMode.FitWithLetterbox,
                PortraitScalingMode  = ImageScalingMode.FillFit
            })
            {
                Padding = 10,
                Masks   = new List <Rectangle>
                {
                    new Rectangle(0, 631, 186, 446),
                    new Rectangle(666, 552, 50, 150),
                    new Rectangle(0, 1065, 557, 205)
                }
            });
        }
コード例 #19
0
        public static FontFamily GetCaptionFontFamily()
        {
            try
            {
                return(SystemFonts.Find("DejaVu Sans"));
            }
            catch (SixLabors.Fonts.Exceptions.FontFamilyNotFoundException)
            {
                using (Amazon.S3.AmazonS3Client client = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast2))
                    using (Amazon.S3.Model.GetObjectResponse response = client.GetObjectAsync("appraisal-bot", "DejaVuSans-Bold.ttf").GetAwaiter().GetResult())
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            // ResponseStream is a HashStream which doesn't support Seeking
                            // which is required to install a font. So first we copy the
                            // data to a MemoryStream which does support seeking.
                            response.ResponseStream.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            FontCollection fonts = new FontCollection();
                            FontFamily     font  = fonts.Install(memoryStream);
                            return(font);
                        }
            }
        }
        public MemoryStream GetCaptchPictureStream(string text)
        {
            var config = configuration.GetSection("Captcha").Get <CaptchaConfig>();

            using (var image = new Image <Rgba32>(config.ImageWidth, config.ImageHeight))
            {
                FontCollection collection          = new FontCollection();
                FontFamily     fontFamily          = collection.Install(config.FontFamilyPath);
                Font           font                = fontFamily.CreateFont(config.FontSize);
                var            fontBrush           = new SolidBrush(Color.Gray);
                var            stringStartingPoint = new Point(0, 20);

                var rectangle = new RectangleF(0, 0, image.Width, image.Height);
                image.Mutate(i => i.Fill(new SolidBrush(Color.White)));


                if (config.DisturbString)
                {
                    DrawDisturbedString(image, text, font, fontBrush, stringStartingPoint, config);
                }
                else
                {
                    DrawStringContinuosly(image, text, font, fontBrush, stringStartingPoint);
                }

                if (config.DisturbtionLines)
                {
                    AddDisturbtionLines(image, config);
                }

                MemoryStream ms = new MemoryStream();
                image.SaveAsPng(ms);
                ms.Position = 0;
                return(ms);
            }
        }
コード例 #21
0
        public async Task <MemoryStream> DrawProfileAsync(UserProfileDto profileInfo, bool isAnimated = false)
        {
            MemoryStream outputStream    = new MemoryStream();
            var          backgroundImage = _cacheService.GetOrAddImage(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "img", "NeonProfile", "behindProfile.png"));
            var          mainImage       = _cacheService.GetOrAddImage(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "img", "NeonProfile", "Profile.png"));
            var          levelIcon       = _cacheService.GetOrAddImage(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "img", "XeroLevelIcons", $"{profileInfo.Level}.png"));
            var          expBar          = _cacheService.GetOrAddImage(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "img", "NeonProfile", "ExpBar.png"));

            FontCollection fonts           = new FontCollection();
            FontFamily     notoSansRegular = fonts.Install(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "fonts", "NotoSans-Regular.ttf"));
            FontFamily     geometos        = fonts.Install(Path.Combine(AppContext.BaseDirectory, "Resources", "RabbotThemeNeon", "assets", "fonts", "Geometos.ttf"));

            var userAvatar = await GetAvatarAsync(profileInfo.AvatarUrl);

            var centerOptions = new TextGraphicsOptions {
                HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center
            };
            var rightOptions = new TextGraphicsOptions {
                HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center
            };

            //Fonts
            var nameFont      = new Font(notoSansRegular, 24, FontStyle.Regular);
            var levelRankFont = new Font(geometos, 26, FontStyle.Bold);
            var expFont       = new Font(geometos, 18, FontStyle.Bold);
            var expInfoFont   = new Font(geometos, 11, FontStyle.Bold);
            var goatFont      = new Font(geometos, 18, FontStyle.Bold);

            //Gif
            int          frameDelay = 0;
            int          frameCount = 1;
            List <Image> frames     = new List <Image>();

            if (isAnimated)
            {
                frameDelay = userAvatar.Frames.RootFrame.Metadata.GetFormatMetadata(GifFormat.Instance).FrameDelay;
                frameCount = userAvatar.Frames.Count - 1;
                for (int i = 0; i < frameCount; i++)
                {
                    try
                    {
                        frames.Add(userAvatar.Frames.CloneFrame(i));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, $"Frame {i} can't be cloned.");
                    }
                }
            }
            else
            {
                frames.Add(userAvatar);
            }

            using (var output = new Image <Rgba32>(300, 175))
            {
                for (int i = 0; i < frames.Count; i++)
                {
                    using var image = new Image <Rgba32>(300, 175);
                    int nameFontSize = (int)nameFont.Size;
                    int expFontSize  = (int)expFont.Size;

                    //Reduce font size if name is too long
                    nameFont = ResizeFont(nameFont, profileInfo.Name, 200);

                    //Reduce font size if current exp is too long
                    expFont = ResizeFont(expFont, profileInfo.Exp, 62);

                    float opacity     = 1f;
                    var   expBarWidth = (int)(161 * (profileInfo.Percent / 100));
                    if (expBarWidth == 0)
                    {
                        opacity = 0;
                    }

                    image.Frames.RootFrame.Metadata.GetFormatMetadata(GifFormat.Instance).FrameDelay = frameDelay;
                    Color color = Color.FromHex("#00FFFF");

                    levelIcon.Mutate(x => x.Resize(27, 27));
                    frames[i].Mutate(x => x.Resize(83, 83));
                    expBar.Mutate(x => x.Resize(expBarWidth, 17));
                    image.Mutate(x => x
                                 .DrawImage(backgroundImage, new Point(0, 0), 1f)
                                 .DrawImage(frames[i], new Point(10, 10), 1f)
                                 .DrawImage(expBar, new Point(119, 130), opacity)
                                 .DrawImage(mainImage, new Point(0, 0), 1f)
                                 .DrawImage(levelIcon, new Point(80, 80), 1f)
                                 .DrawText(centerOptions, profileInfo.Name, nameFont, color, new PointF(195, 25))
                                 .DrawText(centerOptions, profileInfo.Rank, levelRankFont, color, new PointF(155, 63))
                                 .DrawText(centerOptions, profileInfo.Level, levelRankFont, color, new PointF(239, 63))
                                 .DrawText(rightOptions, profileInfo.Exp, expFont, color, new PointF(110, 122))
                                 .DrawText(rightOptions, profileInfo.Goats, goatFont, color, new PointF(110, 155))
                                 .DrawText(centerOptions, profileInfo.LevelInfo, expInfoFont, color, new PointF(204, 155))
                                 );
                    output.Frames.InsertFrame(i, image.Frames.RootFrame);
                }
                if (!isAnimated)
                {
                    output.SaveAsPng(outputStream);
                }
                else
                {
                    output.Frames.RemoveFrame(output.Frames.Count - 1);
                    output.SaveAsGif(outputStream);
                }
            }
            outputStream.Position = 0;
            return(outputStream);
        }
コード例 #22
0
ファイル: Banner.cs プロジェクト: devBanner/devBanner
        public static async Task <string> GenerateAsync(BannerOptions options, Profile profile, string subtext, int width = 800, int height = 192)
        {
            if (profile == null)
            {
                throw new ArgumentNullException(nameof(profile));
            }

            var checkedWidth = CheckWidth(options, width);

            height = (int)(checkedWidth / options.WidthToHeightRatio);

            // Avatar base url + avatar meta = rendered avatar url
            var avatarURL = $"{DevrantAvatarBaseURL}/{profile.Avatar.Image}";

            const string outputDir  = "generated";
            const string avatarsDir = "avatars";

            var outputFileName = $"{profile.Username}.png";

            var workingDir = Directory.GetCurrentDirectory();
            var outputPath = Path.Combine(workingDir, outputDir);

            var avatarPath = Path.Combine(workingDir, avatarsDir);

            Directory.CreateDirectory(outputPath);
            Directory.CreateDirectory(avatarPath);

            var avatarFile = Path.Combine(avatarPath, outputFileName);
            var outputFile = Path.Combine(outputPath, outputFileName);

            byte[] data;

            if (options.CacheAvatars && File.Exists(avatarFile) && File.GetCreationTime(avatarFile) > DateTime.Now.AddMinutes(-options.MaxCacheAvatarAge))
            {
                data = await File.ReadAllBytesAsync(avatarFile);
            }
            else
            {
                // Download rendered avatar
                var httpClient = new HttpClient();

                using (var response = await httpClient.GetAsync(avatarURL))
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new AvatarNotFoundException(profile.Username);
                    }

                    response.EnsureSuccessStatusCode();

                    data = await response.Content.ReadAsByteArrayAsync();

                    if (options.CacheAvatars)
                    {
                        await File.WriteAllBytesAsync(avatarFile, data);
                    }
                }
            }

            using (var avatarImage = Image.Load(data))
                using (var banner = new Image <Rgba32>(checkedWidth, height))
                {
                    var fontCollection = new FontCollection();
                    fontCollection.Install("fonts/Comfortaa-Regular.ttf");

                    var fontSizeUsername = (int)(banner.Width * 0.07); // original : 0.08
                    var fontSizeSubtext  = (int)(banner.Width * 0.04);
                    var fontSizeDevrant  = (int)(banner.Width * 0.02);

                    var fontUsername = fontCollection.CreateFont("Comfortaa", fontSizeUsername, FontStyle.Bold);
                    var fontSubtext  = fontCollection.CreateFont("Comfortaa", fontSizeSubtext, FontStyle.Regular);
                    var fontDevrant  = fontCollection.CreateFont("Comfortaa", fontSizeDevrant, FontStyle.Regular);

                    var avatarHeight = banner.Height;
                    var avatarWidth  = avatarHeight;
                    var avatarSize   = new Size(avatarWidth, avatarHeight);

                    var avatarTargetX = (int)(banner.Width * 0.01875);
                    var avatarTargetY = 0;
                    var avatarTarget  = new Point(avatarTargetX, avatarTargetY);

                    var usernameTargetX = banner.Width / 3;
                    var usernameTargetY = (banner.Height / 4f) - (fontSizeUsername / 2f);
                    var usernameTarget  = new PointF(usernameTargetX, usernameTargetY);

                    var subtextTargetX = usernameTarget.X;
                    var subtextTargetY = usernameTarget.Y + fontSizeUsername;
                    var subtextTarget  = new PointF(subtextTargetX, subtextTargetY + (fontSizeSubtext / 2f));
                    var subTextWidth   = banner.Width - subtextTargetX - (int)(banner.Width * 0.01875);
                    var subTextHeight  = fontSizeSubtext;

                    var devrantTargetX = banner.Width - (int)(banner.Width * 0.130);
                    var devrantTargetY = banner.Height - (int)(banner.Width * 0.03);
                    var devrantTarget  = new Point(devrantTargetX, devrantTargetY);

                    var backgroundColor = Rgba32.FromHex(profile.Avatar.Background);
                    var foregroundColor = GetForegroundColor(backgroundColor);

                    // Draw background
                    banner.SetBGColor(backgroundColor);

                    // Draw avatar
                    banner.DrawImage(avatarImage, avatarSize, avatarTarget);

                    // Draw username
                    banner.DrawText(profile.Username, fontUsername, foregroundColor, usernameTarget, verticalAlignment: VerticalAlignment.Top);

                    // Scale font size to subtext
                    fontSubtext = fontSubtext.ScaleToText(subtext, new SizeF(subTextWidth, subTextHeight), subTextWidth);

                    // Add subtext word wrapping
                    subtext = subtext.AddWrap(fontSubtext, subTextWidth, options.MaxSubtextWraps);

                    // Draw subtext
                    banner.DrawText(subtext, fontSubtext, foregroundColor, subtextTarget, verticalAlignment: VerticalAlignment.Top);

                    // Draw devrant text
                    banner.DrawText("devrant.com", fontDevrant, foregroundColor, devrantTarget, HorizontalAlignment.Left, VerticalAlignment.Top);

                    banner.Save(outputFile, new PngEncoder());
                }

            return(outputFile);
        }
コード例 #23
0
ファイル: OutputText.cs プロジェクト: zxshinxz/ImageSharp
 public OutputText()
 {
     this.FontCollection = new FontCollection();
     this.Font = FontCollection.Install(TestFontUtilities.GetPath("SixLaborsSampleAB.woff")).CreateFont(12);
 }
コード例 #24
0
ファイル: Banner.cs プロジェクト: mscloud/devBanner
        public static async Task <string> GenerateAsync(BannerOptions options, Profile profile, string subtext)
        {
            if (profile == null)
            {
                throw new ArgumentNullException(nameof(profile));
            }

            // Avatar base url + avatar meta = rendered avatar url
            var avatarURL = $"{DevrantAvatarBaseURL}/{profile.Avatar.Image}";

            const string outputDir  = "generated";
            const string avatarsDir = "avatars";

            var outputFileName = $"{profile.Username}.png";

            var workingDir = Directory.GetCurrentDirectory();
            var outputPath = Path.Combine(workingDir, outputDir);

            var avatarPath = Path.Combine(workingDir, avatarsDir);

            Directory.CreateDirectory(outputPath);
            Directory.CreateDirectory(avatarPath);

            var avatarFile = Path.Combine(avatarPath, outputFileName);
            var outputFile = Path.Combine(outputPath, outputFileName);

            byte[] data;

            if (options.CacheAvatars && File.Exists(avatarFile))
            {
                data = await File.ReadAllBytesAsync(avatarFile);
            }
            else
            {
                // Download rendered avatar
                var httpClient = new HttpClient();

                using (var response = await httpClient.GetAsync(avatarURL))
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new AvatarNotFoundException(profile.Username);
                    }

                    response.EnsureSuccessStatusCode();

                    data = await response.Content.ReadAsByteArrayAsync();

                    if (options.CacheAvatars)
                    {
                        await File.WriteAllBytesAsync(avatarFile, data);
                    }
                }
            }

            using (var avatarImage = Image.Load(data))
                using (var banner = new Image <Rgba32>(800, 192))
                {
                    var fontCollection = new FontCollection();
                    fontCollection.Install("fonts/Comfortaa-Regular.ttf");

                    var fontSizeUsername = 64;
                    var fontSizeSubtext  = fontSizeUsername / 2;
                    var fontSizeDevrant  = 16;

                    var fontUsername = fontCollection.CreateFont("Comfortaa", fontSizeUsername, FontStyle.Bold);
                    var fontSubtext  = fontCollection.CreateFont("Comfortaa", fontSizeSubtext, FontStyle.Regular);
                    var fontDevrant  = fontCollection.CreateFont("Comfortaa", fontSizeDevrant, FontStyle.Regular);

                    var avatarHeight = banner.Height;
                    var avatarWidth  = avatarHeight;
                    var avatarSize   = new Size(avatarWidth, avatarHeight);

                    var avatarTargetX = 15;
                    var avatarTargetY = 0;
                    var avatarTarget  = new Point(avatarTargetX, avatarTargetY);

                    var usernameTargetX  = banner.Width / 3;
                    var usernameTartgetY = banner.Height / 4;
                    var usernameTarget   = new Point(usernameTargetX, usernameTartgetY);

                    var subtextTargetX  = usernameTarget.X;
                    var subtextTartgetY = usernameTarget.Y + fontSizeUsername;
                    var subtextTarget   = new Point(subtextTargetX, subtextTartgetY);
                    var subTextWidth    = banner.Width - subtextTargetX - 15;
                    var subTextHeight   = fontSizeSubtext;

                    var devrantTargetX = banner.Width - 108;
                    var devrantTargetY = banner.Height - 4 - fontSizeDevrant;
                    var devrantTarget  = new Point(devrantTargetX, devrantTargetY);

                    // Draw background
                    banner.SetBGColor(Rgba32.FromHex(profile.Avatar.Background));

                    // Draw avatar
                    banner.DrawImage(avatarImage, avatarSize, avatarTarget);

                    // Draw username
                    banner.DrawText(profile.Username, fontUsername, Rgba32.White, usernameTarget);

                    // Scale font size to subtext
                    fontSubtext = fontSubtext.ScaleToText(subtext, new SizeF(subTextWidth, subTextHeight));

                    // Draw subtext
                    banner.DrawText(subtext, fontSubtext, Rgba32.White, subtextTarget);

                    // Draw devrant text
                    banner.DrawText("devrant.com", fontDevrant, Rgba32.White, devrantTarget, HorizontalAlignment.Left, VerticalAlignment.Top);

                    banner.Save(outputFile, new PngEncoder());
                }

            return(outputFile);
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: ywscr/Fonts
        public static void Main(string[] args)
        {
            FontCollection fonts     = new FontCollection();
            FontFamily     font      = fonts.Install(@"..\..\tests\SixLabors.Fonts.Tests\Fonts\SixLaborsSampleAB.ttf");
            FontFamily     fontWoff  = fonts.Install(@"..\..\tests\SixLabors.Fonts.Tests\Fonts\SixLaborsSampleAB.woff");
            FontFamily     font2     = fonts.Install(@"..\..\tests\SixLabors.Fonts.Tests\Fonts\OpenSans-Regular.ttf");
            FontFamily     carter    = fonts.Install(@"..\..\tests\SixLabors.Fonts.Tests\Fonts\Carter_One\CarterOne.ttf");
            FontFamily     Wendy_One = fonts.Install(@"..\..\tests\SixLabors.Fonts.Tests\Fonts\Wendy_One\WendyOne-Regular.ttf");

            RenderText(font, "abc", 72);
            RenderText(font, "ABd", 72);
            RenderText(fontWoff, "abe", 72);
            RenderText(fontWoff, "ABf", 72);
            RenderText(font2, "ov", 72);
            RenderText(font2, "a\ta", 72);
            RenderText(font2, "aa\ta", 72);
            RenderText(font2, "aaa\ta", 72);
            RenderText(font2, "aaaa\ta", 72);
            RenderText(font2, "aaaaa\ta", 72);
            RenderText(font2, "aaaaaa\ta", 72);
            RenderText(font2, "Hello\nWorld", 72);
            RenderText(carter, "Hello\0World", 72);
            RenderText(Wendy_One, "Hello\0World", 72);

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\t\t\tx");

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 0
            }, "Zero\tTab");

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 0
            }, "Zero\tTab");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "One\tTab");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 6
            }, "\tTab Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Tab Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Words Then Tab\t");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "                 Spaces Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Words Then Spaces                 ");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "\naaaabbbbccccddddeeee\n\t\t\t3 tabs\n\t\t\t\t\t5 tabs");

            RenderText(new Font(SystemFonts.Find("Arial"), 20f, FontStyle.Regular), "á é í ó ú ç ã õ", 200, 50);
            RenderText(new Font(SystemFonts.Find("Arial"), 10f, FontStyle.Regular), "PGEP0JK867", 200, 50);

            RenderText(new RendererOptions(SystemFonts.CreateFont("consolas", 72))
            {
                TabWidth = 4
            }, "xxxxxxxxxxxxxxxx\n\txxxx\txxxx\n\t\txxxxxxxx\n\t\t\txxxx");

            BoundingBoxes.Generate("a b c y q G H T", SystemFonts.CreateFont("arial", 40f));

            TextAlignment.Generate(SystemFonts.CreateFont("arial", 50f));
            TextAlignmentWrapped.Generate(SystemFonts.CreateFont("arial", 50f));

            StringBuilder sb = new StringBuilder();

            for (char c = 'a'; c <= 'z'; c++)
            {
                sb.Append(c);
            }
            for (char c = 'A'; c <= 'Z'; c++)
            {
                sb.Append(c);
            }
            for (char c = '0'; c <= '9'; c++)
            {
                sb.Append(c);
            }
            string text = sb.ToString();

            foreach (FontFamily f in fonts.Families)
            {
                RenderText(f, text, 72);
            }
        }
コード例 #26
0
        public String writeMessageOnImage(String text, String text1, String text2, String text3, String text4, int nbArgument)
        {
            String EditFillChemin = "image / update.png";

            FontCollection collection = new FontCollection();
            FontFamily     arial      = collection.Install("font/arial.ttf");
            FontFamily     Burbank    = collection.Install("font/Burbank.ttf");

            using (Image image = Image.Load(convertWebImage()))
            {
                int    fontSize        = image.Width / 5;
                int    fontSizeBorder  = fontSize + 3;
                Font   font            = Burbank.CreateFont(fontSize, FontStyle.Bold);
                Font   fontBorder      = Burbank.CreateFont(fontSizeBorder, FontStyle.Bold);
                String finalText       = "";
                String finalTextBorder = "";

                for (int i = 0; i < nbArgument; i++)
                {
                    switch (i)
                    {
                    case 0:
                        for (int j = 0; j < text.Length; j++)
                        {
                            finalText = finalText + text[j];
                        }

                        break;

                    case 1:
                        for (int j = 0; j < text1.Length; j++)
                        {
                            finalText = finalText + text1[j];
                        }
                        break;

                    case 2:
                        for (int j = 0; j < text2.Length; j++)
                        {
                            finalText = finalText + text2[j];
                        }
                        break;

                    case 3:
                        for (int j = 0; j < text3.Length; j++)
                        {
                            finalText = finalText + text3[j];
                        }
                        break;

                    case 4:
                        for (int j = 0; j < text4.Length; j++)
                        {
                            finalText = finalText + text4[j];
                        }
                        break;
                    }

                    finalText = finalText + "\n";
                }
                finalTextBorder = finalText;
                image.Mutate(x => x.DrawText(finalText, fontBorder, Color.Black, new PointF(image.Width / 100, image.Height / 100)));
                image.Mutate(x => x.DrawText(finalText, font, Color.White, new PointF(image.Width / 100, image.Height / 100)));

                image.Save("image/update.png");
                // image.Save(outPath);
                return(EditFillChemin);
            }
        }
コード例 #27
0
        public ContentManager(
            Game game,
            FileSystem fileSystem,
            GraphicsDevice graphicsDevice,
            SageGame sageGame,
            WndCallbackResolver wndCallbackResolver)
        {
            using (GameTrace.TraceDurationEvent("ContentManager()"))
            {
                _game       = game;
                _fileSystem = fileSystem;

                GraphicsDevice = graphicsDevice;

                SageGame = sageGame;

                Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory);

                IniDataContext = new IniDataContext(fileSystem, sageGame);

                DataContext = new DataContext();

                SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, _fileSystem, IniDataContext);

                switch (sageGame)
                {
                // Only load these INI files for a subset of games, because we can't parse them for others yet.
                case SageGame.CncGenerals:
                case SageGame.CncGeneralsZeroHour:
                case SageGame.Bfme:
                case SageGame.Bfme2:
                case SageGame.Bfme2Rotwk:
                    SubsystemLoader.Load(Subsystem.Core);

                    // TODO: Move this somewhere else.
                    // Subsystem.Core should load mouse and water config, but that isn't the case with at least BFME2.
                    IniDataContext.LoadIniFile(@"Data\INI\Mouse.ini");
                    IniDataContext.LoadIniFile(@"Data\INI\Water.ini");
                    IniDataContext.LoadIniFile(@"Data\INI\AudioSettings.ini");

                    break;

                default:
                    break;
                }

                // TODO: Defer subsystem loading until necessary
                switch (sageGame)
                {
                // Only load these INI files for a subset of games, because we can't parse them for others yet.
                case SageGame.CncGenerals:
                case SageGame.CncGeneralsZeroHour:
                case SageGame.Bfme:
                case SageGame.Bfme2:
                case SageGame.Bfme2Rotwk:
                    SubsystemLoader.Load(Subsystem.Players);
                    SubsystemLoader.Load(Subsystem.ParticleSystems);
                    SubsystemLoader.Load(Subsystem.ObjectCreation);
                    SubsystemLoader.Load(Subsystem.Multiplayer);
                    SubsystemLoader.Load(Subsystem.LinearCampaign);
                    break;

                default:
                    break;
                }

                _contentLoaders = new Dictionary <Type, ContentLoader>
                {
                    { typeof(Model), AddDisposable(new ModelLoader()) },
                    { typeof(Scene3D), AddDisposable(new MapLoader()) },
                    { typeof(Texture), AddDisposable(new TextureLoader(graphicsDevice)) },
                    { typeof(Window), AddDisposable(new WindowLoader(this, wndCallbackResolver, Language)) },
                    { typeof(AptWindow), AddDisposable(new AptLoader()) },
                };

                _cachedObjects = new Dictionary <string, object>();

                TranslationManager = Translation.TranslationManager.Instance;
                Translation.TranslationManager.LoadGameStrings(fileSystem, Language, sageGame);

                _cachedFonts = new Dictionary <FontKey, Font>();

                var linearClampSamplerDescription = SamplerDescription.Linear;
                linearClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp;
                linearClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp;
                linearClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp;
                LinearClampSampler = AddDisposable(
                    graphicsDevice.ResourceFactory.CreateSampler(ref linearClampSamplerDescription));

                var pointClampSamplerDescription = SamplerDescription.Point;
                pointClampSamplerDescription.AddressModeU = SamplerAddressMode.Clamp;
                pointClampSamplerDescription.AddressModeV = SamplerAddressMode.Clamp;
                pointClampSamplerDescription.AddressModeW = SamplerAddressMode.Clamp;
                PointClampSampler = AddDisposable(
                    graphicsDevice.ResourceFactory.CreateSampler(ref pointClampSamplerDescription));

                NullTexture = AddDisposable(graphicsDevice.ResourceFactory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled)));

                _cachedNullStructuredBuffers = new Dictionary <uint, DeviceBuffer>();

                SolidWhiteTexture = AddDisposable(graphicsDevice.CreateStaticTexture2D(
                                                      1, 1, 1,
                                                      new TextureMipMapData(
                                                          new byte[] { 255, 255, 255, 255 },
                                                          4, 4, 1, 1),
                                                      PixelFormat.R8_G8_B8_A8_UNorm));

                ShaderResources = AddDisposable(new ShaderResourceManager(graphicsDevice, SolidWhiteTexture));

                WndImageLoader = AddDisposable(new WndImageLoader(this, new MappedImageLoader(this)));

                _fallbackFonts = new FontCollection();
                var assembly   = Assembly.GetExecutingAssembly();
                var fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Regular.ttf");
                _fallbackFonts.Install(fontStream);
                fontStream = assembly.GetManifestResourceStream($"OpenSage.Content.Fonts.{_fallbackEmbeddedFont}-Bold.ttf");
                _fallbackFonts.Install(fontStream);
            }
        }
コード例 #28
0
ファイル: Images.cs プロジェクト: justuscook/Unimate
        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();
            });
        }
コード例 #29
0
        public static string Generate(string avatarURL, string avatarBGColor, string username, string subtext)
        {
            var workingDir = Directory.GetCurrentDirectory();
            var outputPath = $"{workingDir}/generated/{username}.png";

            // Download rendered avatar
            var httpClient     = new HttpClient();
            var responseStream = httpClient.GetStreamAsync(avatarURL).Result;

            var avatarImage = Image.Load(responseStream);

            System.IO.Directory.CreateDirectory("generated");
            using (Image <Rgba32> banner = new Image <Rgba32>(800, 192))
            {
                var fontCollection = new FontCollection();
                fontCollection.Install("fonts/Comfortaa-Regular.ttf");

                var fontSizeUsername = 64;
                var fontSizeSubtext  = fontSizeUsername / 2;
                var fontSizeDevrant  = 16;

                var fontUsername = fontCollection.CreateFont("Comfortaa", fontSizeUsername, FontStyle.Bold);
                var fontSubtext  = fontCollection.CreateFont("Comfortaa", fontSizeSubtext, FontStyle.Regular);
                var fontDevrant  = fontCollection.CreateFont("Comfortaa", fontSizeDevrant, FontStyle.Regular);

                var avatarHeight = banner.Height;
                var avatarWidth  = avatarHeight;
                var avatarSize   = new Size(avatarWidth, avatarHeight);

                var avatarTargetX = 0;
                var avatarTargetY = 0;
                var avatarTarget  = new Point(avatarTargetX, avatarTargetY);

                var usernameTargetX  = banner.Width / 3;
                var usernameTartgetY = banner.Height / 4;
                var usernameTarget   = new Point(usernameTargetX, usernameTartgetY);

                var subtextTargetX  = usernameTarget.X;
                var subtextTartgetY = usernameTarget.Y + fontSizeUsername;
                var subtextTarget   = new Point(subtextTargetX, subtextTartgetY);

                var devrantTargetX = banner.Width - 108;
                var devrantTargetY = banner.Height - 4 - fontSizeDevrant;
                var devrantTarget  = new Point(devrantTargetX, devrantTargetY);

                // Draw background
                banner.Mutate(i => i.BackgroundColor(Rgba32.FromHex(avatarBGColor)));

                // Draw avatar
                banner.Mutate(i => i.DrawImage(avatarImage, 1, avatarSize, avatarTarget));

                // Draw username
                banner.Mutate(i => i.DrawText(username, fontUsername, Rgba32.White, usernameTarget, new TextGraphicsOptions(true)
                {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment   = VerticalAlignment.Center
                }));

                // Draw subtext
                banner.Mutate(i => i.DrawText(subtext, fontSubtext, Rgba32.White, subtextTarget, new TextGraphicsOptions(true)
                {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment   = VerticalAlignment.Center
                }));

                // Draw devrant text
                banner.Mutate(i => i.DrawText("devrant.com", fontDevrant, Rgba32.White, devrantTarget, new TextGraphicsOptions(true)
                {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment   = VerticalAlignment.Top
                }));

                banner.Save(outputPath);
            }

            responseStream.Close();
            return(outputPath);
        }
コード例 #30
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            logger.LogInformation("Service is starting...");

            app.UseRouting();

            var eventReader = new CloudEventReader(logger);

            var configReader = new ConfigReader(logger);
            var outputBucket = configReader.Read("BUCKET");

            var fontCollection = new FontCollection();

            fontCollection.Install("Arial.ttf");
            var font = fontCollection.CreateFont("Arial", 10);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapPost("/", async context =>
                {
                    try
                    {
                        var(bucket, name) = await eventReader.ReadCloudStorageData(context);

                        using (var inputStream = new MemoryStream())
                        {
                            var client = await StorageClient.CreateAsync();
                            await client.DownloadObjectAsync(bucket, name, inputStream);
                            logger.LogInformation($"Downloaded '{name}' from bucket '{bucket}'");

                            using (var outputStream = new MemoryStream())
                            {
                                inputStream.Position = 0; // Reset to read
                                using (var image = Image.Load(inputStream))
                                {
                                    using (var imageProcessed = image.Clone(ctx => ApplyScalingWaterMarkSimple(ctx, font, Watermark, Color.DeepSkyBlue, 5)))
                                    {
                                        logger.LogInformation($"Added watermark to image '{name}'");
                                        imageProcessed.SaveAsJpeg(outputStream);
                                    }
                                }

                                var outputObjectName = $"{Path.GetFileNameWithoutExtension(name)}-watermark.jpeg";
                                await client.UploadObjectAsync(outputBucket, outputObjectName, "image/jpeg", outputStream);
                                logger.LogInformation($"Uploaded '{outputObjectName}' to bucket '{outputBucket}'");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Error processing: " + e.Message);
                        throw e;
                    }
                });
            });
        }