Skip to content

Instantly share code, notes, and snippets.

@elbruno
Created March 27, 2025 15:38
Show Gist options
  • Select an option

  • Save elbruno/869c119f012f7de6c41568cd7fc814d2 to your computer and use it in GitHub Desktop.

Select an option

Save elbruno/869c119f012f7de6c41568cd7fc814d2 to your computer and use it in GitHub Desktop.
ImageGenOpenAIAPITest.cs
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using OpenAI;
using System.Reflection;
// 1. get the image
var imageLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "images", "petsmusic.png");
var mediaType = GetMediaType(imageLocation);
byte[] imageBytes = File.ReadAllBytes(imageLocation);
// 2. prep openai client using gpt-4o
var imageGenPrompt = $"make me a cute minimalist sticker based on the provided image. use a thick white border and transparent background.";
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
IChatClient chatClient = new OpenAIClient(config["OPENAI_APIKEY"]).AsChatClient("gpt-4o");
List<ChatMessage> messages =
[
new ChatMessage(ChatRole.User, imageGenPrompt),
new ChatMessage(ChatRole.User, [new DataContent(imageBytes, mediaType)]),
];
// 3 run image generation
var imageAnalysis = await chatClient.GetResponseAsync(messages);
Console.WriteLine($"Prompt: {imageGenPrompt}");
Console.WriteLine();
Console.WriteLine($"Response: {imageAnalysis.Text}");
Console.WriteLine();
static string GetMediaType(string imageLocation)
{
// Logic to determine the media type based on the file extension
string extension = Path.GetExtension(imageLocation).ToLower();
return extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
_ => throw new NotSupportedException($"File extension {extension} is not supported"),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment