What is the process for creating an instance of a class within a Blazor component and utilizing its methods?

Saeed Pooladzadeh 241 Reputation points
2023-06-16T06:25:34.7466667+00:00

Hello,

My question is regarding Blazor serve:

In my app, I have a component: Logo-builder. razor

@page "/logo-builder"
@using BlazorApp_AI_1.Data
@inject LogoBuiderService logoBuilderService

<h1>Logo Builder</h1>

<label for="text-input">Text:</label>
<input type="text" id="text-input" @bind-value="@LogoText" />
<label for="color-picker">Color:</label>
<input type="color" id="color-picker" @bind-value="@LogoColor" />

<button @onclick="GenerateLogo">Generate Logo</button>

@if (LogoImage != null)
{
    <img src="@LogoImage" alt="Generated Logo" />
}

@code




A LogoBuilderService.cs

here come some part of this class:

public string GenerateLogo(string text, string color)

        {
            // Convert the color string to a Color object
            var colorObj = ColorTranslator.FromHtml(color);

            // Create a new LogoInput object with the user inputs
            var input = new LogoInput { Text = text, Color = colorObj };

            // Feed the LogoInput object to the prediction engine to generate a LogoOutput object
            var output = predictionEngine.Predict(input);

            // Create a new bitmap with the width and height of the generated logo
            var bitmap = new Bitmap(output.Width, output.Height);

            // Create a new Graphics object to draw on the bitmap
            var graphics = Graphics.FromImage(bitmap);

            // Set the background color of the bitmap
            graphics.Clear(output.BackgroundColor);

            // Draw the text on the bitmap using the font name, font size, font color, and positioning from the LogoOutput object

            graphics.DrawString(text, new Font(output.FontName, output.FontSize), new SolidBrush(output.FontColor), new PointF(output.X, output.Y));



            // Convert the bitmap to a PNG image and write it to a memory stream
            var stream = new MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Seek(0, SeekOrigin.Begin);

            // Convert the memory stream to a base64-encoded string and return it
            return $"data:image/png;base64,{Convert.ToBase64String(stream.ToArray())}";

        }

and I have registerd the LogoBuilder.cs in Program.cs

builder.Services.AddSingleton<LogoBuiderService>();

builder.Services.AddScoped<LogoBuiderService>();

How should I instanciate LogoBuilder.cs in component and use the GenerateLogo method?

regards,

Saeed

