ImageHeader.cs 8.3 KB

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