Skip to content

Instantly share code, notes, and snippets.

@k0ta0uchi
Created March 20, 2025 14:55
Show Gist options
  • Save k0ta0uchi/39983a229f287beaae9afdf688f5e942 to your computer and use it in GitHub Desktop.
Save k0ta0uchi/39983a229f287beaae9afdf688f5e942 to your computer and use it in GitHub Desktop.
Gemini API 画像編集サンプル
using System.Text;
using System.Text.Json;
public class GoogleAI
{
private readonly string _apiKey;
public GoogleAI(string apiKey)
{
_apiKey = apiKey;
}
public async Task<string> GenerateContentObject(string contentText, string base64Image, string mimeType, string modelName)
{
var url = $"https://generativelanguage.googleapis.com/v1beta/models/{modelName}:generateContent?key={_apiKey}";
var requestJson = new
{
contents = new object[]
{
new
{
parts = new object[]
{
new { text = contentText },
new
{
inlineData = new
{
mimeType = mimeType,
data = base64Image
}
}
}
}
}
};
var jsonString = JsonSerializer.Serialize(requestJson);
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
using var httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, stringContent);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
private const string ApiKey = "YOUR-API-KEY";
private const string ModelName = "gemini-2.0-flash-exp";
static async Task Main(string[] args)
{
if (string.IsNullOrEmpty(ApiKey))
{
Console.WriteLine("APIキーが設定されていません。");
return;
}
Console.Write("画像ファイルのパスを入力してください:");
var imgPath = Console.ReadLine();
var mimeType = MimeTypes.GetMimeType(Path.GetExtension(imgPath));
Console.Write("編集内容を入力してください:");
var prompt = Console.ReadLine();
try
{
var base64Image = Convert.ToBase64String(File.ReadAllBytes(imgPath));
var genAi = new GoogleAI(ApiKey);
var responseString = await genAi.GenerateContentObject(prompt, base64Image, mimeType, ModelName);
Console.WriteLine("\n応答: " + responseString);
// 画像データを処理
using JsonDocument doc = JsonDocument.Parse(responseString);
if (doc.RootElement.TryGetProperty("candidates", out JsonElement candidates) && candidates.GetArrayLength() > 0)
{
foreach (JsonElement candidate in candidates.EnumerateArray())
{
if (candidate.TryGetProperty("content", out JsonElement content))
{
foreach (JsonElement part in content.GetProperty("parts").EnumerateArray())
{
if (part.TryGetProperty("inlineData", out JsonElement imagePart))
{
string extractedBase64Image = imagePart.GetProperty("data").GetString();
SaveImage(extractedBase64Image, "output.png");
Console.WriteLine("画像が 'output.png' に保存されました。");
}
}
}
}
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTPリクエストでの例外が発生しました: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Inner Exception: {ex.InnerException.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"例外が発生しました: {ex.Message}");
}
}
private static void SaveImage(string base64Image, string outputPath)
{
var imageBytes = Convert.FromBase64String(base64Image);
File.WriteAllBytes(outputPath, imageBytes);
}
}
public static class MimeTypes
{
private static readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string>
{
{ ".jpg", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".png", "image/png" },
{ ".gif", "image/gif" },
// Add more MIME types as needed
};
public static string GetMimeType(string extension)
{
if (_mimeTypes.TryGetValue(extension.ToLower(), out var mimeType))
{
return mimeType;
}
throw new ArgumentException($"Unknown MIME type for extension: {extension}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment