ImageHeader.cs 7.8 KB

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