-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathImageHelper.cs
786 lines (654 loc) · 33 KB
/
ImageHelper.cs
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
//
// Copyright Fela Ameghino & Contributors 2015-2025
//
// Distributed under the GNU General Public License v3.0. (See accompanying
// file LICENSE or copy at https://www.gnu.org/licenses/gpl-3.0.txt)
//
using Microsoft.Graphics.Canvas;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
using Telegram.Controls;
using Telegram.Entities;
using Telegram.Native;
using Windows.Foundation;
using Windows.Graphics;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
namespace Telegram.Common
{
public static class ImageHelper
{
public static Size Scale(this Size size, double requestedMaxSide)
{
double ratioX = (double)requestedMaxSide / size.Width;
double ratioY = (double)requestedMaxSide / size.Height;
double ratio = Math.Max(ratioX, ratioY);
return new Size(size.Width * ratio, size.Height * ratio);
}
public static Size Scale(double width, double height, double requestedMaxSide)
{
double ratioX = (double)requestedMaxSide / width;
double ratioY = (double)requestedMaxSide / height;
double ratio = Math.Max(ratioX, ratioY);
return new Size(width * ratio, height * ratio);
}
public static async Task<SizeInt32> GetScaleAsync(StorageFile file, bool allowMultipleFrames = false, int requestedMinSide = 1280, BitmapEditState editState = null)
{
try
{
using (var source = await file.OpenReadAsync())
{
var decoder = await BitmapDecoder.CreateAsync(source);
if (decoder.FrameCount > 1 && !allowMultipleFrames)
{
return new SizeInt32 { Width = 0, Height = 0 };
}
var width = decoder.PixelWidth;
var height = decoder.PixelHeight;
if (editState?.Rectangle is Rect crop)
{
width = (uint)(crop.Width * decoder.PixelWidth);
height = (uint)(crop.Height * decoder.PixelHeight);
}
if (width > requestedMinSide || height > requestedMinSide)
{
double ratioX = (double)requestedMinSide / width;
double ratioY = (double)requestedMinSide / height;
double ratio = Math.Min(ratioX, ratioY);
if (editState != null && editState.Rotation is BitmapRotation.Clockwise90Degrees or BitmapRotation.Clockwise270Degrees)
{
return new SizeInt32
{
Width = (int)(height * ratio),
Height = (int)(width * ratio)
};
}
return new SizeInt32
{
Width = (int)(width * ratio),
Height = (int)(height * ratio)
};
}
if (editState != null && editState.Rotation is BitmapRotation.Clockwise90Degrees or BitmapRotation.Clockwise270Degrees)
{
return new SizeInt32
{
Width = (int)(height),
Height = (int)(width)
};
}
return new SizeInt32
{
Width = (int)(width),
Height = (int)(height)
};
}
}
catch
{
return new SizeInt32
{
Width = 0,
Height = 0
};
}
}
/// <summary>
/// Resizes and crops source file image so that resized image width/height are not larger than <param name="requestedMinSide"></param>
/// </summary>
/// <param name="sourceFile">Source StorageFile</param>
/// <param name="resizedImageFile">Target StorageFile</param>
/// <param name="requestedMinSide">Max width/height of the output image</param>
/// <param name="quality">JPEG compression quality (0.77 for pictures, 0.87 for thumbnails)</param>
/// <returns></returns>
public static async Task<StorageFile> ScaleAsync(Guid encoderId, StorageFile sourceFile, StorageFile resizedImageFile, int requestedMinSide = 1280, bool bestQuality = false)
{
using (var source = await sourceFile.OpenReadAsync())
{
return await ScaleAsync(encoderId, source, resizedImageFile, requestedMinSide, bestQuality);
}
}
public static async Task<StorageFile> ScaleAsync(Guid encoderId, IRandomAccessStream source, StorageFile resizedImageFile, int requestedMinSide = 1280, bool bestQuality = false)
{
var decoder = await BitmapDecoder.CreateAsync(source);
//if (decoder.FrameCount > 1)
//{
// throw new InvalidCastException();
//}
var originalPixelWidth = decoder.PixelWidth;
var originalPixelHeight = decoder.PixelHeight;
using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapTransform transform;
if (requestedMinSide > 0 && (decoder.PixelWidth > requestedMinSide || decoder.PixelHeight > requestedMinSide))
{
double ratioX = (double)requestedMinSide / originalPixelWidth;
double ratioY = (double)requestedMinSide / originalPixelHeight;
double ratio = Math.Min(ratioX, ratioY);
uint width = (uint)(originalPixelWidth * ratio);
uint height = (uint)(originalPixelHeight * ratio);
transform = new BitmapTransform
{
ScaledWidth = width,
ScaledHeight = height,
InterpolationMode = bestQuality
? BitmapInterpolationMode.Fant
: BitmapInterpolationMode.Linear
};
}
else
{
transform = new BitmapTransform();
}
var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
// Not using ATM, quality is too low
//var propertySet = new BitmapPropertySet();
//var qualityValue = new BitmapTypedValue(quality, Windows.Foundation.PropertyType.Single);
//propertySet.Add("ImageQuality", qualityValue);
var encoder = await BitmapEncoder.CreateAsync(encoderId, resizedStream/*, propertySet*/);
encoder.SetSoftwareBitmap(pixelData);
await encoder.FlushAsync();
}
return resizedImageFile;
}
public static async Task<StorageFile> TranscodeAsync(IRandomAccessStream source, StorageFile resizedImageFile, Guid encoderId)
{
var decoder = await BitmapDecoder.CreateAsync(source);
//if (decoder.FrameCount > 1)
//{
// throw new InvalidCastException();
//}
using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
{
var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
var encoder = await BitmapEncoder.CreateAsync(encoderId, resizedStream);
encoder.SetSoftwareBitmap(pixelData);
await encoder.FlushAsync();
}
return resizedImageFile;
}
public static async Task<ImageSource> GetPreviewBitmapAsync(StorageMedia source, int requestedMinSide = 1280)
{
try
{
if (source is StorageVideo)
{
int width = 0;
int height = 0;
var buffer = await Task.Run(async () =>
{
using var videoStream = await source.File.OpenReadAsync();
using var animation = VideoAnimation.LoadFromFile(new VideoAnimationStreamSource(videoStream), false, false, false);
if (animation.PixelWidth > requestedMinSide || animation.PixelHeight > requestedMinSide)
{
double ratioX = (double)requestedMinSide / animation.PixelWidth;
double ratioY = (double)requestedMinSide / animation.PixelHeight;
double ratio = Math.Min(ratioX, ratioY);
width = (int)(animation.PixelWidth * ratio);
height = (int)(animation.PixelHeight * ratio);
}
else
{
width = animation.PixelWidth;
height = animation.PixelHeight;
}
var frame = BufferSurface.Create((uint)(width * height * 4));
animation.RenderSync(frame, width, height, true, out _);
return frame;
});
if (width > 0 && height > 0)
{
var bitmap = new WriteableBitmap(width, height);
BufferSurface.Copy(buffer, bitmap.PixelBuffer);
return bitmap;
}
}
else if (source is StoragePhoto)
{
using var imageStream = await source.File.OpenReadAsync();
return await GetPreviewBitmapAsync(imageStream, requestedMinSide);
}
}
catch { }
return null;
}
public static async Task<ImageSource> GetPreviewBitmapAsync(IRandomAccessStream source, int requestedMinSide = 1280)
{
var decoder = await BitmapDecoder.CreateAsync(source);
if (decoder.BitmapPixelFormat == BitmapPixelFormat.Bgra8)
{
var originalPixelWidth = decoder.PixelWidth;
var originalPixelHeight = decoder.PixelHeight;
BitmapTransform transform;
if (decoder.PixelWidth > requestedMinSide || decoder.PixelHeight > requestedMinSide)
{
double ratioX = (double)requestedMinSide / originalPixelWidth;
double ratioY = (double)requestedMinSide / originalPixelHeight;
double ratio = Math.Min(ratioX, ratioY);
uint width = (uint)(originalPixelWidth * ratio);
uint height = (uint)(originalPixelHeight * ratio);
transform = new BitmapTransform
{
ScaledWidth = width,
ScaledHeight = height,
InterpolationMode = BitmapInterpolationMode.Linear
};
}
else
{
transform = new BitmapTransform();
}
var bitmap = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
var bitmapImage = new SoftwareBitmapSource();
await bitmapImage.SetBitmapAsync(bitmap);
return bitmapImage;
}
else
{
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(source);
return bitmap;
}
}
public static async Task<StorageFile> CropAsync(StorageFile sourceFile, StorageFile file, Rect cropRectangle, int min = 1280, int max = 0, double quality = 0.77, BitmapRotation rotation = BitmapRotation.None, BitmapFlip flip = BitmapFlip.None, TimeSpan? trimStart = null)
{
file ??= await ApplicationData.Current.TemporaryFolder.CreateFileAsync("crop.jpg", CreationCollisionOption.ReplaceExisting);
using (var source = await OpenReadAsync(sourceFile))
using (var destination = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var decoder = await BitmapDecoder.CreateAsync(source);
var cropWidth = (double)decoder.PixelWidth;
var cropHeight = (double)decoder.PixelHeight;
if (decoder.PixelWidth > 1280 || decoder.PixelHeight > 1280)
{
double ratioX = 1280d / cropWidth;
double ratioY = 1280d / cropHeight;
double ratio = Math.Min(ratioX, ratioY);
cropWidth *= ratio;
cropHeight *= ratio;
}
if (cropRectangle.Right <= 1 && cropRectangle.Bottom <= 1)
{
cropRectangle = new Rect(
cropRectangle.X * decoder.PixelWidth,
cropRectangle.Y * decoder.PixelHeight,
cropRectangle.Width * decoder.PixelWidth,
cropRectangle.Height * decoder.PixelHeight);
}
if (rotation != BitmapRotation.None)
{
cropRectangle = RotateArea(cropRectangle, decoder.PixelWidth, decoder.PixelHeight, (int)rotation);
}
if (flip == BitmapFlip.Horizontal)
{
cropRectangle = FlipArea(cropRectangle, decoder.PixelWidth);
}
var (scaledCrop, scaledSize) = Scale(cropRectangle, new Size(decoder.PixelWidth, decoder.PixelHeight), new Size(cropWidth, cropHeight), min, max);
var bounds = new BitmapBounds();
bounds.X = (uint)scaledCrop.X;
bounds.Y = (uint)scaledCrop.Y;
bounds.Width = (uint)scaledCrop.Width;
bounds.Height = (uint)scaledCrop.Height;
var transform = new BitmapTransform();
transform.ScaledWidth = (uint)scaledSize.Width;
transform.ScaledHeight = (uint)scaledSize.Height;
transform.Bounds = bounds;
transform.InterpolationMode = BitmapInterpolationMode.Linear;
transform.Rotation = rotation;
transform.Flip = flip;
var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
// Not using ATM, quality is too low
//var propertySet = new BitmapPropertySet();
//var qualityValue = new BitmapTypedValue(quality, PropertyType.Single);
//propertySet.Add("ImageQuality", qualityValue);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destination);
encoder.SetSoftwareBitmap(pixelData);
await encoder.FlushAsync();
}
return file;
}
private static Rect RotateArea(Rect area, uint width, uint height, int count)
{
for (int i = 0; i < count; i++)
{
var point = new Point(height - area.Bottom, width - (width - area.X));
area = new Rect(point.X, point.Y, area.Height, area.Width);
var temp = width;
width = height;
height = temp;
}
return area;
}
private static Rect FlipArea(Rect area, uint width)
{
var point = new Point(width - area.Right, area.Y);
var result = new Rect(point.X, point.Y, area.Width, area.Height);
return result;
}
private static (Rect, Size) Scale(Rect rect, Size start, Size size, int min, int max)
{
var width = rect.Width * size.Width / start.Width;
var height = rect.Height * size.Height / start.Height;
if (width > min || height > min)
{
double ratioX = min / width;
double ratioY = min / height;
double ratio = Math.Min(ratioX, ratioY);
width *= ratio;
height *= ratio;
}
if (width < max || height < max)
{
double ratioX = max / width;
double ratioY = max / height;
double ratio = Math.Min(ratioX, ratioY);
width *= ratio;
height *= ratio;
}
var ratioW = start.Width * width / rect.Width;
var ratioH = start.Height * height / rect.Height;
var x = rect.X * ratioW / start.Width;
var y = rect.Y * ratioH / start.Height;
var w = rect.Width * ratioW / start.Width;
var h = rect.Height * ratioH / start.Height;
return (new Rect(x, y, w, h), new Size(ratioW, ratioH));
}
public static async Task<ImageSource> CropAndPreviewAsync(StorageMedia source, BitmapEditState editState)
{
if (source is StorageVideo)
{
using var videoStream = await source.File.OpenReadAsync();
using var animation = await Task.Run(() => VideoAnimation.LoadFromFile(new VideoAnimationStreamSource(videoStream), false, false, false));
if (editState.TrimStartTime is TimeSpan trimStart && trimStart > TimeSpan.Zero)
{
animation.SeekToMilliseconds((long)trimStart.TotalMilliseconds, false);
}
int width = animation.PixelWidth;
int height = animation.PixelHeight;
var frame = BufferSurface.Create((uint)(width * height * 4));
await Task.Run(() => animation.RenderSync(frame, width, height, true, out _));
using var stream = new InMemoryRandomAccessStream();
PlaceholderImageHelper.Current.Encode(frame, stream, width, height);
return await CropAndPreviewAsync(stream, editState);
}
else
{
using var imageStream = await source.File.OpenReadAsync();
return await CropAndPreviewAsync(imageStream, editState);
}
}
public static async Task<ImageSource> CropAndPreviewAsync(IRandomAccessStream source, BitmapEditState editState, int maxSize = 1280)
{
var decoder = await BitmapDecoder.CreateAsync(source);
var cropWidth = (double)decoder.PixelWidth;
var cropHeight = (double)decoder.PixelHeight;
if (decoder.PixelWidth > maxSize || decoder.PixelHeight > maxSize)
{
double ratioX = maxSize / cropWidth;
double ratioY = maxSize / cropHeight;
double ratio = Math.Min(ratioX, ratioY);
cropWidth *= ratio;
cropHeight *= ratio;
}
var cropRectangle = new Rect(
editState.Rectangle.X * decoder.PixelWidth,
editState.Rectangle.Y * decoder.PixelHeight,
editState.Rectangle.Width * decoder.PixelWidth,
editState.Rectangle.Height * decoder.PixelHeight);
if (editState.Rotation != BitmapRotation.None)
{
cropRectangle = RotateArea(cropRectangle, decoder.PixelWidth, decoder.PixelHeight, (int)editState.Rotation);
}
if (editState.Flip == BitmapFlip.Horizontal)
{
cropRectangle = FlipArea(cropRectangle, decoder.PixelWidth);
}
var (scaledCrop, scaledSize) = Scale(cropRectangle, new Size(decoder.PixelWidth, decoder.PixelHeight), new Size(cropWidth, cropHeight), maxSize, 0);
var bounds = new BitmapBounds();
bounds.X = (uint)scaledCrop.X;
bounds.Y = (uint)scaledCrop.Y;
bounds.Width = (uint)scaledCrop.Width;
bounds.Height = (uint)scaledCrop.Height;
var transform = new BitmapTransform();
transform.ScaledWidth = (uint)scaledSize.Width;
transform.ScaledHeight = (uint)scaledSize.Height;
transform.Bounds = bounds;
transform.InterpolationMode = BitmapInterpolationMode.Linear;
transform.Rotation = editState.Rotation;
transform.Flip = editState.Flip;
var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
if (editState.Strokes != null)
{
using (var stream = await DrawStrokesAsync(pixelData, editState.Strokes, editState.Rectangle, editState.Rotation, editState.Flip))
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
return bitmapImage;
}
}
else
{
var bitmapImage = new SoftwareBitmapSource();
await bitmapImage.SetBitmapAsync(pixelData);
return bitmapImage;
}
}
public static async Task<IRandomAccessStream> OpenReadAsync(StorageFile sourceFile, TimeSpan? trimStart = null)
{
if (sourceFile.FileType.Equals(".mp4", StringComparison.OrdinalIgnoreCase))
{
return await Task.Run(async () =>
{
using var videoStream = await sourceFile.OpenReadAsync();
using var animation = VideoAnimation.LoadFromFile(new VideoAnimationStreamSource(videoStream), false, false, false);
if (trimStart > TimeSpan.Zero)
{
animation.SeekToMilliseconds((long)trimStart.Value.TotalMilliseconds, false);
}
int width = animation.PixelWidth;
int height = animation.PixelHeight;
var frame = BufferSurface.Create((uint)(width * height * 4));
var result = animation.RenderSync(frame, width, height, true, out _);
var stream = new InMemoryRandomAccessStream();
PlaceholderImageHelper.Current.Encode(frame, stream, width, height);
return stream;
});
}
else
{
return await sourceFile.OpenReadAsync();
}
}
public static BitmapTransform ComputeScalingTransformForSourceImage(BitmapDecoder sourceDecoder)
{
var transform = new BitmapTransform();
if (sourceDecoder.PixelWidth > 1280 || sourceDecoder.PixelHeight > 1280)
{
double ratioX = (double)1280 / sourceDecoder.PixelWidth;
double ratioY = (double)1280 / sourceDecoder.PixelHeight;
double ratio = Math.Min(ratioX, ratioY);
transform.ScaledWidth = (uint)(sourceDecoder.PixelWidth * ratio);
transform.ScaledHeight = (uint)(sourceDecoder.PixelHeight * ratio);
transform.InterpolationMode = BitmapInterpolationMode.Linear;
}
return transform;
}
public static async Task<IRandomAccessStream> DrawStrokesAsync(SoftwareBitmap file, IReadOnlyList<SmoothPathBuilder> strokes, Rect rectangle, BitmapRotation rotation, BitmapFlip flip)
{
var device = ElementComposition.GetSharedDevice();
var bitmap = CanvasBitmap.CreateFromSoftwareBitmap(device, file);
var canvas1 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
var canvas2 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
var size = canvas1.Size.ToVector2();
var canvasSize = canvas1.Size.ToVector2();
var scaleX = 1 / (float)rectangle.Width;
var scaleY = 1 / (float)rectangle.Height;
var offsetX = (float)rectangle.X * scaleX;
var offsetY = (float)rectangle.Y * scaleY;
if (rotation is BitmapRotation.Clockwise270Degrees or BitmapRotation.Clockwise90Degrees)
{
size = new Vector2(size.Y, size.X);
scaleX = scaleY;
scaleY = 1 * 1 / (float)rectangle.Width;
}
using (var session = canvas1.CreateDrawingSession())
{
switch (rotation)
{
case BitmapRotation.Clockwise90Degrees:
var transform1 = Matrix3x2.CreateRotation(MathFEx.ToRadians(90));
transform1.Translation = new Vector2(size.Y, 0);
session.Transform = transform1;
break;
case BitmapRotation.Clockwise180Degrees:
var transform2 = Matrix3x2.CreateRotation(MathFEx.ToRadians(180));
transform2.Translation = new Vector2(size.X, size.Y);
session.Transform = transform2;
break;
case BitmapRotation.Clockwise270Degrees:
var transform3 = Matrix3x2.CreateRotation(MathFEx.ToRadians(270));
transform3.Translation = new Vector2(0, size.X);
session.Transform = transform3;
break;
}
switch (flip)
{
case BitmapFlip.Horizontal:
switch (rotation)
{
case BitmapRotation.Clockwise90Degrees:
case BitmapRotation.Clockwise270Degrees:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
break;
default:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
break;
}
break;
case BitmapFlip.Vertical:
switch (rotation)
{
case BitmapRotation.None:
case BitmapRotation.Clockwise180Degrees:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
break;
default:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
break;
}
break;
}
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(scaleX, scaleY));
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateTranslation(-(offsetX * size.X), -(offsetY * size.Y)));
foreach (var builder in strokes)
{
PencilCanvas.DrawPath(session, builder, size);
}
}
using (var session = canvas2.CreateDrawingSession())
{
session.DrawImage(bitmap);
session.DrawImage(canvas1);
}
bitmap.Dispose();
var stream = new InMemoryRandomAccessStream();
await canvas2.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg/*, 0.77f*/);
canvas2.Dispose();
canvas1.Dispose();
stream.Seek(0);
return stream;
}
public static async Task<StorageFile> DrawStrokesAsync(StorageFile file, IReadOnlyList<SmoothPathBuilder> strokes, Rect rectangle, BitmapRotation rotation, BitmapFlip flip)
{
var device = ElementComposition.GetSharedDevice();
var bitmap = await CanvasBitmap.LoadAsync(device, file.Path);
var canvas1 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
var canvas2 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
var size = canvas1.Size.ToVector2();
var canvasSize = canvas1.Size.ToVector2();
var scaleX = 1 / (float)rectangle.Width;
var scaleY = 1 / (float)rectangle.Height;
var offsetX = (float)rectangle.X * scaleX;
var offsetY = (float)rectangle.Y * scaleY;
if (rotation is BitmapRotation.Clockwise270Degrees or BitmapRotation.Clockwise90Degrees)
{
size = new Vector2(size.Y, size.X);
scaleX = scaleY;
scaleY = 1 * 1 / (float)rectangle.Width;
}
using (var session = canvas1.CreateDrawingSession())
{
switch (rotation)
{
case BitmapRotation.Clockwise90Degrees:
var transform1 = Matrix3x2.CreateRotation(MathFEx.ToRadians(90));
transform1.Translation = new Vector2(size.Y, 0);
session.Transform = transform1;
break;
case BitmapRotation.Clockwise180Degrees:
var transform2 = Matrix3x2.CreateRotation(MathFEx.ToRadians(180));
transform2.Translation = new Vector2(size.X, size.Y);
session.Transform = transform2;
break;
case BitmapRotation.Clockwise270Degrees:
var transform3 = Matrix3x2.CreateRotation(MathFEx.ToRadians(270));
transform3.Translation = new Vector2(0, size.X);
session.Transform = transform3;
break;
}
switch (flip)
{
case BitmapFlip.Horizontal:
switch (rotation)
{
case BitmapRotation.Clockwise90Degrees:
case BitmapRotation.Clockwise270Degrees:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
break;
default:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
break;
}
break;
case BitmapFlip.Vertical:
switch (rotation)
{
case BitmapRotation.None:
case BitmapRotation.Clockwise180Degrees:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
break;
default:
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
break;
}
break;
}
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(scaleX, scaleY));
session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateTranslation(-(offsetX * size.X), -(offsetY * size.Y)));
foreach (var builder in strokes)
{
PencilCanvas.DrawPath(session, builder, size);
}
}
using (var session = canvas2.CreateDrawingSession())
{
session.DrawImage(bitmap);
session.DrawImage(canvas1);
}
bitmap.Dispose();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await canvas2.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg/*, 0.77f*/);
}
canvas2.Dispose();
canvas1.Dispose();
return file;
}
}
}