diff options
| author | Jake Mannens <jake@asger.xyz> | 2023-08-29 15:47:37 +1000 |
|---|---|---|
| committer | Jake Mannens <jake@asger.xyz> | 2023-08-29 15:47:37 +1000 |
| commit | cb8c17917d0363f09eeaa3c379617dc213b2dacf (patch) | |
| tree | 9c3c1c15cb6925b31fb9ef3eb93b66fb9e02a5ac /Services/MediaService.cs | |
| parent | d3b8abea30cda6127e9318f7762df175d5f6d459 (diff) | |
Moved thumbnail generation from media controller to media service
Diffstat (limited to 'Services/MediaService.cs')
| -rw-r--r-- | Services/MediaService.cs | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/Services/MediaService.cs b/Services/MediaService.cs index 8c2a5e0..ccee027 100644 --- a/Services/MediaService.cs +++ b/Services/MediaService.cs @@ -24,6 +24,8 @@ public interface IMediaService { public void Delete(Guid media); public void Delete(Media media); + public Stream GetThumbnail(Guid media, int? width, int? height); + public Stream GetThumbnail(Media media, int? width, int? height); public string GetPath(Media media); public string GetPath(Media media, int width, int height); @@ -206,6 +208,41 @@ public class MediaService : IMediaService { public void Delete(Media media) => Delete(media.Guid); + public Stream GetThumbnail(Guid media, int? width, int? height) { + using var db = dbFactory.CreateDbContext(); + var m = db.Media.First(m => m.Guid == media); + if(m is null) + throw new ObjectNotFoundException(media); + + if(m.MimeType.Split("/")[0] != "image") + throw new ThumbnailException("Media object not an image", m); + + using var image = new MagickImage(GetPath(m)); + + if(width is null && height is null) + throw new ThumbnailException("Both width and height cannot be null!", m); + + if(width > image.Width || height > image.Height) + throw new ThumbnailException("Requested thumbnail size is larger than original media", m); + + #pragma warning disable CS8629 + int w = (int) (width is not null ? width : image.Width * height / image.Height); + int h = (int) (height is not null ? height : image.Height * width / image.Width); + #pragma warning restore CS8629 + + var thumbPath = GetPath(m, w, h); + + if(!System.IO.File.Exists(thumbPath)) { + image.Resize(w, h); + image.Write(thumbPath); + } + + return System.IO.File.OpenRead(thumbPath); + } + + public Stream GetThumbnail(Media media, int? width, int? height) => + GetThumbnail(media.Guid, width, height); + public string GetPath(Media media) { var fileInfo = new FileInfo( Path.Join( |
