Added example application

This commit is contained in:
Darth Affe 2024-03-22 23:45:41 +01:00
parent 5346e83b84
commit a198128967
11 changed files with 493 additions and 1 deletions

View File

@ -0,0 +1,42 @@
using System.Windows.Input;
namespace ImageCreationUI;
public class ActionCommand(Action command, Func<bool>? canExecute = null) : ICommand
{
#region Events
public event EventHandler? CanExecuteChanged;
#endregion
#region Methods
public bool CanExecute(object? parameter) => canExecute?.Invoke() ?? true;
public void Execute(object? parameter) => command.Invoke();
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
#endregion
}
public class ActionCommand<T>(Action<T> command, Func<T, bool>? canExecute = null) : ICommand
where T : class
{
#region Events
public event EventHandler? CanExecuteChanged;
#endregion
#region Methods
public bool CanExecute(object? parameter) => canExecute?.Invoke((T)parameter!) ?? true;
public void Execute(object? parameter) => command.Invoke((T)parameter!);
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
#endregion
}

4
ImageCreationUI/App.xaml Normal file
View File

@ -0,0 +1,4 @@
<Application x:Class="ImageCreationUI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" />

View File

@ -0,0 +1,14 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace ImageCreationUI
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,33 @@
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using StableDiffusion.NET.Helper.Images;
namespace ImageCreationUI.Converter;
[ValueConversion(typeof(IImage), typeof(ImageSource))]
public class ImageToImageSourceConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
Bitmap? bitmap = (value as IImage)?.ToBitmap();
if (bitmap == null) return null;
using MemoryStream ms = new();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Position = 0;
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}

View File

@ -0,0 +1,45 @@
using System.Drawing;
using System.Drawing.Imaging;
using StableDiffusion.NET.Helper.Images.Colors;
using StableDiffusion.NET.Helper.Images;
using System.IO;
namespace ImageCreationUI;
public static class ImageExtension
{
public static Bitmap ToBitmap(this IImage image) => image.AsRefImage<ColorRGB>().ToBitmap();
public static Bitmap ToBitmap(this Image<ColorRGB> image) => image.AsRefImage<ColorRGB>().ToBitmap();
public static unsafe Bitmap ToBitmap(this RefImage<ColorRGB> image)
{
Bitmap output = new(image.Width, image.Height, PixelFormat.Format24bppRgb);
Rectangle rect = new(0, 0, image.Width, image.Height);
BitmapData bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);
nint ptr = bmpData.Scan0;
foreach (ReadOnlyRefEnumerable<ColorRGB> row in image.Rows)
{
Span<ColorBGR> target = new((void*)ptr, bmpData.Stride);
for (int i = 0; i < row.Length; i++)
{
ColorRGB srcColor = row[i];
target[i] = new ColorBGR(srcColor.B, srcColor.G, srcColor.R);
}
ptr += bmpData.Stride;
}
output.UnlockBits(bmpData);
return output;
}
public static byte[] ToPng(this IImage image)
{
using Bitmap bitmap = image.ToBitmap();
using MemoryStream ms = new();
bitmap.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\StableDiffusion.NET\StableDiffusion.NET.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=extensions/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -0,0 +1,85 @@
<Window x:Class="ImageCreationUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ImageCreationUI"
xmlns:converter="clr-namespace:ImageCreationUI.Converter"
mc:Ignorable="d"
Title="StableDiffusion.NET" Width="1280" Height="720">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<converter:ImageToImageSourceConverter x:Key="ImageToImageSourceConverter" />
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="400" />
</Grid.ColumnDefinitions>
<StackPanel Margin="4,0" Orientation="Vertical">
<TextBlock Margin="8" Text="This is just an example - inputs are not validated!&#10;Make sure everything is correct before pressing 'Create Image'." />
<Separator />
<Label Content="Model-Path"/>
<DockPanel>
<Button DockPanel.Dock="Right" Width="24" Margin="2,0,0,0" Content="..." Command="{Binding SelectModelCommand}" IsEnabled="{Binding IsReady}" />
<TextBox Text="{Binding ModelPath}" />
</DockPanel>
<Button Margin="0,8" Content="Load Model" Command="{Binding LoadModelCommand}" IsEnabled="{Binding IsReady}" />
<Separator />
<Label Margin="0,8,0,0" Content="Prompt" />
<TextBox Height="80" TextWrapping="Wrap" Text="{Binding Prompt}" />
<Label Content="AntiPrompt" />
<TextBox Height="80" TextWrapping="Wrap" Text="{Binding AntiPrompt}" />
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Label Width="50" Content="Width" />
<TextBox HorizontalAlignment="Left" Width="60" Text="{Binding Width}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Label Width="50" Content="Height" />
<TextBox HorizontalAlignment="Left" Width="60" Text="{Binding Height}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Label Width="50" Content="Cfg" />
<TextBox HorizontalAlignment="Left" Width="60" Text="{Binding Cfg}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Label Width="50" Content="Steps" />
<TextBox HorizontalAlignment="Left" Width="60" Text="{Binding Steps}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Label Width="50" Content="Seed" />
<TextBox HorizontalAlignment="Left" Width="60" Text="{Binding Seed}" />
</StackPanel>
<Button Margin="0,16,0,0" Content="Create Image" Command="{Binding CreateImageCommand}" IsEnabled="{Binding IsReady}" />
<Button Margin="0,16,0,0" Content="Save Image" Command="{Binding SaveImageCommand}" IsEnabled="{Binding IsReady}" />
</StackPanel>
<GridSplitter Grid.Column="1" Margin="2,0" Width="2" Background="DimGray" VerticalAlignment="Stretch" HorizontalAlignment="Center" />
<Image Grid.Column="2" Source="{Binding Image, Converter={StaticResource ImageToImageSourceConverter}}" />
<GridSplitter Grid.Column="3" Margin="2,0" Width="2" Background="DimGray" VerticalAlignment="Stretch" HorizontalAlignment="Center" />
<TextBox Grid.Column="4" IsReadOnly="True" BorderThickness="0" AcceptsReturn="True" Text="{Binding Log}" TextChanged="TextBoxBase_OnTextChanged" />
</Grid>
</Window>

View File

@ -0,0 +1,11 @@
using System.Windows;
using System.Windows.Controls;
namespace ImageCreationUI;
public partial class MainWindow : Window
{
public MainWindow() => InitializeComponent();
private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs args) => (sender as TextBox)?.ScrollToEnd();
}

