forked from ecoAPM/SrcSet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResizer.cs
72 lines (66 loc) · 2.41 KB
/
Resizer.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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace ImageResizer
{
public static class Resizer
{
public static void Resize(string filePath, IEnumerable<int> widths)
{
using (var bmp = new Bitmap(filePath))
{
foreach (var width in widths)
{
var aspectRatio = bmp.Size.AspectRatio();
var size = new Size(width, (int)(width / aspectRatio));
Resize(filePath, bmp, size);
}
}
}
private static void Resize(string filePath, Image bmp, Size newSize)
{
var dir = Path.GetDirectoryName(filePath);
if (dir == null)
throw new DirectoryNotFoundException();
var file = Path.GetFileNameWithoutExtension(filePath);
var extension = Path.GetExtension(filePath);
var newFileName = $"{file}-{newSize.Width:D4}{extension}";
var newPath = Path.Combine(dir, newFileName);
if (File.Exists(newPath))
return;
var imageFormat = getImageFormat(extension);
Console.WriteLine(newFileName);
using (var newImage = new Bitmap(newSize.Width, newSize.Height))
{
using (var graphics = Graphics.FromImage(newImage))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(bmp, 0, 0, newSize.Width, newSize.Height);
}
newImage.Save(newPath, imageFormat);
}
}
private static ImageFormat getImageFormat(string extension)
{
switch (extension.ToLower())
{
case ".jpg":
return ImageFormat.Jpeg;
case ".png":
return ImageFormat.Png;
case ".bmp":
return ImageFormat.Bmp;
case ".gif":
return ImageFormat.Gif;
case ".tif":
case ".tiff":
return ImageFormat.Tiff;
default:
throw new BadImageFormatException();
}
}
}
}