This repository has been archived by the owner on May 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Thumb.aspx.cs
268 lines (242 loc) · 11 KB
/
Thumb.aspx.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
using System;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
/*
Thumb.NET version 3.1, by wyllyan@wyllyan.com
* Parameters
w: Width
h: Height
only w or h: Proportional resize
b: Background color (html type)
c: Condition
= 0 -> don't crop (fixed size)
= 1 -> crop (fixed size)
i: Interpolation Mode
= 0 -> High Quality Bicubic
= 1 -> High Quality Bilinear
p: Precision
*/
public partial class Thumb : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
double proporcao;
int w, h, xCrop, yCrop;
string imgName = Request.QueryString["img"];
byte crop = Convert.ToByte(Request.QueryString["c"]);
string colorName = Request.QueryString["b"];
int interpolationMode = Convert.ToInt16(Request.QueryString["i"]);
//Precisão do redimensionamento
int p = Convert.ToInt32(Request.QueryString["p"]);
int widthT = Convert.ToInt32(Request.QueryString["w"]);
int heightT = Convert.ToInt32(Request.QueryString["h"]);
//Nome da imagem a ser cacheada ou comparada
string strImg = imgName.Substring(0, imgName.LastIndexOf('.')) + "_" + widthT + "x" + heightT + "_" + crop.ToString() + (string.IsNullOrEmpty(colorName) ? "" : "_" + colorName) + "_" + interpolationMode + "_" + p + imgName.Substring(imgName.LastIndexOf('.'));
//Path com as imagens "cacheadas"
string cachePath = Path.Combine(Server.MapPath("~/Arquivos/ThumbCache/"), strImg);
//Dados da última
DateTime dataModCache = File.GetLastWriteTime(Server.MapPath(imgName));
DateTime dataModImg = File.GetLastWriteTime(cachePath);
int comparacao = DateTime.Compare(dataModCache, dataModImg);
//Se o arquivo já existe no cache
if (File.Exists(cachePath) && comparacao <= 0)
{
OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(cachePath));
HttpContext.Current.Response.WriteFile(cachePath);
return;
}
else
{
//Cria diretório com as imagens (parâmetro)
Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
//Deleta se já existe imagem cacheada
if (File.Exists(cachePath))
{
File.Delete(cachePath);
}
//Cria o "bitmap" com imagem original
string imgPath = HttpContext.Current.Request.MapPath("~/" + imgName);
Bitmap bmp = new Bitmap(imgPath);
ImageFormat formato = bmp.RawFormat;
double widthO = bmp.Size.Width;
double heightO = bmp.Size.Height;
//Caso só largura ou altura sejam transmitidas
if (widthT == 0 || heightT == 0)
{
//Cálculo com base na largura (widthT)
if (widthT > 0)
{
heightO = widthT / (widthO / heightO);
widthO = widthT;
heightT = Convert.ToInt32(heightO);
//Cálculo com base na altura (heightT)
}
else
{
widthO = heightT / (heightO / widthO);
heightO = heightT;
widthT = Convert.ToInt32(widthO);
}
}
else
{
//Caso opção seja "CROPAR"
if (crop == 1)
{
//Se uma das medidas originais forem MAIORES que o "Target"
if (widthO > widthT || heightO > heightT)
{
proporcao = widthO / heightO;
while (widthO > widthT || heightO > heightT)
{
widthO--;
heightO = widthO / proporcao;
if (widthO <= widthT && heightO <= heightT)
{
break;
}
}
}
//Se uma das medidas originais forem MENORES que o "Target"
if (widthO < widthT || heightO < heightT)
{
proporcao = widthO / heightO;
while (widthO < widthT || heightO < heightT)
{
widthO++;
heightO = widthO / proporcao;
if (widthO >= widthT && heightO >= heightT)
{
break;
}
}
}
}
else
{
//Se uma das medidas originais forem MAIORES que o "Target"
if (widthO > widthT || heightO > heightT)
{
proporcao = widthO / heightO;
while (widthO > widthT || heightO > heightT)
{
widthO--;
heightO = widthO / proporcao;
if (widthO <= widthT && heightO <= heightT)
{
break;
}
}
}
else
{
//Se uma das medidas originais forem MENORES que o "Target"
if (widthO < widthT || heightO < heightT)
{
proporcao = widthO / heightO;
while (widthO < widthT && heightO < heightT)
{
widthO++;
heightO = widthO / proporcao;
if (widthO >= widthT && heightO >= heightT)
{
break;
}
}
}
}
}
}
//Medidas finais (incluindo valor de precisão)
w = Convert.ToInt32(widthO) + p;
h = Convert.ToInt32(heightO) + p;
//Calcula as coordenadas para corte
xCrop = Convert.ToInt32((w - widthT) / 2);
yCrop = Convert.ToInt32((h - heightT) / 2);
Bitmap bmpT = new Bitmap(widthT, heightT);
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 95L);
//Image codec
ImageCodecInfo imgCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.FormatID == formato.Guid);
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
//Cor de fundo
Color bg = Color.White;
//Caso a cor não seja transmitida
if (string.IsNullOrEmpty(colorName))
{
//se PNG "transparent"
if (formato.Equals(ImageFormat.Png) || formato.Equals(ImageFormat.Gif))
bg = Color.Transparent;
}
else
{
try
{
//Html color (hex)
bg = ColorTranslator.FromHtml("#" + colorName);
}
catch (Exception)
{
//Html color
bg = ColorTranslator.FromHtml(colorName);
}
}
//Manipula e salva em cache
using (Graphics g = Graphics.FromImage(bmpT))
{
g.CompositingQuality = CompositingQuality.HighSpeed;
g.InterpolationMode = interpolationMode == 0 ? InterpolationMode.HighQualityBicubic : InterpolationMode.HighQualityBilinear;
g.CompositingMode = CompositingMode.SourceCopy;
g.Clear(bg);
g.DrawImage(bmp, -xCrop, -yCrop, w, h);
using (MemoryStream memoryStream = new MemoryStream())
{
bmpT.Save(memoryStream, imgCodec, encoderParams);
OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(imgPath));
using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
{
memoryStream.WriteTo(diskCacheStream);
}
memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
}
}
bmp.Dispose();
bmpT.Dispose();
}
}
catch (Exception ex)
{
Font font = new Font("verdana", 12);
Bitmap bmp = new Bitmap(ex.Message.Length * 10, 50);
Graphics g = Graphics.FromImage(bmp);
g.DrawString(ex.Message.Replace("'", ""), font, new SolidBrush(Color.White), new PointF(5.0F, 5.0F));
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
g.Dispose();
bmp.Dispose();
}
}
//Cache Response
private void OutputCacheResponse(HttpContext context, DateTime lastModified)
{
HttpCachePolicy cachePolicy = context.Response.Cache;
cachePolicy.SetCacheability(HttpCacheability.Public);
cachePolicy.VaryByParams["img"] = true;
cachePolicy.VaryByParams["w"] = true;
cachePolicy.VaryByParams["h"] = true;
cachePolicy.VaryByParams["c"] = true;
cachePolicy.VaryByParams["b"] = true;
cachePolicy.VaryByParams["i"] = true;
cachePolicy.VaryByParams["p"] = true;
cachePolicy.SetOmitVaryStar(true);
//cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(1));
cachePolicy.SetExpires(DateTime.Now);
cachePolicy.SetValidUntilExpires(true);
cachePolicy.SetLastModified(lastModified);
}
}