Implemented gif exportation and added some style (again)

This commit is contained in:
Laurent
2026-02-17 18:20:53 +01:00
parent b81d912cf4
commit 4a5bf8dfff
10 changed files with 268 additions and 101 deletions

View File

@@ -16,7 +16,7 @@ public partial class App : Application
{ {
base.OnStartup(e); base.OnStartup(e);
var viewModel = new MainViewModel(new ResizeService()); var viewModel = new MainViewModel(new GifService());
var mainWindow = new MainWindow(viewModel); var mainWindow = new MainWindow(viewModel);
mainWindow.Show(); mainWindow.Show();

View File

@@ -0,0 +1,18 @@
namespace GifResizer.Models;
public class Format
{
public Format(int width, int height)
{
Width = width;
Height = height;
Checked = true;
}
public int Width { get; private set; }
public int Height { get; private set; }
public bool Checked { get; set; }
public override string ToString() => $"{Width}x{Height}";
}

View File

@@ -1,6 +1,4 @@
using System.Diagnostics; using System.IO;
using System.IO;
using GifResizer.Service;
using SixLabors.ImageSharp; using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing;
@@ -9,7 +7,7 @@ namespace GifResizer.Models;
public class Gif : IDisposable public class Gif : IDisposable
{ {
private readonly FileInfo _file; private readonly string _path;
private Image? _image; private Image? _image;
public Gif(string path) public Gif(string path)
@@ -17,18 +15,19 @@ public class Gif : IDisposable
ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(path);
if (path.Length == 0 || path.IsWhiteSpace() || !File.Exists(path)) if (path.Length == 0 || path.IsWhiteSpace() || !File.Exists(path))
throw new ArgumentException($"File '{path}' does not exist"); throw new ArgumentException($"File '{path}' does not exist");
_path = path;
_file = new FileInfo(path);
} }
public void Load() public void Load()
{ {
_image = Image.Load(_file.FullName); _image = Image.Load(_path);
} }
public void Resize(int width, int height) public void Resize(int width, int height)
{ {
if(_image == null) throw new InvalidOperationException("Image hasn't been loaded yet"); if(_image == null) throw new InvalidOperationException("Image hasn't been loaded yet");
if(width <= 0 || height <= 0) throw new InvalidOperationException("Please specify a valid width or height.");
if(width == _image.Width && height == _image.Height) return;
_image.Mutate(x => x.Resize(width, height)); _image.Mutate(x => x.Resize(width, height));
} }

View File

@@ -0,0 +1,29 @@
using System.IO;
using SixLabors.ImageSharp;
namespace GifResizer.Models;
public class GifData
{
public GifData(string path)
{
Load(path);
}
private void Load(string path)
{
ArgumentNullException.ThrowIfNull(path);
if (path.Length == 0 || path.IsWhiteSpace() || !File.Exists(path))
throw new ArgumentException($"File '{path}' does not exist");
using Image image = Image.Load(path);
Path = path;
Width = image.Width;
Height = image.Height;
}
public string Path { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
}

View File

@@ -0,0 +1,26 @@
using System.IO;
using GifResizer.Models;
namespace GifResizer.Service;
public class GifService
{
public GifService()
{
}
public GifData GetData(string filePath)
{
return new GifData(filePath);
}
public void ResizeGif(string filePath, int width, int height)
{
using Gif gif = new Gif(filePath);
gif.Load();
gif.Resize(width, height);
gif.Save(Path.Combine(Directory.GetCurrentDirectory(), "output", $"{width}x{height}.gif"));
}
}

View File

@@ -1,20 +0,0 @@
using GifResizer.Models;
namespace GifResizer.Service;
public class ResizeService
{
public ResizeService()
{
}
public void ResizeGif(string filePath, int width, int height)
{
using Gif gif = new Gif(filePath);
gif.Load();
gif.Resize(width, height);
gif.Save("D:/test-output.gif");
}
}

View File

@@ -1,33 +1,62 @@
using System.ComponentModel; using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using GifResizer.Models; using GifResizer.Models;
using GifResizer.Service; using GifResizer.Service;
namespace GifResizer.ViewModels; namespace GifResizer.ViewModels;
public class MainViewModel : INotifyPropertyChanged public sealed class MainViewModel : INotifyPropertyChanged
{ {
private readonly GifService _gifService;
private readonly ResizeService _resizeService;
public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangedEventHandler? PropertyChanged;
public MainViewModel(ResizeService service) public MainViewModel(GifService service)
{ {
_resizeService = service; _gifService = service;
FilePath = Directory.GetCurrentDirectory(); CommonFormats = [
new Format(112, 112),
new Format(500, 500),
new Format(1000, 1000)
];
FilePath = null;
} }
public string? FilePath
public string FilePath
{ {
get; get;
set => SetField(ref field, value); set => SetField(ref field, value);
} }
public void ResizeGif(int width, int height) public int? GifWidth
{ {
_resizeService.ResizeGif(FilePath, width, height); get;
set => SetField(ref field, value);
}
public int? GifHeight
{
get;
set => SetField(ref field, value);
}
public List<Format> CommonFormats { get; }
public void LoadGifData(string filePath)
{
GifData data = _gifService.GetData(filePath);
FilePath = filePath;
GifWidth = data.Width;
GifHeight = data.Height;
}
public void ResizeGif()
{
if(FilePath == null && GifWidth == null && GifHeight == null) return;
_gifService.ResizeGif(FilePath!, GifWidth!.Value, GifHeight!.Value);
CommonFormats
.Where(f => f.Checked)
.ToList()
.ForEach(f => _gifService.ResizeGif(FilePath!, f.Width, f.Height));
} }
private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null) private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
@@ -38,7 +67,7 @@ public class MainViewModel : INotifyPropertyChanged
return true; return true;
} }
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{ {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
} }

View File

@@ -0,0 +1,21 @@
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace GifResizer.Views.Converter;
public class VisibleWhenNullConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
bool invert = parameter?.ToString() == "invert";
bool isVisible = invert ? value != null : value == null;
return isVisible ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

View File

@@ -4,70 +4,124 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:gif="http://wpfanimatedgif.codeplex.com" xmlns:gif="http://wpfanimatedgif.codeplex.com"
xmlns:converter="clr-namespace:GifResizer.Views.Converter"
mc:Ignorable="d" mc:Ignorable="d"
Title="Gif resizer" Height="480" Width="640" Title="Gif resizer" Height="480" Width="640"
ResizeMode="NoResize"> ResizeMode="NoResize">
<Grid> <Window.Resources>
<converter:VisibleWhenNullConverter x:Key="VisibleWhenNullConverter"/>
</Window.Resources>
<Grid x:Name="MainContainer">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="3*"/> <RowDefinition Height="*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Border Grid.Row="0" BorderBrush="Gray" <Border Grid.Row="0"
BorderBrush="Gray"
BorderThickness="1" BorderThickness="1"
CornerRadius="5" CornerRadius="5"
Margin="10 10 10 5"> Margin="10 10 10 5">
<Grid Style="{StaticResource DarkGrid}">
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Image gif:ImageBehavior.AnimatedSource="{Binding FilePath}" <!-- GIF -->
Stretch="Uniform" <Grid x:Name="GifPreview"
Visibility="{Binding FilePath}"/> Style="{StaticResource DarkGrid}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" <Image Grid.Column="0" gif:ImageBehavior.AnimatedSource="{Binding FilePath}"
Stretch="UniformToFill"
Visibility="{
Binding FilePath,
Converter={StaticResource VisibleWhenNullConverter},
ConverterParameter=invert
}"
HorizontalAlignment="Left"
VerticalAlignment="Center"/>
<Button Grid.Column="0"
Style="{StaticResource LinkButtonStyle}" Style="{StaticResource LinkButtonStyle}"
Click="BrowseButton_Click" Click="BrowseButton_Click"
Visibility="{
Binding FilePath,
Converter={StaticResource VisibleWhenNullConverter}
}"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center"> VerticalAlignment="Center">
<TextBlock Text="Browse files" <TextBlock
Text="Browse files..."
Width="Auto" Width="Auto"
Height="Auto" Height="Auto"
TextDecorations="Underline"/> TextDecorations="Underline"/>
</Button> </Button>
<TextBlock Grid.Row="1"
Margin="0,0,0,5"
Text="{Binding FilePath,
TargetNullValue=No file selected,
FallbackValue=Gif filepath...}"
Width="Auto"
Height="Auto"
HorizontalAlignment="Left"
VerticalAlignment="Center"/>
</Grid>
</Border>
<Border Grid.Row="1" BorderBrush="Gray" <GridSplitter Grid.Column="1" HorizontalAlignment="Stretch"/>
BorderThickness="1"
CornerRadius="5" <Grid Grid.Column="1" Margin="10">
Padding="5" <Grid.RowDefinitions>
Margin="10 5 10 10"> <RowDefinition Height="75*"/>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center"> <RowDefinition Height="25*"/>
<StackPanel Orientation="Horizontal"> </Grid.RowDefinitions>
<CheckBox Content="112x112" IsChecked="True" Margin="10"/>
<CheckBox Content="500x500" IsChecked="True" Margin="10"/> <StackPanel x:Name="GifInfo" Grid.Row="0">
<CheckBox Content="1000x1000" IsChecked="True" Margin="10"/> <StackPanel Margin="0 0 0 15">
<TextBlock Grid.Row="0" Grid.Column="0">Location</TextBlock>
<TextBlock Text="{Binding FilePath}"/>
</StackPanel> </StackPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">Width</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="2">Height</TextBlock>
<TextBox Grid.Row="1" Grid.Column="0" Text="{Binding GifWidth}"></TextBox>
<TextBox Grid.Row="1" Grid.Column="2" Text="{Binding GifHeight}"></TextBox>
</Grid>
</StackPanel>
<Rectangle Grid.Row="1"
Height="1"
Fill="Gray"
VerticalAlignment="Top"/>
<StackPanel x:Name="Actions" Grid.Row="1" Orientation="Vertical"
HorizontalAlignment="Stretch" VerticalAlignment="Center">
<TextBlock VerticalAlignment="Top" Margin="0 0 0 5">Common formats</TextBlock>
<ItemsControl ItemsSource="{Binding CommonFormats}" Margin="0 0 0 5">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}"
IsChecked="{Binding Checked}"
Margin="0 0 10 5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button <Button
Style="{StaticResource ButtonStyle}" Style="{StaticResource ButtonStyle}"
Content="Resize" Content="Resize"
Click="ResizeButton_Click" Click="ResizeButton_Click"
HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
VerticalAlignment="Center"/>
</StackPanel> </StackPanel>
</Grid>
</Grid>
</Border> </Border>
</Grid> </Grid>
</Window> </Window>

View File

@@ -1,4 +1,5 @@
using System.Windows; using System.Windows;
using System.Windows.Input;
using GifResizer.ViewModels; using GifResizer.ViewModels;
using Microsoft.Win32; using Microsoft.Win32;
@@ -31,21 +32,21 @@ public partial class MainWindow : Window
if (fileDialog.ShowDialog() == true) if (fileDialog.ShowDialog() == true)
{ {
_mainViewModel.FilePath = fileDialog.FileName; _mainViewModel.LoadGifData(fileDialog.FileName);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
DisplayErrorMessage("An error occured while selecting the GIF file: " + ex.Message); DisplayErrorMessage("An error occured while selecting the GIF file: " + ex.Message);
} }
} }
private void ResizeButton_Click(object sender, RoutedEventArgs e) private void ResizeButton_Click(object sender, RoutedEventArgs e)
{ {
try try
{ {
_mainViewModel.ResizeGif(128,128); _mainViewModel.ResizeGif();
DisplaySuccessMessage("Resize successful!");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -53,8 +54,18 @@ public partial class MainWindow : Window
} }
} }
private void IntegerOnly(object sender, TextCompositionEventArgs e)
{
e.Handled = !int.TryParse(e.Text, out _);
}
private void DisplayErrorMessage(string message) private void DisplayErrorMessage(string message)
{ {
MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
} }
private void DisplaySuccessMessage(string message)
{
MessageBox.Show(message, "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
} }