|
1 | 1 | using System; |
| 2 | +using System.Collections.Generic; |
2 | 3 | using System.Drawing.Imaging; |
3 | 4 | using System.IO; |
4 | 5 | using System.Linq; |
@@ -42,7 +43,8 @@ public class ImageService : Service |
42 | 43 | const int ThumbnailSize = 100; |
43 | 44 | readonly string UploadsDir = "~/uploads".MapHostAbsolutePath(); |
44 | 45 | readonly string ThumbnailsDir = "~/uploads/thumbnails".MapHostAbsolutePath(); |
45 | | - |
| 46 | + readonly List<string> ImageSizes = new[] { "320x480", "640x960", "640x1136", "768x1024", "1536x2048" }.ToList(); |
| 47 | + |
46 | 48 | public object Get(Images request) |
47 | 49 | { |
48 | 50 | return Directory.GetFiles(UploadsDir).SafeConvertAll(x => x.SplitOnLast(Path.DirectorySeparatorChar).Last()); |
@@ -79,14 +81,17 @@ private void WriteImage(Stream ms) |
79 | 81 | using (var img = Image.FromStream(ms)) |
80 | 82 | { |
81 | 83 | img.Save(UploadsDir.CombineWith(fileName)); |
82 | | - |
83 | 84 | var stream = Resize(img, ThumbnailSize, ThumbnailSize); |
84 | 85 | File.WriteAllBytes(ThumbnailsDir.CombineWith(fileName), stream.ReadFully()); |
| 86 | + |
| 87 | + ImageSizes.ForEach(x => File.WriteAllBytes( |
| 88 | + AssertDir(UploadsDir.CombineWith(x)).CombineWith(hash + ".png"), |
| 89 | + Get(new Resize { Id = hash, Size = x }).ReadFully())); |
85 | 90 | } |
86 | 91 | } |
87 | 92 |
|
88 | 93 | [AddHeader(ContentType = "image/png")] |
89 | | - public object Get(Resize request) |
| 94 | + public Stream Get(Resize request) |
90 | 95 | { |
91 | 96 | var imagePath = UploadsDir.CombineWith(request.Id + ".png"); |
92 | 97 | if (request.Id == null || !File.Exists(imagePath)) |
@@ -179,17 +184,20 @@ public static Image Crop(Image Image, int newWidth, int newHeight, int startX = |
179 | 184 |
|
180 | 185 | public object Any(Reset request) |
181 | 186 | { |
182 | | - if (!Directory.Exists(UploadsDir)) |
183 | | - Directory.CreateDirectory(UploadsDir); |
184 | | - if (!Directory.Exists(ThumbnailsDir)) |
185 | | - Directory.CreateDirectory(ThumbnailsDir); |
186 | | - |
187 | | - Directory.GetFiles(UploadsDir).ToList().ForEach(File.Delete); |
188 | | - Directory.GetFiles(ThumbnailsDir).ToList().ForEach(File.Delete); |
| 187 | + Directory.GetFiles(AssertDir(UploadsDir)).ToList().ForEach(File.Delete); |
| 188 | + Directory.GetFiles(AssertDir(ThumbnailsDir)).ToList().ForEach(File.Delete); |
189 | 189 | File.ReadAllLines("~/preset-urls.txt".MapHostAbsolutePath()).ToList() |
190 | 190 | .ForEach(url => WriteImage(new MemoryStream(url.Trim().GetBytesFromUrl()))); |
| 191 | + |
191 | 192 | return HttpResult.Redirect("/"); |
192 | 193 | } |
| 194 | + |
| 195 | + private static string AssertDir(string dirPath) |
| 196 | + { |
| 197 | + if (!Directory.Exists(dirPath)) |
| 198 | + Directory.CreateDirectory(dirPath); |
| 199 | + return dirPath; |
| 200 | + } |
193 | 201 | } |
194 | 202 |
|
195 | 203 | public class AppHost : AppHostBase |
|
0 commit comments