Developer technologies .NET Blazor
Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2023-06-19T02:46:15.2833333+00:00

    Hi @Saeed Pooladzadeh

    How should I instanciate LogoBuilder.cs in component and use the GenerateLogo method?

    After injecting the LogoBuiderService service, you can directly call the GenerateLogo method in the @code block, the code like this:

    @page "/logo-builder"
    @using BlazorApp_AI_1.Data
    @inject LogoBuiderService logoBuilderService
    
    <h1>Logo Builder</h1>
    
    <label for="text-input">Text:</label>
    <input type="text" id="text-input" @bind-value="@LogoText" />
    <label for="color-picker">Color:</label>
    <input type="color" id="color-picker" @bind-value="@LogoColor" />
    
    <button @onclick="GenerateLogo">Generate Logo</button>
    
    @if (LogoImage != null)
    {
        <img src="@LogoImage" alt="Generated Logo" />
    }
    
    @code { 
        private string LogoText{ get; set; }
        private string LogoColor{ get; set; }
        private string LogoImage{ get; set; }
        private void GenerateLogo()
        {
           LogoImage =  logoBuilderService.GenerateLogo(LogoText,LogoColor);
        }
    }
    

    I also create a sample on my side, the result as below:

    image2


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


  2. Anonymous
    2023-06-22T05:40:27.6233333+00:00

    Hi @Saeed Pooladzadeh

    I wanted to create a program that artificial intelligence would create a logo for itself based on the information received from work. Did I go the wrong way?

    This is a new question. I suggest you can create a thread about this question.

    Besides, you can refer to the following sample: after clicking the generate button, it will generate a captcha code image.

    using BlazorApp1.Data;
    using System.Drawing;
    using System.IO;
    using System.Text;
    
    namespace BlazorApp1.Services
    {
        public class LogoBuilderService
        {
            //public string GenerateLogo(string text, string color)
    
            //{
            //    // Convert the color string to a Color object
            //    var colorObj = ColorTranslator.FromHtml(color);
    
            //    // Create a new LogoInput object with the user inputs
            //    var input = new LogoInput { Text = text, Color = colorObj };
    
            //    // Feed the LogoInput object to the prediction engine to generate a LogoOutput object
            //    var output = //predictionEngine.Predict(input);
    
            //    // Create a new bitmap with the width and height of the generated logo
            //    var bitmap = new Bitmap(output.Width, output.Height);
    
            //    // Create a new Graphics object to draw on the bitmap
            //    var graphics = Graphics.FromImage(bitmap);
    
            //    // Set the background color of the bitmap
            //    graphics.Clear(output.BackgroundColor);
    
            //    // Draw the text on the bitmap using the font name, font size, font color, and positioning from the LogoOutput object
    
            //    graphics.DrawString(text, new Font(output.FontName, output.FontSize), new SolidBrush(output.FontColor), new PointF(output.X, output.Y));
    
    
    
            //    // Convert the bitmap to a PNG image and write it to a memory stream
            //    var stream = new MemoryStream();
            //    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            //    stream.Seek(0, SeekOrigin.Begin);
    
            //    // Convert the memory stream to a base64-encoded string and return it
            //    return $"data:image/png;base64,{Convert.ToBase64String(stream.ToArray())}";
    
            //}
            // Background color 
            private readonly Color bgColor = Color.FromArgb(0xe9, 0xec, 0xef);
            // Code color 
            private readonly Color codeColor = Color.FromArgb(0x00, 0x69, 0xd9);
            // Obstruction color 
            private readonly Color obsColor = Color.FromArgb(0x28, 0xa7, 0x45);
            public (string content, string contentType) GenerateCaptchaImage()
            {
                // Setup output format
                var contentType = "image/png";
                // Image width
                const int imageWidth = 150;
                // Image height
                const int imageHeight = 50;
                // Captcha code length
                const int captchaCodeLength = 4;
                // Captcha code string, all the possible chars that can appear in the image.
                const string captchaCodeString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
                Random random = new Random();
                // Generate random characters
                StringBuilder s = new StringBuilder();
                using var ms = new MemoryStream();
    
                // Create the image
                using Bitmap bitmap = new Bitmap(imageWidth, imageHeight);
                // Create the graphics 
                using Graphics graphics = Graphics.FromImage(bitmap);
                // Write bg color
                graphics.FillRectangle(new SolidBrush(bgColor), 0, 0, imageWidth, imageHeight);
    
                // Add obstructions
                using (Pen pen = new Pen(new SolidBrush(obsColor), 2))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        graphics.DrawLine(pen, new Point(random.Next(0, imageWidth - 1), random.Next(0, imageHeight - 1)), new Point(random.Next(0, imageWidth - 1), random.Next(0, imageHeight - 1)));
                    }
                }
                for (int i = 0; i < 100; i++)
                {
                    bitmap.SetPixel(random.Next(imageWidth), random.Next(imageHeight), Color.FromArgb(random.Next()));
                }
    
                // Font
                using (Font font = new Font(FontFamily.GenericMonospace, 32, FontStyle.Bold | FontStyle.Italic, GraphicsUnit.Pixel))
                {
                    for (int i = 0; i < captchaCodeLength; i++)
                    {
                        s.Append(captchaCodeString.Substring(random.Next(0, captchaCodeString.Length - 1), 1));
                        // Write char to the graphic 
                        graphics.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(codeColor), i * 32, random.Next(0, 24));
                    }
                }
                // Save image, image format type is consistent with response content type.
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                //return (ms.ToArray(), contentType);
    
                return ($"data:image/png;base64,{Convert.ToBase64String(ms.ToArray())}", contentType);
            }
        }
    }
    
    

    blazor component:

    @page "/logobuilder"
    @using BlazorApp1.Data
    @using BlazorApp1.Services
    
    @inject LogoBuilderService _logservice
    
    
    <h1>Logo Builder</h1>
    
    <label for="text-input">Text:</label>
    <input type="text" id="text-input" @bind-value="@LogoText" />
    <label for="color-picker">Color:</label>
    <input type="color" id="color-picker" @bind-value="@LogoColor" />
    
    <button @onclick="GenerateLogo">Generate Logo</button>
     
    @if (LogoImage!=null)
    {
        <img src="@LogoImage" alt="Generated Logo" />
    }
     
    @code { 
        private string LogoText{ get; set; }
        private string LogoColor{ get; set; }
        private string LogoImage{ get; set; }
        private void GenerateLogo()
        {
           LogoImage =   _logservice.GenerateCaptchaImage().content;
        }
    }
    

    The result as below:

    image2


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.