MaxstARSDK  3.5.0
JpegUtils.cs
1 /*==============================================================================
2 Copyright 2017 Maxst, Inc. All Rights Reserved.
3 ==============================================================================*/
4 
5 using System;
6 using System.Collections.Generic;
7 using System.Linq;
8 using System.Text;
9 using System.IO;
10 
11 namespace maxstAR
12 {
13  internal class JpegUtils
14  {
15  public static Dimensions GetJpegDimensions(byte[] bytes)
16  {
17  using (var ms = new MemoryStream(bytes))
18  {
19  return GetJpegDimensions(ms);
20  }
21  }
22 
23  public static Dimensions GetJpegDimensions(string filePath)
24  {
25  using (var fs = File.OpenRead(filePath))
26  {
27  return GetJpegDimensions(fs);
28  }
29  }
30 
31  public static Dimensions GetJpegDimensions(Stream fs)
32  {
33  if (!fs.CanSeek) throw new ArgumentException("Stream must be seekable");
34  long blockStart;
35  var buf = new byte[4];
36  fs.Read(buf, 0, 4);
37  if (buf.SequenceEqual(new byte[] { 0xff, 0xd8, 0xff, 0xe0 }))
38  {
39  blockStart = fs.Position;
40  fs.Read(buf, 0, 2);
41  var blockLength = ((buf[0] << 8) + buf[1]);
42  fs.Read(buf, 0, 4);
43  if (Encoding.ASCII.GetString(buf, 0, 4) == "JFIF"
44  && fs.ReadByte() == 0)
45  {
46  blockStart += blockLength;
47  while (blockStart < fs.Length)
48  {
49  fs.Position = blockStart;
50  fs.Read(buf, 0, 4);
51  blockLength = ((buf[2] << 8) + buf[3]);
52  if (blockLength >= 7 && buf[0] == 0xff && buf[1] == 0xc0)
53  {
54  fs.Position += 1;
55  fs.Read(buf, 0, 4);
56  var height = (buf[0] << 8) + buf[1];
57  var width = (buf[2] << 8) + buf[3];
58  return new Dimensions(width, height);
59  }
60  blockStart += blockLength + 2;
61  }
62  }
63  }
64  return null;
65  }
66  }
67 }