ImageHeader.cs 8.3 KB

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