Open doggy8088 opened 4 years ago
public async Task ResizeImagesAsync(string sourcePath, string destPath, double scale, CancellationToken ct)
{
var allFiles = FindImages(sourcePath);
var tasks = new ConcurrentBag<Task>();
var i = 0;
foreach (var filePath in allFiles)
{
i++;
var j = i;
var task = Task.Run(() =>
{
var imgName = Path.GetFileNameWithoutExtension(filePath);
// Console.WriteLine($"tid: {Thread.CurrentThread.ManagedThreadId} running process image name:{imgName}");
var bitmap = SKBitmap.Decode(filePath);
var imgPhoto = SKImage.FromBitmap(bitmap);
var sourceWidth = imgPhoto.Width;
var sourceHeight = imgPhoto.Height;
var destinationWidth = (int) (sourceWidth * scale);
var destinationHeight = (int) (sourceHeight * scale);
using var scaledBitmap = bitmap.Resize(
new SKImageInfo(destinationWidth, destinationHeight),
SKFilterQuality.High);
if (ct.IsCancellationRequested)
{
Console.WriteLine($"{j} {filePath} IsCancellationRequested");
return;
}
using var scaledImage = SKImage.FromBitmap(scaledBitmap);
using var data = scaledImage.Encode(SKEncodedImageFormat.Jpeg, 100);
using var s = File.OpenWrite(Path.Combine(destPath, imgName + ".jpg"));
data.SaveTo(s);
}, ct);
tasks.Add(task);
}
try
{
await Task.WhenAll(tasks);
}
catch (OperationCanceledException oce)
{
foreach (var task in tasks)
{
if (task.IsCanceled)
{
Console.WriteLine($"Task {task.Id}");
}
}
}
}
Program.cs
SKImageProcess.cs