ImageHeader.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using MediaBrowser.Model.Drawing;
  6. using MediaBrowser.Model.IO;
  7. using Microsoft.Extensions.Logging;
  8. namespace Emby.Drawing.Common
  9. {
  10. /// <summary>
  11. /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349
  12. /// http://www.codeproject.com/Articles/35978/Reading-Image-Headers-to-Get-Width-and-Height
  13. /// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic
  14. /// to load the image using new Bitmap if reading the headers fails
  15. /// </summary>
  16. public static class ImageHeader
  17. {
  18. /// <summary>
  19. /// The error message
  20. /// </summary>
  21. const string ErrorMessage = "Could not recognize image format.";
  22. /// <summary>
  23. /// The image format decoders
  24. /// </summary>
  25. private static readonly KeyValuePair<byte[], Func<BinaryReader, ImageSize>>[] ImageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, ImageSize>>
  26. {
  27. { new byte[] { 0x42, 0x4D }, DecodeBitmap },
  28. { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
  29. { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },
  30. { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },
  31. { new byte[] { 0xff, 0xd8 }, DecodeJfif }
  32. }.ToArray();
  33. private static readonly int MaxMagicBytesLength = ImageFormatDecoders.Select(i => i.Key.Length).OrderByDescending(i => i).First();
  34. private static string[] SupportedExtensions = new string[] { ".jpg", ".jpeg", ".png", ".gif" };
  35. /// <summary>
  36. /// Gets the dimensions of an image.
  37. /// </summary>
  38. /// <param name="path">The path of the image to get the dimensions of.</param>
  39. /// <param name="logger">The logger.</param>
  40. /// <param name="fileSystem">The file system.</param>
  41. /// <returns>The dimensions of the specified image.</returns>
  42. /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
  43. public static ImageSize GetDimensions(string path, ILogger logger, IFileSystem fileSystem)
  44. {
  45. var extension = Path.GetExtension(path);
  46. if (string.IsNullOrEmpty(extension))
  47. {
  48. throw new ArgumentException("ImageHeader doesn't support image file");
  49. }
  50. if (!SupportedExtensions.Contains(extension))
  51. {
  52. throw new ArgumentException("ImageHeader doesn't support " + extension);
  53. }
  54. using (var fs = fileSystem.OpenRead(path))
  55. {
  56. using (var binaryReader = new BinaryReader(fs))
  57. {
  58. return GetDimensions(binaryReader);
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// Gets the dimensions of an image.
  64. /// </summary>
  65. /// <param name="binaryReader">The binary reader.</param>
  66. /// <returns>Size.</returns>
  67. /// <exception cref="System.ArgumentException">binaryReader</exception>
  68. /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
  69. private static ImageSize GetDimensions(BinaryReader binaryReader)
  70. {
  71. var magicBytes = new byte[MaxMagicBytesLength];
  72. for (var i = 0; i < MaxMagicBytesLength; i += 1)
  73. {
  74. magicBytes[i] = binaryReader.ReadByte();
  75. foreach (var kvPair in ImageFormatDecoders)
  76. {
  77. if (StartsWith(magicBytes, kvPair.Key))
  78. {
  79. return kvPair.Value(binaryReader);
  80. }
  81. }
  82. }
  83. throw new ArgumentException(ErrorMessage, nameof(binaryReader));
  84. }
  85. /// <summary>
  86. /// Startses the with.
  87. /// </summary>
  88. /// <param name="thisBytes">The this bytes.</param>
  89. /// <param name="thatBytes">The that bytes.</param>
  90. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  91. private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)
  92. {
  93. for (int i = 0; i < thatBytes.Length; i += 1)
  94. {
  95. if (thisBytes[i] != thatBytes[i])
  96. {
  97. return false;
  98. }
  99. }
  100. return true;
  101. }
  102. /// <summary>
  103. /// Reads the little endian int16.
  104. /// </summary>
  105. /// <param name="binaryReader">The binary reader.</param>
  106. /// <returns>System.Int16.</returns>
  107. private static short ReadLittleEndianInt16(this BinaryReader binaryReader)
  108. {
  109. var bytes = new byte[sizeof(short)];
  110. for (int i = 0; i < sizeof(short); i += 1)
  111. {
  112. bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
  113. }
  114. return BitConverter.ToInt16(bytes, 0);
  115. }
  116. /// <summary>
  117. /// Reads the little endian int32.
  118. /// </summary>
  119. /// <param name="binaryReader">The binary reader.</param>
  120. /// <returns>System.Int32.</returns>
  121. private static int ReadLittleEndianInt32(this BinaryReader binaryReader)
  122. {
  123. var bytes = new byte[sizeof(int)];
  124. for (int i = 0; i < sizeof(int); i += 1)
  125. {
  126. bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
  127. }
  128. return BitConverter.ToInt32(bytes, 0);
  129. }
  130. /// <summary>
  131. /// Decodes the bitmap.
  132. /// </summary>
  133. /// <param name="binaryReader">The binary reader.</param>
  134. /// <returns>Size.</returns>
  135. private static ImageSize DecodeBitmap(BinaryReader binaryReader)
  136. {
  137. binaryReader.ReadBytes(16);
  138. int width = binaryReader.ReadInt32();
  139. int height = binaryReader.ReadInt32();
  140. return new ImageSize
  141. {
  142. Width = width,
  143. Height = height
  144. };
  145. }
  146. /// <summary>
  147. /// Decodes the GIF.
  148. /// </summary>
  149. /// <param name="binaryReader">The binary reader.</param>
  150. /// <returns>Size.</returns>
  151. private static ImageSize DecodeGif(BinaryReader binaryReader)
  152. {
  153. int width = binaryReader.ReadInt16();
  154. int height = binaryReader.ReadInt16();
  155. return new ImageSize
  156. {
  157. Width = width,
  158. Height = height
  159. };
  160. }
  161. /// <summary>
  162. /// Decodes the PNG.
  163. /// </summary>
  164. /// <param name="binaryReader">The binary reader.</param>
  165. /// <returns>Size.</returns>
  166. private static ImageSize DecodePng(BinaryReader binaryReader)
  167. {
  168. binaryReader.ReadBytes(8);
  169. int width = ReadLittleEndianInt32(binaryReader);
  170. int height = ReadLittleEndianInt32(binaryReader);
  171. return new ImageSize
  172. {
  173. Width = width,
  174. Height = height
  175. };
  176. }
  177. /// <summary>
  178. /// Decodes the jfif.
  179. /// </summary>
  180. /// <param name="binaryReader">The binary reader.</param>
  181. /// <returns>Size.</returns>
  182. /// <exception cref="System.ArgumentException"></exception>
  183. private static ImageSize DecodeJfif(BinaryReader binaryReader)
  184. {
  185. // A JPEG image consists of a sequence of segments,
  186. // each beginning with a marker, each of which begins with a 0xFF byte
  187. // followed by a byte indicating what kind of marker it is.
  188. // Source: https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
  189. while (binaryReader.ReadByte() == 0xff)
  190. {
  191. byte marker = binaryReader.ReadByte();
  192. short chunkLength = binaryReader.ReadLittleEndianInt16();
  193. // SOF0: Indicates that this is a baseline DCT-based JPEG,
  194. // and specifies the width, height, number of components, and component subsampling
  195. // SOF2: Indicates that this is a progressive DCT-based JPEG,
  196. // and specifies the width, height, number of components, and component subsampling
  197. if (marker == 0xc0 || marker == 0xc2)
  198. {
  199. // https://help.accusoft.com/ImageGear/v18.2/Windows/ActiveX/IGAX-10-12.html
  200. binaryReader.ReadByte(); // We don't care about the first byte
  201. int height = binaryReader.ReadLittleEndianInt16();
  202. int width = binaryReader.ReadLittleEndianInt16();
  203. return new ImageSize(width, height);
  204. }
  205. if (chunkLength < 0)
  206. {
  207. ushort uchunkLength = (ushort)chunkLength;
  208. binaryReader.ReadBytes(uchunkLength - 2);
  209. }
  210. else
  211. {
  212. binaryReader.ReadBytes(chunkLength - 2);
  213. }
  214. }
  215. throw new ArgumentException(ErrorMessage);
  216. }
  217. }
  218. }