关于Blazor服务,我的应用程序中有一个名为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{
}
LogoBuilderService.cs:
以下是这个类的一些部分:
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())}";
}
我已在Program.cs文件中注册LogoBuilder.cs文件。
builder.Services.AddSingleton<LogoBuiderService>();
builder.Services.AddScoped<LogoBuiderService>();
如何在组件中示例化LogoBuilder.cs并使用GenerateLogo方法?
我想在我的组件中使用此服务类。示例化应该如何?
1条答案
按热度按时间yacmzcpb1#
我认为你可以这样使用:
如果你能让
GenerateLogo
返回一个Task<string>
来允许异步操作,也许会更好。