View File

@ -0,0 +1,225 @@
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Win32;
using StableDiffusion.NET;
using StableDiffusion.NET.Helper.Images;
namespace ImageCreationUI;
public class MainWindowViewModel : INotifyPropertyChanged
{
#region Properties & Fields
private StableDiffusionModel? _model;
private string _modelPath = string.Empty;
public string ModelPath
{
get => _modelPath;
set => SetProperty(ref _modelPath, value);
}
private string _prompt = string.Empty;
public string Prompt
{
get => _prompt;
set => SetProperty(ref _prompt, value);
}
private string _antiPrompt = string.Empty;
public string AntiPrompt
{
get => _antiPrompt;
set => SetProperty(ref _antiPrompt, value);
}
private int _width = 1024;
public int Width
{
get => _width;
set => SetProperty(ref _width, value);
}
private int _height = 1024;
public int Height
{
get => _height;
set => SetProperty(ref _height, value);
}
private float _cfg = 5f;
public float Cfg
{
get => _cfg;
set => SetProperty(ref _cfg, value);
}
private int _steps = 28;
public int Steps
{
get => _steps;
set => SetProperty(ref _steps, value);
}
private int _seed = 0;
public int Seed
{
get => _seed;
set => SetProperty(ref _seed, value);
}
private IImage? _image;
public IImage? Image
{
get => _image;
set => SetProperty(ref _image, value);
}
private string _log = string.Empty;
public string Log
{
get => _log;
set => SetProperty(ref _log, value);
}
private bool _isReady = true;
public bool IsReady
{
get => _isReady;
set => SetProperty(ref _isReady, value);
}
#endregion
#region Commands
private ActionCommand? _loadModelCommand;
public ActionCommand LoadModelCommand => _loadModelCommand ??= new ActionCommand(LoadModel);
private ActionCommand? _createImageCommand;
public ActionCommand CreateImageCommand => _createImageCommand ??= new ActionCommand(CreateImage);
private ActionCommand? _saveImageCommand;
public ActionCommand SaveImageCommand => _saveImageCommand ??= new ActionCommand(SaveImage);
private ActionCommand? _selectModelCommand;
public ActionCommand SelectModelCommand => _selectModelCommand ??= new ActionCommand(SelectModel);
#endregion
#region Constructors
public MainWindowViewModel()
{
StableDiffusionModel.Log += (_, args) => LogLine($"LOG [{args.Level}]: {args.Text}", false);
StableDiffusionModel.Progress += (_, args) => LogLine($"PROGRESS {args.Step} / {args.Steps} ({(args.Progress * 100):N2} %) {args.IterationsPerSecond:N2} it/s ({args.Time})");
}
#endregion
#region Methods
private async void LoadModel()
{
try
{
IsReady = false;
_model?.Dispose();
LogLine($"Loading model '{ModelPath}'");
_model = await Task.Run(() => new StableDiffusionModel(ModelPath, new ModelParameter()));
}
catch (Exception ex)
{
LogLine($"Failed to load model ...{Environment.NewLine}{ex.Message}");
}
finally
{
IsReady = true;
}
}
private async void CreateImage()
{
try
{
IsReady = false;
LogLine("Creating image ...");
using StableDiffusionImage? image = await Task.Run(() => _model?.TextToImage(Prompt, new StableDiffusionParameter
{
NegativePrompt = AntiPrompt,
Width = Width,
Height = Height,
CfgScale = Cfg,
SampleSteps = Steps,
Seed = Seed
}));
Image = image?.ToImage();
LogLine("done!");
}
catch (Exception ex)
{
LogLine($"Failed to create image ...{Environment.NewLine}{ex.Message}");
}
finally
{
IsReady = true;
}
}
private void SaveImage()
{
try
{
if (Image == null) return;
SaveFileDialog saveFileDialog = new() { Filter = "PNG File (*.png)|*.png" };
if (saveFileDialog.ShowDialog() == true)
{
File.WriteAllBytes(saveFileDialog.FileName, Image.ToPng());
LogLine($"Image saved to '{saveFileDialog.FileName}'!");
}
}
catch (Exception ex)
{
LogLine($"Failed to save image ...{Environment.NewLine}{ex.Message}");
}
}
private void SelectModel()
{
OpenFileDialog openFileDialog = new() { Filter = "Stable Diffusion Model|*.*" };
if (openFileDialog.ShowDialog() == true)
ModelPath = openFileDialog.FileName;
}
private void LogLine(string line, bool appendNewLine = true)
{
if (appendNewLine)
Log += line + Environment.NewLine;
else
Log += line;
}
#endregion
#region NotifyPropertyChanged
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
#endregion
}

