ImageHeader.cs 8.4 KB

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