4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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);
    }
}

💡 ざっくり使い方

cat.jpg

var analyzer = new GeminiAnalyzer("YOUR_API_KEY");
await analyzer.AnalyzeAsync("この画像に写ってるのは?", "cat.jpg");
回答
この画像に写っているのは、**子猫**です。
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?