ImageHeader.cs 7.9 KB

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