ImageHeader.cs 8.1 KB

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