2
0

ImageHeader.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Model.Drawing;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. namespace MediaBrowser.Server.Implementations.Drawing
  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. /// <summary>
  35. /// Gets the dimensions of an image.
  36. /// </summary>
  37. /// <param name="path">The path of the image to get the dimensions of.</param>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="fileSystem">The file system.</param>
  40. /// <returns>The dimensions of the specified image.</returns>
  41. /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
  42. public static ImageSize GetDimensions(string path, ILogger logger, IFileSystem fileSystem)
  43. {
  44. try
  45. {
  46. using (var fs = File.OpenRead(path))
  47. {
  48. using (var binaryReader = new BinaryReader(fs))
  49. {
  50. return GetDimensions(binaryReader);
  51. }
  52. }
  53. }
  54. catch
  55. {
  56. logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
  57. }
  58. // Buffer to memory stream to avoid image locking file
  59. using (var fs = fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  60. {
  61. using (var memoryStream = new MemoryStream())
  62. {
  63. fs.CopyTo(memoryStream);
  64. memoryStream.Position = 0;
  65. // Co it the old fashioned way
  66. using (var b = System.Drawing.Image.FromStream(memoryStream, true, false))
  67. {
  68. var size = b.Size;
  69. return new ImageSize
  70. {
  71. Width = size.Width,
  72. Height = size.Height
  73. };
  74. }
  75. }
  76. }
  77. }
  78. /// <summary>
  79. /// Gets the dimensions of an image.
  80. /// </summary>
  81. /// <param name="binaryReader">The binary reader.</param>
  82. /// <returns>Size.</returns>
  83. /// <exception cref="System.ArgumentException">binaryReader</exception>
  84. /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
  85. private static ImageSize GetDimensions(BinaryReader binaryReader)
  86. {
  87. var magicBytes = new byte[MaxMagicBytesLength];
  88. for (var i = 0; i < MaxMagicBytesLength; i += 1)
  89. {
  90. magicBytes[i] = binaryReader.ReadByte();
  91. foreach (var kvPair in ImageFormatDecoders)
  92. {
  93. if (StartsWith(magicBytes, kvPair.Key))
  94. {
  95. return kvPair.Value(binaryReader);
  96. }
  97. }
  98. }
  99. throw new ArgumentException(ErrorMessage, "binaryReader");
  100. }
  101. /// <summary>
  102. /// Startses the with.
  103. /// </summary>
  104. /// <param name="thisBytes">The this bytes.</param>
  105. /// <param name="thatBytes">The that bytes.</param>
  106. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  107. private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)
  108. {
  109. for (int i = 0; i < thatBytes.Length; i += 1)
  110. {
  111. if (thisBytes[i] != thatBytes[i])
  112. {
  113. return false;
  114. }
  115. }
  116. return true;
  117. }
  118. /// <summary>
  119. /// Reads the little endian int16.
  120. /// </summary>
  121. /// <param name="binaryReader">The binary reader.</param>
  122. /// <returns>System.Int16.</returns>
  123. private static short ReadLittleEndianInt16(BinaryReader binaryReader)
  124. {
  125. var bytes = new byte[sizeof(short)];
  126. for (int i = 0; i < sizeof(short); i += 1)
  127. {
  128. bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
  129. }
  130. return BitConverter.ToInt16(bytes, 0);
  131. }
  132. /// <summary>
  133. /// Reads the little endian int32.
  134. /// </summary>
  135. /// <param name="binaryReader">The binary reader.</param>
  136. /// <returns>System.Int32.</returns>
  137. private static int ReadLittleEndianInt32(BinaryReader binaryReader)
  138. {
  139. var bytes = new byte[sizeof(int)];
  140. for (int i = 0; i < sizeof(int); i += 1)
  141. {
  142. bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
  143. }
  144. return BitConverter.ToInt32(bytes, 0);
  145. }
  146. /// <summary>
  147. /// Decodes the bitmap.
  148. /// </summary>
  149. /// <param name="binaryReader">The binary reader.</param>
  150. /// <returns>Size.</returns>
  151. private static ImageSize DecodeBitmap(BinaryReader binaryReader)
  152. {
  153. binaryReader.ReadBytes(16);
  154. int width = binaryReader.ReadInt32();
  155. int height = binaryReader.ReadInt32();
  156. return new ImageSize
  157. {
  158. Width = width,
  159. Height = height
  160. };
  161. }
  162. /// <summary>
  163. /// Decodes the GIF.
  164. /// </summary>
  165. /// <param name="binaryReader">The binary reader.</param>
  166. /// <returns>Size.</returns>
  167. private static ImageSize DecodeGif(BinaryReader binaryReader)
  168. {
  169. int width = binaryReader.ReadInt16();
  170. int height = binaryReader.ReadInt16();
  171. return new ImageSize
  172. {
  173. Width = width,
  174. Height = height
  175. };
  176. }
  177. /// <summary>
  178. /// Decodes the PNG.
  179. /// </summary>
  180. /// <param name="binaryReader">The binary reader.</param>
  181. /// <returns>Size.</returns>
  182. private static ImageSize DecodePng(BinaryReader binaryReader)
  183. {
  184. binaryReader.ReadBytes(8);
  185. int width = ReadLittleEndianInt32(binaryReader);
  186. int height = ReadLittleEndianInt32(binaryReader);
  187. return new ImageSize
  188. {
  189. Width = width,
  190. Height = height
  191. };
  192. }
  193. /// <summary>
  194. /// Decodes the jfif.
  195. /// </summary>
  196. /// <param name="binaryReader">The binary reader.</param>
  197. /// <returns>Size.</returns>
  198. /// <exception cref="System.ArgumentException"></exception>
  199. private static ImageSize DecodeJfif(BinaryReader binaryReader)
  200. {
  201. while (binaryReader.ReadByte() == 0xff)
  202. {
  203. byte marker = binaryReader.ReadByte();
  204. short chunkLength = ReadLittleEndianInt16(binaryReader);
  205. if (marker == 0xc0)
  206. {
  207. binaryReader.ReadByte();
  208. int height = ReadLittleEndianInt16(binaryReader);
  209. int width = ReadLittleEndianInt16(binaryReader);
  210. return new ImageSize
  211. {
  212. Width = width,
  213. Height = height
  214. };
  215. }
  216. if (chunkLength < 0)
  217. {
  218. var uchunkLength = (ushort)chunkLength;
  219. binaryReader.ReadBytes(uchunkLength - 2);
  220. }
  221. else
  222. {
  223. binaryReader.ReadBytes(chunkLength - 2);
  224. }
  225. }
  226. throw new ArgumentException(ErrorMessage);
  227. }
  228. }
  229. }