/
Way2enjoy.cs
321 lines (264 loc) · 9.76 KB
/
Way2enjoy.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* @file
* The Way2enjoy API allows you to compress and optimize JPEG, PNG & GIF images.You can also compress PDF, Any Music or Video files
*
* @author
* way2enjoy2 <support@way2enjoy.com>
*
* @documentation
* https://way2enjoy.com/developers
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
/// <summary>
/// The Way2enjoy API allows you to compress and optimize JPEG, PNG & GIF images. YOu can also optimize PDF, Music & Video files
/// </summary>
public class Way2enjoy {
/// <summary>
/// Base 64 encoded API key.
/// </summary>
private string base64ApiKey { get; set; }
/// <summary>
/// HTTP status code from the last request.
/// </summary>
public int LastHttpStatusCode { get; set; }
/// <summary>
/// HTTP status description from the last request.
/// </summary>
public string LastHttpStatusDescription { get; set; }
/// <summary>
/// The Way2enjoy API allows you to compress and optimize JPEG, PNG & GIF images.You can also compress PDF, Music & Video files
/// </summary>
/// <param name="apiKey"></param>
public Way2enjoy(string apiKey) {
this.base64ApiKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey));
}
/// <summary>
/// Scales the image proportionally and crops it if necessary so that the result has exactly the given dimensions. You must provide both a width and a height.
/// </summary>
/// <param name="response">Response object from a upload/shrink operation.</param>
/// <param name="width">Width to scale within.</param>
/// <param name="height">Height to scale within.</param>
/// <param name="outputFile">Filename to save to.</param>
/// <param name="store">Amazon S3 credentials and information.</param>
/// <returns>Stream</returns>
public Stream Cover(Way2enjoyResponse response, int width, int height, string outputFile = null, Way2enjoyOptionsStore store = null) {
return executeOption(response, width, height, "cover", outputFile, store);
}
/// <summary>
/// Scales the image down proportionally so that it fits within the given dimensions. You must provide both a width and a height.
/// </summary>
/// <param name="response">Response object from a upload/shrink operation.</param>
/// <param name="width">Width to scale within.</param>
/// <param name="height">Height to scale within.</param>
/// <param name="outputFile">Filename to save to.</param>
/// <param name="store">Amazon S3 credentials and information.</param>
/// <returns>Stream</returns>
public Stream Fit(Way2enjoyResponse response, int width, int height, string outputFile = null, Way2enjoyOptionsStore store = null) {
return executeOption(response, width, height, "fit", outputFile, store);
}
/// <summary>
/// Scales the image down proportionally. You must provide either a target width or a target height, but not both.
/// </summary>
/// <param name="response">Response object from a upload/shrink operation.</param>
/// <param name="width">Width to scale within.</param>
/// <param name="height">Height to scale within.</param>
/// <param name="outputFile">Filename to save to.</param>
/// <param name="store">Amazon S3 credentials and information.</param>
/// <returns>Stream</returns>
public Stream Scale(Way2enjoyResponse response, int width, int height, string outputFile = null, Way2enjoyOptionsStore store = null) {
return executeOption(response, width, height, "scale", outputFile, store);
}
/// <summary>
/// Upload image to Way2enjoy and attempt to shrink it, lossless.
/// </summary>
/// <param name="inputFile">File to upload.</param>
/// <param name="outputFile">Filename to save to.</param>
/// <param name="store">Amazon S3 credentials and information.</param>
/// <returns>JSON with info about the upload/shrink.</returns>
public Way2enjoyResponse Shrink(string inputFile, string outputFile = null, Way2enjoyOptionsStore store = null) {
var response = new JavaScriptSerializer()
.Deserialize<Way2enjoyResponse>(
getResponse(request(binaryFile: inputFile)));
if (outputFile == null ||
response.output == null ||
string.IsNullOrEmpty(response.output.url))
return response;
if (store != null)
executeOption(
response,
null,
null,
null,
null,
store);
var webClient = new WebClient();
webClient.DownloadFile(
response.output.url,
outputFile);
return response;
}
/// <summary>
/// Execute a set of options against a previous uploaded/shrinked file.
/// </summary>
/// <param name="response">Response object from a upload/shrink operation.</param>
/// <param name="width">Width to scale within.</param>
/// <param name="height">Height to scale within.</param>
/// <param name="method">Scale method to apply.</param>
/// <param name="outputFile">Filename to save to.</param>
/// <param name="store">Amazon S3 credentials and information.</param>
/// <returns>Stream</returns>
private Stream executeOption(Way2enjoyResponse response, int? width, int? height, string method = null, string outputFile = null, Way2enjoyOptionsStore store = null) {
var options = new Way2enjoyOptions();
if (method != null &&
(width.HasValue ||
height.HasValue)) {
options.resize = new Way2enjoyOptionsResize {
method = method
};
if (width.HasValue)
options.resize.width = width.Value;
if (height.HasValue)
options.resize.height = height.Value;
}
if (store != null)
options.store = store;
var stream = request(
"POST",
response.output.url,
null,
options);
writeStreamToDisk(
stream,
outputFile);
return stream;
}
/// <summary>
/// Get the response as a string.
/// </summary>
/// <param name="responseStream">Stream to read from.</param>
/// <returns>String</returns>
private string getResponse(Stream responseStream) {
if (responseStream == null)
return null;
var output = new List<byte>();
var buffer = new byte[1024];
int byteCount;
do {
byteCount = responseStream.Read(buffer, 0, buffer.Length);
for (var i = 0; i < byteCount; i++)
output.Add(buffer[i]);
} while (byteCount > 0);
return Encoding.UTF8.GetString(output.ToArray());
}
/// <summary>
/// Performs the actual communication towards the Way2enjoy API.
/// </summary>
/// <param name="method">HTTP method to perform.</param>
/// <param name="url">URL to request.</param>
/// <param name="binaryFile">File to upload.</param>
/// <param name="options">Options to pass along to the API.</param>
/// <returns>Stream</returns>
private Stream request(string method = "POST", string url = null, string binaryFile = null, Way2enjoyOptions options = null) {
if (url == null)
url = "https://way2enjoy.com/modules/compress-png/way2enjoy-cli2.php";
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null)
throw new WebException("Could not create webrequest.");
request.Method = method;
request.Headers.Add(
"Authorization",
"Basic " + this.base64ApiKey);
if (!string.IsNullOrEmpty(binaryFile)) {
var requestStream = request.GetRequestStream();
var bytes = File.ReadAllBytes(binaryFile);
requestStream.Write(bytes, 0, bytes.Length);
}
if (options != null) {
request.ContentType = "application/json";
var requestStream = request.GetRequestStream();
var json = new JavaScriptSerializer().Serialize(options);
var bytes = Encoding.UTF8.GetBytes(json);
requestStream.Write(bytes, 0, bytes.Length);
}
this.LastHttpStatusCode = 0;
this.LastHttpStatusDescription = null;
HttpWebResponse response = null;
try {
response = request.GetResponse() as HttpWebResponse;
if (response == null)
throw new Exception("Request returned NULL response.");
this.LastHttpStatusCode = (int) response.StatusCode;
this.LastHttpStatusDescription = response.StatusDescription;
}
catch (WebException ex) {
var erres = ex.Response as HttpWebResponse;
if (erres == null)
throw new Exception("Request returned NULL response.");
this.LastHttpStatusCode = (int) erres.StatusCode;
this.LastHttpStatusDescription = erres.StatusDescription;
}
return response != null
? response.GetResponseStream()
: null;
}
/// <summary>
/// Write a stream to disk.
/// </summary>
/// <param name="stream">Stream to write.</param>
/// <param name="outputFile">File to write too.</param>
private void writeStreamToDisk(Stream stream, string outputFile) {
if (outputFile == null)
return;
if (stream == null)
return;
var output = new List<byte>();
var buffer = new byte[1024];
int byteCount;
do {
byteCount = stream.Read(buffer, 0, buffer.Length);
for (var i = 0; i < byteCount; i++)
output.Add(buffer[i]);
} while (byteCount > 0);
using (var fileStream = File.Create(outputFile))
fileStream.Write(output.ToArray(), 0, output.Count);
}
}
public class Way2enjoyResponse {
public Way2enjoyResponseInput input { get; set; }
public Way2enjoyResponseOutput output { get; set; }
public string error { get; set; }
public string message { get; set; }
}
public class Way2enjoyResponseInput {
public int size { get; set; }
public string type { get; set; }
}
public class Way2enjoyResponseOutput {
public int size { get; set; }
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public decimal ratio { get; set; }
public string url { get; set; }
}
public class Way2enjoyOptions {
public Way2enjoyOptionsResize resize { get; set; }
public Way2enjoyOptionsStore store { get; set; }
}
public class Way2enjoyOptionsResize {
public string method { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Way2enjoyOptionsStore {
public string service = "s3";
public string aws_access_key_id { get; set; }
public string aws_secret_access_key { get; set; }
public string region { get; set; }
public string path { get; set; }
}