SK也对应了文生图的功能,本文中分别使用的是GPT的DALL·E 2和DALL·E 3来生成图版,虽然不如专业的文生图那么专业,但提示词到位,在一些场景中还是可用的。
下面是最简单的文生图的代码实现,通过TextToImage服务来完成生成,GPT中生成图的尺寸要求是:256x256, 512x512, 1024x1024, 1024x1792,'1792x1024]
代码:
public static class TextToImageSample
{
public static async Task Exec()
{
#pragma warning disable SKEXP0010
var builder = Kernel.CreateBuilder()
.AddOpenAITextToImage(Config.OpenAiKey, modelId: "dall-e-2");
#pragma warning restore SKEXP0010
var kernel = builder.Build();
var prompt1 = $"背景是白色,用墨水,画一匹腾空跃起的骏马。要求马位中图的中央,显示完整。";
await CreateImageAsync(kernel,prompt1);
Console.ReadKey();
}
private static async Task CreateImageAsync(Kernel kernel,string prompt)
{
#pragma warning disable SKEXP0001
var dallE = kernel.GetRequiredService<ITextToImageService>();
var imageUrl = await dallE.GenerateImageAsync(prompt, 1024, 1024);
await DownLoadImageAsync(imageUrl);
}
private static async Task DownLoadImageAsync(string imageUrl){
var localPath = "downloaded_image.jpg";
using (var client = new HttpClient()) {
var response = await client.GetAsync(imageUrl);
response.EnsureSuccessStatusCode();
var imageBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync(localPath, imageBytes);
Console.WriteLine("图片下载成功,保存在:" + localPath); }
Process.Start(new ProcessStartInfo(localPath) { UseShellExecute = true });}
}
生成图片:
接下来把上面代码第10行修改成DALL·E 3,来看一下效果:
.AddOpenAITextToImage(key,modelId: "dall-e-3)
标签:Kernel,semantic,kernel,await,localPath,static,文转图,var
From: https://www.cnblogs.com/fanfan-90/p/18533661