There's no wrapper for Google Cloud Gemini API in C# as of now.
Here's how to call the rest API using C#.
private async Task<string> GetAccessTokenAsync()
{
var credential = GoogleCredential.FromFile(serviceAccountPath)
.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
return accessToken;
}Key points:
- Uses a service account JSON
- Requests cloud-platform scope
- Returns a Bearer token for API calls
var endpoint = $"https://{location}-aiplatform.googleapis.com/v1/projects/{projectId}/locations/{location}/publishers/google/models/gemini-2.5-flash-image:generateContent";var requestBody = new
{
contents = new[]
{
new
{
role = "user",
parts = new object[]
{
new { text = $"{prompt}" },
new
{
inlineData = new
{
mimeType = "image/png",
data = referenceImageBase64
}
}
}
}
},
generationConfig = new
{
candidateCount = 1,
mediaResolution = "MEDIA_RESOLUTION_MEDIUM"
}
};Key concepts:
textβ your promptinlineDataβ reference image (base64)- Gemini accepts multi-part input (text + image)
var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
request.Content = content;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await _httpClient.SendAsync(request);Important:
- Uses
HttpClient - Adds
Authorization: Bearer <token> - Sends JSON body
if (root.TryGetProperty("candidates", out var candidates))
{
var candidate = candidates[0];
foreach (var part in parts.EnumerateArray())
{
if (part.TryGetProperty("inlineData", out var inlineData))
{
var mimeType = inlineData.GetProperty("mimeType").GetString();
var dataBase64 = inlineData.GetProperty("data").GetString();
byte[] imageBytes = Convert.FromBase64String(dataBase64);
var outputPath = Path.Combine("output", $"{timestamp}.png");
await File.WriteAllBytesAsync(outputPath, imageBytes);
return outputPath;
}
}
}What happens here:
- Extracts
candidates - Finds
inlineData - Decodes base64 β image bytes
- Saves
.pngfile locally
if (pixel.R < 15 && pixel.G < 15 && pixel.B < 15)
{
pixel.A = 0; // transparent
}Logic:
- Detects near-black pixels
- Converts them to transparent
- Saves new
.transparent.png
var generatedImagePath = await generator.GenerateImageAsync(
ReferenceImagePath,
prompt,
TargetImageSize);
generatedImagePath = await generator.RemoveWhiteBackgroundAsync(generatedImagePath);Flow:
- Generate image via API
- Post-process (remove background)
- Save final output
This system:
- Uses Gemini Image API
- Combines prompt + reference image
- Handles auth, request, parsing
- Outputs a processed PNG
Prompt + Image
β
OAuth2 Token
β
POST β Gemini API
β
Base64 Image Response
β
Decode + Save
β
(Optional) Remove Background