Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created October 2, 2025 15:03
Show Gist options
  • Save AldeRoberge/140a6e6cc9c029ce7c2135fe455a20f4 to your computer and use it in GitHub Desktop.
Save AldeRoberge/140a6e6cc9c029ce7c2135fe455a20f4 to your computer and use it in GitHub Desktop.
Create images using Stable Diffusion API from C#
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleAvatarGenerator
{
/// <summary>
/// Represents the response from the avatar generation API.
/// </summary>
public class AvatarCreateResponse
{
public string AvatarId { get; set; } = Guid.NewGuid().ToString();
public string Prompt { get; set; } = string.Empty;
public string ImageBase64 { get; set; } = string.Empty;
}
/// <summary>
/// Simple service for generating images from prompts using an API.
/// </summary>
public class AvatarCreateService
{
private const string ApiUrl = "http://127.0.0.1:7860";
private const string Text2ImageEndpoint = "/sdapi/v1/txt2img";
/// <summary>
/// Generates an image from the given prompt.
/// </summary>
/// <param name="prompt">The text prompt for image generation.</param>
/// <param name="negativePrompt">The negative prompt to guide generation.</param>
/// <param name="removeBackground">Whether to remove the background.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The avatar response with base64 image.</returns>
public async Task<AvatarCreateResponse> GenerateImageAsync(
string prompt,
string negativePrompt,
bool removeBackground = true,
CancellationToken ct = default)
{
using var client = new HttpClient();
// Build the JSON payload
var requestJson = new
{
prompt = prompt,
negative_prompt = negativePrompt,
steps = 20,
model = "dreamshaper_8",
script_name = removeBackground ? "ABG Remover" : string.Empty,
script_args = removeBackground ? new object[] { true, false, "", "FFFFFF", false } : null
};
var content = new StringContent(
JsonSerializer.Serialize(requestJson),
Encoding.UTF8,
"application/json"
);
var response = await client.PostAsync($"{ApiUrl}{Text2ImageEndpoint}", content, ct);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync(ct);
var jsonResponse = JsonDocument.Parse(responseBody);
var base64Image = jsonResponse.RootElement
.GetProperty("images")[0]
.GetString();
if (string.IsNullOrEmpty(base64Image))
throw new Exception("No image returned from API.");
return new AvatarCreateResponse
{
Prompt = prompt,
ImageBase64 = base64Image
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment