C#からGemini APIを使って、画像とテキストを一緒にAIに送って解析してみたメモです。
✅ 対象読者
- Gemini APIをC#から使ってみたい人
- Google_GenerativeAIライブラリの使い方が知りたい人
- Gemini APIで画像解析をしたい人
🔑 Gemini APIキーの取得
APIキーは、Google AI Studio から無料で取得できます。
取得後は、ソースコード中の "YOUR_API_KEY"
の部分に貼り付けてください。
🔧 開発環境
- .NET 8.0
- Google_GenerativeAI 2.7.0
- モデル名:
gemini-2.5-flash
NuGetでのライブラリ追加
dotnet add package Google_GenerativeAI --version 2.7.0
サンプルコード
using GenerativeAI;
using GenerativeAI.Types;
class GeminiAnalyzer
{
private readonly GenerativeModel generativeModel;
public GeminiAnalyzer(string apiKey)
{
if (string.IsNullOrWhiteSpace(apiKey))
throw new ArgumentException("APIキーは必須です。", nameof(apiKey));
generativeModel = new GenerativeModel(apiKey, "models/gemini-2.5-flash");
}
public async Task AnalyzeAsync(string textPrompt, string imagePath)
{
var imageBytes = await File.ReadAllBytesAsync(imagePath);
var imageBase64 = Convert.ToBase64String(imageBytes);
var response = await generativeModel.GenerateContentAsync([
new Part { Text = textPrompt },
new Part {
InlineData = new Blob {
MimeType = "image/jpeg",
Data = imageBase64
}
}
]);
Console.WriteLine(response.Text);
}
}
💡 ざっくり使い方
var analyzer = new GeminiAnalyzer("YOUR_API_KEY");
await analyzer.AnalyzeAsync("この画像に写ってるのは?", "cat.jpg");
回答
この画像に写っているのは、**子猫**です。