Util.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Photoshop PSD FileType Plugin for Paint.NET
  4. // http://psdplugin.codeplex.com/
  5. //
  6. // This software is provided under the MIT License:
  7. // Copyright (c) 2006-2007 Frank Blumenberg
  8. // Copyright (c) 2010-2017 Tao Yue
  9. //
  10. // See LICENSE.txt for complete licensing and attribution information.
  11. //
  12. /////////////////////////////////////////////////////////////////////////////////
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.Drawing;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Text;
  20. namespace PhotoshopFile
  21. {
  22. public static class Util
  23. {
  24. [DebuggerDisplay("Top = {Top}, Bottom = {Bottom}, Left = {Left}, Right = {Right}")]
  25. public struct RectanglePosition
  26. {
  27. public int Top { get; set; }
  28. public int Bottom { get; set; }
  29. public int Left { get; set; }
  30. public int Right { get; set; }
  31. }
  32. public static Rectangle IntersectWith(
  33. this Rectangle thisRect, Rectangle rect)
  34. {
  35. thisRect.Intersect(rect);
  36. return thisRect;
  37. }
  38. ///////////////////////////////////////////////////////////////////////////
  39. /// <summary>
  40. /// Fills a buffer with a byte value.
  41. /// </summary>
  42. unsafe static public void Fill(byte* ptr, byte* ptrEnd, byte value)
  43. {
  44. while (ptr < ptrEnd)
  45. {
  46. *ptr = value;
  47. ptr++;
  48. }
  49. }
  50. unsafe static public void Invert(byte* ptr, byte* ptrEnd)
  51. {
  52. while (ptr < ptrEnd)
  53. {
  54. *ptr = (byte)(*ptr ^ 0xff);
  55. ptr++;
  56. }
  57. }
  58. ///////////////////////////////////////////////////////////////////////////
  59. /// <summary>
  60. /// Reverses the endianness of a 2-byte word.
  61. /// </summary>
  62. unsafe static public void SwapBytes2(byte* ptr)
  63. {
  64. byte byte0 = *ptr;
  65. *ptr = *(ptr + 1);
  66. *(ptr + 1) = byte0;
  67. }
  68. ///////////////////////////////////////////////////////////////////////////
  69. /// <summary>
  70. /// Reverses the endianness of a 4-byte word.
  71. /// </summary>
  72. unsafe static public void SwapBytes4(byte* ptr)
  73. {
  74. byte byte0 = *ptr;
  75. byte byte1 = *(ptr + 1);
  76. *ptr = *(ptr + 3);
  77. *(ptr + 1) = *(ptr + 2);
  78. *(ptr + 2) = byte1;
  79. *(ptr + 3) = byte0;
  80. }
  81. /// <summary>
  82. /// Reverses the endianness of a word of arbitrary length.
  83. /// </summary>
  84. unsafe static public void SwapBytes(byte* ptr, int nLength)
  85. {
  86. for (long i = 0; i < nLength / 2; ++i)
  87. {
  88. byte t = *(ptr + i);
  89. *(ptr + i) = *(ptr + nLength - i - 1);
  90. *(ptr + nLength - i - 1) = t;
  91. }
  92. }
  93. ///////////////////////////////////////////////////////////////////////////
  94. public static void SwapByteArray(int bitDepth,
  95. byte[] byteArray, int startIdx, int count)
  96. {
  97. switch (bitDepth)
  98. {
  99. case 1:
  100. case 8:
  101. break;
  102. case 16:
  103. SwapByteArray2(byteArray, startIdx, count);
  104. break;
  105. case 32:
  106. SwapByteArray4(byteArray, startIdx, count);
  107. break;
  108. default:
  109. throw new Exception(
  110. "Byte-swapping implemented only for 16-bit and 32-bit depths.");
  111. }
  112. }
  113. /// <summary>
  114. /// Reverses the endianness of 2-byte words in a byte array.
  115. /// </summary>
  116. /// <param name="byteArray">Byte array containing the sequence on which to swap endianness</param>
  117. /// <param name="startIdx">Byte index of the first word to swap</param>
  118. /// <param name="count">Number of words to swap</param>
  119. public static void SwapByteArray2(byte[] byteArray, int startIdx, int count)
  120. {
  121. int endIdx = startIdx + count * 2;
  122. if (byteArray.Length < endIdx)
  123. throw new IndexOutOfRangeException();
  124. unsafe
  125. {
  126. fixed (byte* arrayPtr = &byteArray[0])
  127. {
  128. byte* ptr = arrayPtr + startIdx;
  129. byte* endPtr = arrayPtr + endIdx;
  130. while (ptr < endPtr)
  131. {
  132. SwapBytes2(ptr);
  133. ptr += 2;
  134. }
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Reverses the endianness of 4-byte words in a byte array.
  140. /// </summary>
  141. /// <param name="byteArray">Byte array containing the sequence on which to swap endianness</param>
  142. /// <param name="startIdx">Byte index of the first word to swap</param>
  143. /// <param name="count">Number of words to swap</param>
  144. public static void SwapByteArray4(byte[] byteArray, int startIdx, int count)
  145. {
  146. int endIdx = startIdx + count * 4;
  147. if (byteArray.Length < endIdx)
  148. throw new IndexOutOfRangeException();
  149. unsafe
  150. {
  151. fixed (byte* arrayPtr = &byteArray[0])
  152. {
  153. byte* ptr = arrayPtr + startIdx;
  154. byte* endPtr = arrayPtr + endIdx;
  155. while (ptr < endPtr)
  156. {
  157. SwapBytes4(ptr);
  158. ptr += 4;
  159. }
  160. }
  161. }
  162. }
  163. ///////////////////////////////////////////////////////////////////////////
  164. /// <summary>
  165. /// Calculates the number of bytes required to store a row of an image
  166. /// with the specified bit depth.
  167. /// </summary>
  168. /// <param name="size">The size of the image in pixels.</param>
  169. /// <param name="bitDepth">The bit depth of the image.</param>
  170. /// <returns>The number of bytes needed to store a row of the image.</returns>
  171. public static int BytesPerRow(Size size, int bitDepth)
  172. {
  173. switch (bitDepth)
  174. {
  175. case 1:
  176. return (size.Width + 7) / 8;
  177. default:
  178. return size.Width * BytesFromBitDepth(bitDepth);
  179. }
  180. }
  181. /// <summary>
  182. /// Round the integer to a multiple.
  183. /// </summary>
  184. public static int RoundUp(int value, int multiple)
  185. {
  186. if (value == 0)
  187. return 0;
  188. if (Math.Sign(value) != Math.Sign(multiple))
  189. {
  190. throw new ArgumentException(
  191. $"{nameof(value)} and {nameof(multiple)} cannot have opposite signs.");
  192. }
  193. var remainder = value % multiple;
  194. if (remainder > 0)
  195. {
  196. value += (multiple - remainder);
  197. }
  198. return value;
  199. }
  200. /// <summary>
  201. /// Get number of bytes required to pad to the specified multiple.
  202. /// </summary>
  203. public static int GetPadding(int length, int padMultiple)
  204. {
  205. if ((length < 0) || (padMultiple < 0))
  206. throw new ArgumentException();
  207. var remainder = length % padMultiple;
  208. if (remainder == 0)
  209. return 0;
  210. var padding = padMultiple - remainder;
  211. return padding;
  212. }
  213. /// <summary>
  214. /// Returns the number of bytes needed to store a single pixel of the
  215. /// specified bit depth.
  216. /// </summary>
  217. public static int BytesFromBitDepth(int depth)
  218. {
  219. switch (depth)
  220. {
  221. case 1:
  222. case 8:
  223. return 1;
  224. case 16:
  225. return 2;
  226. case 32:
  227. return 4;
  228. default:
  229. throw new ArgumentException("Invalid bit depth.");
  230. }
  231. }
  232. public static short MinChannelCount(this PsdColorMode colorMode)
  233. {
  234. switch (colorMode)
  235. {
  236. case PsdColorMode.Bitmap:
  237. case PsdColorMode.Duotone:
  238. case PsdColorMode.Grayscale:
  239. case PsdColorMode.Indexed:
  240. case PsdColorMode.Multichannel:
  241. return 1;
  242. case PsdColorMode.Lab:
  243. case PsdColorMode.RGB:
  244. return 3;
  245. case PsdColorMode.CMYK:
  246. return 4;
  247. }
  248. throw new ArgumentException("Unknown color mode.");
  249. }
  250. /// <summary>
  251. /// Verify that the offset and count will remain within the bounds of the
  252. /// buffer.
  253. /// </summary>
  254. /// <returns>True if in bounds, false if out of bounds.</returns>
  255. public static bool CheckBufferBounds(byte[] data, int offset, int count)
  256. {
  257. if (offset < 0)
  258. return false;
  259. if (count < 0)
  260. return false;
  261. if (offset + count > data.Length)
  262. return false;
  263. return true;
  264. }
  265. public static void CheckByteArrayLength(long length)
  266. {
  267. if (length < 0)
  268. {
  269. throw new Exception("Byte array cannot have a negative length.");
  270. }
  271. if (length > 0x7fffffc7)
  272. {
  273. throw new OutOfMemoryException(
  274. "Byte array cannot exceed 2,147,483,591 in length.");
  275. }
  276. }
  277. /// <summary>
  278. /// Writes a message to the debug console, indicating the current position
  279. /// in the stream in both decimal and hexadecimal formats.
  280. /// </summary>
  281. [Conditional("DEBUG")]
  282. public static void DebugMessage(Stream stream, string message)
  283. {
  284. Debug.WriteLine($"0x{stream.Position:x}, {stream.Position}, {message}");
  285. }
  286. }
  287. /// <summary>
  288. /// Fixed-point decimal, with 16-bit integer and 16-bit fraction.
  289. /// </summary>
  290. public class UFixed16_16
  291. {
  292. public UInt16 Integer { get; set; }
  293. public UInt16 Fraction { get; set; }
  294. public UFixed16_16(UInt16 integer, UInt16 fraction)
  295. {
  296. Integer = integer;
  297. Fraction = fraction;
  298. }
  299. /// <summary>
  300. /// Split the high and low words of a 32-bit unsigned integer into a
  301. /// fixed-point number.
  302. /// </summary>
  303. public UFixed16_16(UInt32 value)
  304. {
  305. Integer = (UInt16)(value >> 16);
  306. Fraction = (UInt16)(value & 0x0000ffff);
  307. }
  308. public UFixed16_16(double value)
  309. {
  310. if (value >= 65536.0) throw new OverflowException();
  311. if (value < 0) throw new OverflowException();
  312. Integer = (UInt16)value;
  313. // Round instead of truncate, because doubles may not represent the
  314. // fraction exactly.
  315. Fraction = (UInt16)((value - Integer) * 65536 + 0.5);
  316. }
  317. public static implicit operator double(UFixed16_16 value)
  318. {
  319. return (double)value.Integer + value.Fraction / 65536.0;
  320. }
  321. }
  322. }