forked from smartstore/SmartStoreNET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageHeader.cs
More file actions
443 lines (394 loc) · 14.6 KB
/
Copy pathImageHeader.cs
File metadata and controls
443 lines (394 loc) · 14.6 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
namespace SmartStore.Core.IO
{
/// <summary>
/// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349
/// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic
/// to load the image using new Bitmap if reading the headers fails
/// </summary>
public static class ImageHeader
{
internal class UnknownImageFormatException : ArgumentException
{
public UnknownImageFormatException(string paramName = "", Exception e = null)
: base("Could not recognise image format.", paramName, e)
{
}
}
private static readonly Dictionary<byte[], Func<BinaryReader, Size>> _imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()
{
{ new byte[] { 0x42, 0x4D }, DecodeBitmap },
{ new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
{ new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },
{ new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },
{ new byte[] { 0xff, 0xd8 }, DecodeJpeg },
//{ new byte[] { 0xff, 0xd8, 0xff, 0xe0 }, DecodeJpeg },
//{ new byte[] { 0xff }, DecodeJpeg2 }
};
private static readonly int _maxMagicBytesLength = 0;
static ImageHeader()
{
_maxMagicBytesLength = _imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="path">The path of the image to get the dimensions for.</param>
/// <returns>The dimensions of the specified image.</returns>
public static Size GetDimensions(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("File '{0}' does not exist.".FormatInvariant(path));
}
var mime = MimeTypes.MapNameToMimeType(path);
return GetDimensions(File.OpenRead(path), mime, false);
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="buffer">The bytes of the image to get the dimensions for.</param>
/// <param name="mime">The MIME type of the image. Can be <c>null</c>.</param>
/// <returns>The dimensions of the specified image.</returns>
public static Size GetDimensions(byte[] buffer, string mime = null)
{
if (buffer == null || buffer.Length == 0)
{
return Size.Empty;
}
return GetDimensions(new MemoryStream(buffer), mime, false);
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="input">The stream of the image to get the dimensions for.</param>
/// <param name="leaveOpen">If false, the passed stream will get disposed</param>
/// <returns>The dimensions of the specified image.</returns>
public static Size GetDimensions(Stream input, bool leaveOpen = true)
{
return GetDimensions(input, null, leaveOpen);
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="input">The stream of the image to get the dimensions for.</param>
/// <param name="mime">The MIME type of the image. Can be <c>null</c>.</param>
/// <param name="leaveOpen">If false, the passed stream will get disposed</param>
/// <returns>The dimensions of the specified image.</returns>
public static Size GetDimensions(Stream input, string mime, bool leaveOpen = true)
{
Guard.NotNull(input, nameof(input));
var gdip = false;
if (!input.CanSeek || input.Length == 0)
{
return Size.Empty;
}
try
{
//if (mime == "image/jpeg")
//{
// // Reading JPEG header does not work reliably
// gdip = true;
// return GetDimensionsByGdip(input);
//}
if (mime == "image/svg+xml")
{
return GetDimensionsFromSvg(input);
}
using (var reader = new BinaryReader(input, Encoding.Unicode, true))
{
return GetDimensions(reader);
}
}
catch (Exception ex)
{
if (gdip)
{
throw ex;
}
// something went wrong with fast image access,
// so get original size the classic way
try
{
input.Seek(0, SeekOrigin.Begin);
return GetDimensionsByGdip(input);
}
catch
{
throw ex;
}
}
finally
{
if (!leaveOpen)
{
input.Dispose();
}
else
{
input.Seek(0, SeekOrigin.Begin);
}
}
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="path">The path of the image to get the dimensions of.</param>
/// <returns>The dimensions of the specified image.</returns>
/// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
public static Size GetDimensions(BinaryReader binaryReader)
{
byte[] magicBytes = new byte[_maxMagicBytesLength];
for (int i = 0; i < _maxMagicBytesLength; i += 1)
{
magicBytes[i] = binaryReader.ReadByte();
foreach (var kvPair in _imageFormatDecoders)
{
if (StartsWith(magicBytes, kvPair.Key))
{
var size = kvPair.Value(binaryReader);
if (size.IsEmpty)
{
break;
}
else
{
return size;
}
}
}
}
throw new UnknownImageFormatException("binaryReader");
}
private static Size GetDimensionsByGdip(Stream input)
{
using (var b = Image.FromStream(input, false, false))
{
return new Size(b.Width, b.Height);
}
}
private static Size GetDimensionsFromSvg(Stream input)
{
using (var reader = XmlReader.Create(input))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
if (reader.Name == "svg")
{
var width = reader["width"];
var height = reader["height"];
var size = new Size(width.ToInt(), height.ToInt());
if (size.Width == 0 || size.Height == 0)
{
var viewBox = reader["viewBox"];
if (viewBox.HasValue())
{
var arrViewBox = viewBox.Trim().Split(' ');
if (arrViewBox.Length == 4)
{
size = new Size(arrViewBox[2].ToInt(), arrViewBox[3].ToInt());
}
}
}
return size;
}
}
}
}
return Size.Empty;
}
private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)
{
for (int i = 0; i < thatBytes.Length; i += 1)
{
if (thisBytes[i] != thatBytes[i])
{
return false;
}
}
return true;
}
private static short ReadLittleEndianInt16(BinaryReader binaryReader)
{
byte[] bytes = new byte[sizeof(short)];
for (int i = 0; i < sizeof(short); i += 1)
{
bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt16(bytes, 0);
}
private static ushort ReadLittleEndianUInt16(BinaryReader binaryReader)
{
byte[] bytes = new byte[sizeof(ushort)];
for (int i = 0; i < sizeof(ushort); i += 1)
{
bytes[sizeof(ushort) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToUInt16(bytes, 0);
}
private static int ReadLittleEndianInt32(BinaryReader binaryReader)
{
byte[] bytes = new byte[sizeof(int)];
for (int i = 0; i < sizeof(int); i += 1)
{
bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt32(bytes, 0);
}
private static Size DecodeBitmap(BinaryReader binaryReader)
{
binaryReader.ReadBytes(16);
int width = binaryReader.ReadInt32();
int height = binaryReader.ReadInt32();
return new Size(width, height);
}
private static Size DecodeGif(BinaryReader binaryReader)
{
int width = binaryReader.ReadInt16();
int height = binaryReader.ReadInt16();
return new Size(width, height);
}
private static Size DecodePng(BinaryReader binaryReader)
{
binaryReader.ReadBytes(8);
int width = ReadLittleEndianInt32(binaryReader);
int height = ReadLittleEndianInt32(binaryReader);
return new Size(width, height);
}
private static Size DecodeJpeg(BinaryReader reader)
{
string state = "started";
while (true)
{
byte[] c;
if (state == "started")
{
c = reader.ReadBytes(1);
state = (c[0] == 0xFF) ? "sof" : "started";
}
else if (state == "sof")
{
c = reader.ReadBytes(1);
if (c[0] >= 0xe0 && c[0] <= 0xef)
{
state = "skipframe";
}
else if ((c[0] >= 0xC0 && c[0] <= 0xC3) || (c[0] >= 0xC5 && c[0] <= 0xC7) || (c[0] >= 0xC9 && c[0] <= 0xCB) || (c[0] >= 0xCD && c[0] <= 0xCF))
{
state = "readsize";
}
else if (c[0] == 0xFF)
{
state = "sof";
}
else
{
state = "skipframe";
}
}
else if (state == "skipframe")
{
c = reader.ReadBytes(2);
int skip = ReadInt(c) - 2;
reader.ReadBytes(skip);
state = "started";
}
else if (state == "readsize")
{
c = reader.ReadBytes(7);
var width = ReadInt(new[] { c[5], c[6] });
var height = ReadInt(new[] { c[3], c[4] });
return new Size(width, height);
}
}
throw new UnknownImageFormatException();
}
private static int ReadInt(byte[] chars)
{
return (chars[0] << 8) + chars[1];
}
#region Experiments
//private static Size DecodeJpeg2(BinaryReader reader)
//{
// bool found = false;
// bool eof = false;
// while (!found || eof)
// {
// // read 0xFF and the type
// //reader.ReadByte();
// byte type = reader.ReadByte();
// // get length
// int len = 0;
// switch (type)
// {
// // start and end of the image
// case 0xD8:
// case 0xD9:
// len = 0;
// break;
// // restart interval
// case 0xDD:
// len = 2;
// break;
// // the next two bytes is the length
// default:
// int lenHi = reader.ReadByte();
// int lenLo = reader.ReadByte();
// len = (lenHi << 8 | lenLo) - 2;
// break;
// }
// // EOF?
// if (type == 0xD9)
// eof = true;
// // process the data
// if (len > 0)
// {
// // read the data
// byte[] data = reader.ReadBytes(len);
// // this is what we are looking for
// if (type == 0xC0)
// {
// int width = data[1] << 8 | data[2];
// int height = data[3] << 8 | data[4];
// return new Size(width, height);
// }
// }
// }
// throw new UnknownImageFormatException();
//}
//private static Size DecodeJfif(BinaryReader reader)
//{
// while (reader.ReadByte() == 0xff)
// {
// byte marker = reader.ReadByte();
// short chunkLength = ReadLittleEndianInt16(reader);
// if (marker == 0xc0)
// {
// reader.ReadByte();
// int height = ReadLittleEndianInt16(reader);
// int width = ReadLittleEndianInt16(reader);
// return new Size(width, height);
// }
// if (chunkLength < 0)
// {
// ushort uchunkLength = (ushort)chunkLength;
// reader.ReadBytes(uchunkLength - 2);
// }
// else
// {
// reader.ReadBytes(chunkLength - 2);
// }
// }
// throw new UnknownImageFormatException();
//}
#endregion
}
}