1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using AnimatedGif;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
namespace UVtools.Core.Operations
{
[Serializable]
public sealed class OperationLayerExportGif : Operation
{
#region Members
private string _filePath;
private bool _clipByVolumeBounds;
private bool _renderLayerCount = true;
private byte _fps = 30;
private ushort _repeats;
private ushort _skip;
private decimal _scale = 50;
private Enumerations.RotateDirection _rotateDirection = Enumerations.RotateDirection.None;
private Enumerations.FlipDirection _flipDirection = Enumerations.FlipDirection.None;
#endregion
#region Overrides
public override string Title => "Export layers to GIF";
public override string Description =>
"Export a layer range to an animated GIF file.\n" +
"Note: This process is slow, optimize the parameters to output few layers as possible and/or scale them down.";
public override string ConfirmationText =>
$"export layers {LayerIndexStart} through {LayerIndexEnd} and pack {TotalLayers} layers?";
public override string ProgressTitle =>
$"Exporting layers {LayerIndexStart} through {LayerIndexEnd}";
public override string ProgressAction => "Exported layers";
public override string ValidateInternally()
{
var sb = new StringBuilder();
if (TotalLayers == 0)
{
sb.AppendLine("There are no layers to pack, please adjust the configurations.");
}
/*else if (TotalLayers > 500)
{
sb.AppendLine("Packing more than 500 layers will cause most of the systems and browsers to not play the GIF animation.\n" +
"For that reason the pack is limited to 500 maximum layers.\n" +
"Use the 'Skip layers' option or adjust the layer range to limit the number of layers in the pack.");
}*/
return sb.ToString();
}
public override string ToString()
{
var result = $"[Clip bounds: {_clipByVolumeBounds}]" +
$" [Render count: {_renderLayerCount}]" +
$" [FPS: {_fps}]" +
$" [Repeats: {_repeats}]" +
$" [Skip: {_skip}]" +
$" [Scale: {_scale}%]" +
$" [Rotate: {_rotateDirection}]" +
$" [Flip: {_flipDirection}]" +
LayerRangeString;
if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
return result;
}
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(LayerRangeCount))
{
RaisePropertyChanged(nameof(TotalLayers));
RaisePropertyChanged(nameof(GifDurationMilliseconds));
RaisePropertyChanged(nameof(GifDurationSeconds));
}
base.OnPropertyChanged(e);
}
#endregion
#region Properties
public string FilePath
{
get => _filePath;
set => RaiseAndSetIfChanged(ref _filePath, value);
}
public bool ClipByVolumeBounds
{
get => _clipByVolumeBounds;
set => RaiseAndSetIfChanged(ref _clipByVolumeBounds, value);
}
public bool RenderLayerCount
{
get => _renderLayerCount;
set => RaiseAndSetIfChanged(ref _renderLayerCount, value);
}
public byte FPS
{
get => _fps;
set
{
if(!RaiseAndSetIfChanged(ref _fps, value)) return;
RaisePropertyChanged(nameof(FPSToMilliseconds));
RaisePropertyChanged(nameof(GifDurationMilliseconds));
RaisePropertyChanged(nameof(GifDurationSeconds));
}
}
public int FPSToMilliseconds => 1000 / _fps;
public ushort Repeats
{
get => _repeats;
set => RaiseAndSetIfChanged(ref _repeats, value);
}
public ushort Skip
{
get => _skip;
set
{
if(!RaiseAndSetIfChanged(ref _skip, value)) return;
RaisePropertyChanged(nameof(TotalLayers));
RaisePropertyChanged(nameof(GifDurationMilliseconds));
RaisePropertyChanged(nameof(GifDurationSeconds));
}
}
public uint TotalLayers => (uint)(LayerRangeCount / (float) (_skip + 1));
public uint GifDurationMilliseconds => (uint)(TotalLayers * FPSToMilliseconds);
public float GifDurationSeconds => (float)Math.Round(GifDurationMilliseconds / 1000.0, 2);
public decimal Scale
{
get => _scale;
set => RaiseAndSetIfChanged(ref _scale, Math.Round(value, 2));
}
public float ScaleFactor => (float)_scale / 100f;
public Enumerations.RotateDirection RotateDirection
{
get => _rotateDirection;
set => RaiseAndSetIfChanged(ref _rotateDirection, value);
}
public Enumerations.FlipDirection FlipDirection
{
get => _flipDirection;
set => RaiseAndSetIfChanged(ref _flipDirection, value);
}
#endregion
#region Constructor
public OperationLayerExportGif()
{ }
public OperationLayerExportGif(FileFormat slicerFile) : base(slicerFile)
{
_filePath = SlicerFile.FileFullPath + ".gif";
_skip = TotalLayers switch
{
> 5000 => 2,
> 1000 => 1,
_ => _skip
};
/*while (TotalLayers > 500)
{
_skip++;
}*/
}
#endregion
#region Methods
protected override bool ExecuteInternally(OperationProgress progress)
{
using var gif = AnimatedGif.AnimatedGif.Create(_filePath, FPSToMilliseconds, _repeats);
var layerBuffer = new byte[TotalLayers][];
progress.Reset("Optimized layers", TotalLayers);
var fontFace = FontFace.HersheyDuplex;
float fontScale = 1.5f;
int fontThickness = 2;
MCvScalar textColor = new(200);
if (_clipByVolumeBounds)
{
ROI = SlicerFile.BoundingRectangle;
}
Parallel.For(0, TotalLayers, i =>
{
if (progress.Token.IsCancellationRequested) return;
uint layerIndex = (uint) (LayerIndexStart + i * (_skip + 1));
var layer = SlicerFile[layerIndex];
using var mat = layer.LayerMat;
//using var matOriginal = mat.Clone();
var matRoi = GetRoiOrDefault(mat);
if (_scale != 100)
{
CvInvoke.Resize(matRoi, matRoi, new Size((int) (matRoi.Width * ScaleFactor), (int)(matRoi.Height * ScaleFactor)));
}
if (_flipDirection != Enumerations.FlipDirection.None)
{
CvInvoke.Flip(matRoi, matRoi, Enumerations.ToOpenCVFlipType(_flipDirection));
}
if (_rotateDirection != Enumerations.RotateDirection.None)
{
CvInvoke.Rotate(matRoi, matRoi, Enumerations.ToOpenCVRotateFlags(_rotateDirection));
}
if (_renderLayerCount)
{
int baseLine = 0;
var text = $"{layerIndex.ToString().PadLeft(SlicerFile.LayerCount.ToString().Length, '0')}/{SlicerFile.LayerCount-1}";
var fontSize = CvInvoke.GetTextSize(text, fontFace, fontScale, fontThickness, ref baseLine);
Point point = new(
matRoi.Width / 2 - fontSize.Width / 2,
70);
CvInvoke.PutText(matRoi, text, point, fontFace, fontScale, textColor, fontThickness, LineType.AntiAlias);
}
//ApplyMask(matOriginal, matRoi);
layerBuffer[i] = matRoi.GetPngByes();
progress.LockAndIncrement();
});
progress.ResetNameAndProcessed("Packed layers");
foreach (var buffer in layerBuffer)
{
if (progress.Token.IsCancellationRequested) break;
using Stream stream = new MemoryStream(buffer);
using var img = Image.FromStream(stream);
gif.AddFrame(img, -1, GifQuality.Bit8);
progress++;
}
if (progress.Token.IsCancellationRequested)
{
try
{
File.Delete(_filePath);
}
catch
{
// ignored
}
}
return !progress.Token.IsCancellationRequested;
}
#endregion
#region Equality
private bool Equals(OperationLayerExportGif other)
{
return _clipByVolumeBounds == other._clipByVolumeBounds && _renderLayerCount == other._renderLayerCount && _fps == other._fps && _skip == other._skip && _scale == other._scale && _rotateDirection == other._rotateDirection && _flipDirection == other._flipDirection && _repeats == other._repeats;
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is OperationLayerExportGif other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(_clipByVolumeBounds, _renderLayerCount, _fps, _skip, _scale, (int) _rotateDirection, (int) _flipDirection, _repeats);
}
#endregion
}
}
|