cambooth/src/CamBooth/CamBooth.App/PictureGallery/PictureGalleryService.cs
2025-01-20 13:54:38 +01:00

76 lines
2.0 KiB
C#

using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using CamBooth.App.Core.AppSettings;
using CamBooth.App.Core.Logging;
using Wpf.Ui.Controls;
namespace CamBooth.App.PictureGallery;
public class PictureGalleryService
{
private readonly AppSettingsService _appSettings;
private readonly Logger _logger;
public List<BitmapImage> ThumbnailsOrderedByNewestDescending =>
this.thumbnails.OrderByDescending(map => map.Key)
.Select(ordered => ordered.Value)
.ToList();
private Dictionary<DateTime, BitmapImage> thumbnails = new();
public PictureGalleryService(AppSettingsService appSettings, Logger logger)
{
this._appSettings = appSettings;
this._logger = logger;
}
public async Task LoadThumbnailsToCache(int cacheSize = 0)
{
this._logger.Info("Start load thumbnails into cache");
string? pictureLocation = this._appSettings.PictureLocation;
int loop = 0;
List<string> picturePaths = Directory.EnumerateFiles(pictureLocation).ToList();
await Task.Run(
() =>
{
do
{
string picturePath = picturePaths[loop];
DateTime creationTime = File.GetCreationTime(picturePath);
// add if not exists
if (!this.thumbnails.ContainsKey(creationTime))
{
this.thumbnails.Add(creationTime, CreateThumbnail(picturePath, 244, 200));
this._logger.Info($"Thumbnail '{picturePath}' successfully created");
}
loop++;
}
while ((loop < cacheSize || cacheSize == 0) && loop < picturePaths.Count);
});
this._logger.Info("Loading thumbnails into cache completed");
}
public static BitmapImage CreateThumbnail(string filePath, int maxWidth, int maxHeight)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(filePath);
bitmap.DecodePixelWidth = maxWidth; // Größe des ThumbnailsOrderedByNewestDescending direkt beim Dekodieren festlegen
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
bitmap.Freeze(); // Threadsicher machen
return bitmap;
}
}