6 using System.Collections.Generic;
15 public static Dimensions GetJpegDimensions(byte[] bytes)
17 using (var ms =
new MemoryStream(bytes))
19 return GetJpegDimensions(ms);
23 public static Dimensions GetJpegDimensions(
string filePath)
25 using (var fs = File.OpenRead(filePath))
27 return GetJpegDimensions(fs);
31 public static Dimensions GetJpegDimensions(Stream fs)
33 if (!fs.CanSeek)
throw new ArgumentException(
"Stream must be seekable");
35 var buf =
new byte[4];
37 if (buf.SequenceEqual(
new byte[] { 0xff, 0xd8, 0xff, 0xe0 }))
39 blockStart = fs.Position;
41 var blockLength = ((buf[0] << 8) + buf[1]);
43 if (Encoding.ASCII.GetString(buf, 0, 4) ==
"JFIF" 44 && fs.ReadByte() == 0)
46 blockStart += blockLength;
47 while (blockStart < fs.Length)
49 fs.Position = blockStart;
51 blockLength = ((buf[2] << 8) + buf[3]);
52 if (blockLength >= 7 && buf[0] == 0xff && buf[1] == 0xc0)
56 var height = (buf[0] << 8) + buf[1];
57 var width = (buf[2] << 8) + buf[3];
60 blockStart += blockLength + 2;