View File

@ -3,7 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34322.80
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StableDiffusion.NET", "StableDiffusion.NET\StableDiffusion.NET.csproj", "{ED9336F9-7C5F-47DD-A120-272F4835E95F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StableDiffusion.NET", "StableDiffusion.NET\StableDiffusion.NET.csproj", "{ED9336F9-7C5F-47DD-A120-272F4835E95F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{8961F5D8-3F50-4027-8862-635FCA1E1568}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCreationUI", "ImageCreationUI\ImageCreationUI.csproj", "{EB73E250-D2F7-469A-80BF-02C5078546A7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,10 +19,17 @@ Global
{ED9336F9-7C5F-47DD-A120-272F4835E95F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED9336F9-7C5F-47DD-A120-272F4835E95F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED9336F9-7C5F-47DD-A120-272F4835E95F}.Release|Any CPU.Build.0 = Release|Any CPU
{EB73E250-D2F7-469A-80BF-02C5078546A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB73E250-D2F7-469A-80BF-02C5078546A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB73E250-D2F7-469A-80BF-02C5078546A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB73E250-D2F7-469A-80BF-02C5078546A7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{EB73E250-D2F7-469A-80BF-02C5078546A7} = {8961F5D8-3F50-4027-8862-635FCA1E1568}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8DD53974-8766-4659-97B6-4AEDF4323F65}
EndGlobalSection