Created
March 27, 2025 15:38
-
-
Save elbruno/869c119f012f7de6c41568cd7fc814d2 to your computer and use it in GitHub Desktop.
ImageGenOpenAIAPITest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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