ImageUtils.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. using InABox.Core;
  2. using System.Drawing.Drawing2D;
  3. using System.Drawing.Imaging;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Windows;
  8. using System.Windows.Interop;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Imaging;
  11. using System.Xml.Linq;
  12. using ColorHelper;
  13. using Color = System.Drawing.Color;
  14. using Pen = System.Drawing.Pen;
  15. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  16. using Point = System.Drawing.Point;
  17. using Size = System.Drawing.Size;
  18. namespace InABox.WPF
  19. {
  20. public static class ImageUtils
  21. {
  22. // https://en.wikipedia.org/wiki/List_of_file_signatures
  23. /* Bytes in c# have a range of 0 to 255 so each byte can be represented as
  24. * a two digit hex string. */
  25. private static readonly Dictionary<ImageFormat, string[][]> SignatureTable = new()
  26. {
  27. {
  28. ImageFormat.Jpeg,
  29. new[]
  30. {
  31. new[] { "FF", "D8", "FF", "DB" },
  32. new[] { "FF", "D8", "FF", "EE" },
  33. new[] { "FF", "D8", "FF", "E0", "00", "10", "4A", "46", "49", "46", "00", "01" }
  34. }
  35. },
  36. {
  37. ImageFormat.Gif,
  38. new[]
  39. {
  40. new[] { "47", "49", "46", "38", "37", "61" },
  41. new[] { "47", "49", "46", "38", "39", "61" }
  42. }
  43. },
  44. {
  45. ImageFormat.Png,
  46. new[]
  47. {
  48. new[] { "89", "50", "4E", "47", "0D", "0A", "1A", "0A" }
  49. }
  50. },
  51. {
  52. ImageFormat.Bmp,
  53. new[]
  54. {
  55. new[] { "42", "4D" }
  56. }
  57. }
  58. };
  59. public static Size Adjust(this Size src, double maxWidth, double maxHeight, bool enlarge = false)
  60. {
  61. maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
  62. maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
  63. var rnd = Math.Min((decimal)maxWidth / src.Width, (decimal)maxHeight / src.Height);
  64. return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
  65. }
  66. public static Bitmap AsGrayScale(this Bitmap source)
  67. {
  68. //create a blank bitmap the same size as original
  69. var newBitmap = new Bitmap(source.Width, source.Height);
  70. //get a graphics object from the new image
  71. var g = Graphics.FromImage(newBitmap);
  72. //create the grayscale ColorMatrix
  73. var colorMatrix = new ColorMatrix(
  74. new[]
  75. {
  76. new[] { .3f, .3f, .3f, 0, 0 },
  77. new[] { .59f, .59f, .59f, 0, 0 },
  78. new[] { .11f, .11f, .11f, 0, 0 },
  79. new float[] { 0, 0, 0, 1, 0 },
  80. new float[] { 0, 0, 0, 0, 1 }
  81. });
  82. //create some image attributes
  83. var attributes = new ImageAttributes();
  84. //set the color matrix attribute
  85. attributes.SetColorMatrix(colorMatrix);
  86. //draw the original image on the new image
  87. //using the grayscale color matrix
  88. g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
  89. 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
  90. //dispose the Graphics object
  91. g.Dispose();
  92. return newBitmap;
  93. }
  94. public static BitmapImage AsBitmapImage(this Bitmap src, int height, int width, bool transparent = true)
  95. {
  96. var resized = new Bitmap(src, new Size(width, height));
  97. return AsBitmapImage(resized, transparent);
  98. }
  99. public static BitmapImage AsBitmapImage(this Bitmap src, Color transparent)
  100. {
  101. src.MakeTransparent(transparent);
  102. return src.AsBitmapImage();
  103. }
  104. public static Bitmap ChangeColor(this Bitmap image, Color fromColor, Color toColor)
  105. {
  106. var attributes = new ImageAttributes();
  107. attributes.SetRemapTable(new ColorMap[]
  108. {
  109. new()
  110. {
  111. OldColor = fromColor,
  112. NewColor = toColor
  113. }
  114. }, ColorAdjustType.Bitmap);
  115. using (var g = Graphics.FromImage(image))
  116. {
  117. g.DrawImage(
  118. image,
  119. new Rectangle(Point.Empty, image.Size),
  120. 0, 0, image.Width, image.Height,
  121. GraphicsUnit.Pixel,
  122. attributes);
  123. }
  124. return image;
  125. }
  126. public static Bitmap Fade(this Bitmap source, float opacity)
  127. {
  128. var result = new Bitmap(source.Width, source.Height);
  129. //create a graphics object from the image
  130. using (var gfx = Graphics.FromImage(result))
  131. {
  132. if (opacity < 1.0)
  133. gfx.Clear(Color.White);
  134. //create a color matrix object
  135. var matrix = new ColorMatrix();
  136. //set the opacity
  137. matrix.Matrix33 = opacity;
  138. //create image attributes
  139. var attributes = new ImageAttributes();
  140. //set the color(opacity) of the image
  141. attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
  142. //now draw the image
  143. gfx.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel,
  144. attributes);
  145. }
  146. return result;
  147. }
  148. public static BitmapImage AsBitmapImage(this Bitmap src, Color replace, Color with)
  149. {
  150. return src.ChangeColor(replace, with).AsBitmapImage(false);
  151. }
  152. public static Bitmap AsBitmap(this BitmapImage bitmapImage)
  153. {
  154. using (var outStream = new MemoryStream())
  155. {
  156. BitmapEncoder enc = new BmpBitmapEncoder();
  157. enc.Frames.Add(BitmapFrame.Create(bitmapImage));
  158. enc.Save(outStream);
  159. var bitmap = new Bitmap(outStream);
  160. return new Bitmap(bitmap);
  161. }
  162. }
  163. public static Bitmap AsBitmap(this BitmapSource source)
  164. {
  165. var width = source.PixelWidth;
  166. var height = source.PixelHeight;
  167. var stride = width * ((source.Format.BitsPerPixel + 7) / 8);
  168. var ptr = IntPtr.Zero;
  169. try
  170. {
  171. ptr = Marshal.AllocHGlobal(height * stride);
  172. source.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
  173. using (var btm = new Bitmap(width, height, stride, PixelFormat.Format1bppIndexed, ptr))
  174. {
  175. return new Bitmap(btm);
  176. }
  177. }
  178. finally
  179. {
  180. if (ptr != IntPtr.Zero)
  181. Marshal.FreeHGlobal(ptr);
  182. }
  183. }
  184. public static Bitmap AsBitmap2(this BitmapSource source)
  185. {
  186. var bmp = new Bitmap(
  187. source.PixelWidth,
  188. source.PixelHeight,
  189. PixelFormat.Format32bppPArgb);
  190. var data = bmp.LockBits(
  191. new Rectangle(Point.Empty, bmp.Size),
  192. ImageLockMode.WriteOnly,
  193. PixelFormat.Format32bppPArgb);
  194. source.CopyPixels(
  195. Int32Rect.Empty,
  196. data.Scan0,
  197. data.Height * data.Stride,
  198. data.Stride);
  199. bmp.UnlockBits(data);
  200. return bmp;
  201. }
  202. public static BitmapImage? BitmapImageFromBase64(string base64)
  203. {
  204. return BitmapImageFromBytes(Convert.FromBase64String(base64));
  205. }
  206. public static BitmapImage? BitmapImageFromBytes(byte[] data)
  207. {
  208. var imageSource = new BitmapImage();
  209. if(data.Length > 0)
  210. {
  211. using (var ms = new MemoryStream(data))
  212. {
  213. imageSource.BeginInit();
  214. imageSource.StreamSource = ms;
  215. imageSource.CacheOption = BitmapCacheOption.OnLoad;
  216. imageSource.EndInit();
  217. }
  218. return imageSource;
  219. }
  220. return null;
  221. }
  222. public static BitmapImage? BitmapImageFromStream(Stream data)
  223. {
  224. var imageSource = new BitmapImage();
  225. imageSource.BeginInit();
  226. imageSource.StreamSource = data;
  227. imageSource.CacheOption = BitmapCacheOption.OnLoad;
  228. imageSource.EndInit();
  229. return imageSource;
  230. }
  231. public static BitmapImage AsBitmapImage(this Bitmap src, bool transparent = true)
  232. {
  233. if (transparent)
  234. src.MakeTransparent(src.GetPixel(0, 0));
  235. var bitmapImage = new BitmapImage();
  236. using (var memory = new MemoryStream())
  237. {
  238. src.Save(memory, ImageFormat.Png);
  239. memory.Position = 0;
  240. bitmapImage.BeginInit();
  241. bitmapImage.StreamSource = memory;
  242. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  243. bitmapImage.EndInit();
  244. }
  245. return bitmapImage;
  246. }
  247. public static BitmapSource AsBitmapSource(this Metafile metafile, int width, int height, Color background)
  248. {
  249. var src = new Bitmap(metafile.Width, metafile.Height);
  250. src.SetResolution(metafile.HorizontalResolution, metafile.VerticalResolution);
  251. using (var g = Graphics.FromImage(src))
  252. {
  253. g.DrawImage(metafile, 0, 0, metafile.Width, metafile.Height);
  254. }
  255. var scale = Math.Min(width / (float)metafile.Width, height / (float)metafile.Height);
  256. var scaleWidth = src.Width * scale;
  257. var scaleHeight = src.Height * scale;
  258. var xoffset = (width - scaleWidth) / 2.0F;
  259. var yoffset = (height - scaleHeight) / 2.0F;
  260. using (var bmp = new Bitmap(width, height))
  261. {
  262. bmp.SetResolution(metafile.HorizontalResolution, metafile.VerticalResolution);
  263. using (var g = Graphics.FromImage(bmp))
  264. {
  265. g.InterpolationMode = InterpolationMode.High;
  266. g.CompositingQuality = CompositingQuality.HighQuality;
  267. g.SmoothingMode = SmoothingMode.AntiAlias;
  268. g.FillRectangle(new SolidBrush(background), new RectangleF(0, 0, width, height));
  269. g.DrawImage(src, xoffset, yoffset, scaleWidth, scaleHeight);
  270. }
  271. bmp.Save("c:\\development\\emf2bmp.png");
  272. return Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  273. }
  274. }
  275. public static BitmapImage LoadImage(byte[] imageData)
  276. {
  277. var result = new BitmapImage();
  278. result.LoadImage(imageData);
  279. return result;
  280. }
  281. public static void LoadImage(this BitmapImage image, byte[]? imageData)
  282. {
  283. if (imageData == null || imageData.Length == 0)
  284. return;
  285. using (var mem = new MemoryStream(imageData))
  286. {
  287. mem.Position = 0;
  288. image.BeginInit();
  289. image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
  290. image.CacheOption = BitmapCacheOption.OnLoad;
  291. image.UriSource = null;
  292. image.StreamSource = mem;
  293. image.EndInit();
  294. }
  295. image.Freeze();
  296. }
  297. public static byte[] ToArray<T>(this BitmapImage image) where T : BitmapEncoder, new()
  298. {
  299. byte[] data;
  300. var encoder = new T();
  301. encoder.Frames.Add(BitmapFrame.Create(image));
  302. using (var ms = new MemoryStream())
  303. {
  304. encoder.Save(ms);
  305. data = ms.ToArray();
  306. }
  307. return data;
  308. }
  309. public static BitmapImage Resize(this BitmapImage image, int height, int width)
  310. {
  311. var buffer = image.ToArray<BmpBitmapEncoder>();
  312. var ms = new MemoryStream(buffer);
  313. var result = new BitmapImage();
  314. result.BeginInit();
  315. result.CacheOption = BitmapCacheOption.None;
  316. result.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  317. result.DecodePixelWidth = width;
  318. result.DecodePixelHeight = height;
  319. result.StreamSource = ms;
  320. result.Rotation = Rotation.Rotate0;
  321. result.EndInit();
  322. buffer = null;
  323. return result;
  324. }
  325. public static BitmapImage Scale(this BitmapImage image, int maxheight, int maxwidth)
  326. {
  327. var scaleHeight = maxheight / (float)image.Height;
  328. var scaleWidth = maxwidth / (float)image.Width;
  329. var scale = Math.Min(scaleHeight, scaleWidth);
  330. return image.Resize((int)(image.Height * scale), (int)(image.Width * scale));
  331. }
  332. public static Bitmap BitmapFromColor(Color color, int width, int height, Color frame)
  333. {
  334. var result = new Bitmap(width, height);
  335. var g = Graphics.FromImage(result);
  336. g.Clear(color);
  337. if (frame != Color.Transparent)
  338. g.DrawRectangle(new Pen(new SolidBrush(frame), 1), new Rectangle(0, 0, width-1, height-1));
  339. return result;
  340. }
  341. public static Bitmap BitmapFromColor(System.Windows.Media.Color color, int width, int height, System.Windows.Media.Color frame)
  342. {
  343. var result = new Bitmap(width, height);
  344. var g = Graphics.FromImage(result);
  345. g.Clear(Color.FromArgb(color.A,color.R,color.G,color.B));
  346. if (frame != Colors.Transparent)
  347. g.DrawRectangle(new Pen(new SolidBrush(Color.FromArgb(frame.A,frame.R,frame.G,frame.B)), 1F), new Rectangle(0, 0, width-1, height-1));
  348. return result;
  349. }
  350. public static Color MixColors(this Color color1, double factor, Color color2)
  351. {
  352. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  353. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  354. if (factor == 0) return color2;
  355. if (factor == 1) return color1;
  356. var factor1 = 1 - factor;
  357. return Color.FromArgb(
  358. (byte)(color1.A * factor + color2.A * factor1),
  359. (byte)(color1.R * factor + color2.R * factor1),
  360. (byte)(color1.G * factor + color2.G * factor1),
  361. (byte)(color1.B * factor + color2.B * factor1));
  362. }
  363. public static System.Windows.Media.Color MixColors(this System.Windows.Media.Color color1, double factor, System.Windows.Media.Color color2)
  364. {
  365. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  366. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  367. if (factor == 0) return color2;
  368. if (factor == 1) return color1;
  369. var factor1 = 1 - factor;
  370. return System.Windows.Media.Color.FromArgb(
  371. (byte)(color1.A * factor + color2.A * factor1),
  372. (byte)(color1.R * factor + color2.R * factor1),
  373. (byte)(color1.G * factor + color2.G * factor1),
  374. (byte)(color1.B * factor + color2.B * factor1));
  375. }
  376. public static string ColorToString(Color color)
  377. {
  378. return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",
  379. color.A,
  380. color.R,
  381. color.G,
  382. color.B
  383. );
  384. }
  385. public static Color StringToColor(string colorcode)
  386. {
  387. var col = Color.Transparent;
  388. if (!string.IsNullOrEmpty(colorcode))
  389. {
  390. var code = colorcode.Replace("#", "");
  391. if (code.Length == 6)
  392. col = Color.FromArgb(255,
  393. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  394. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  395. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  396. else if (code.Length == 8)
  397. col = Color.FromArgb(
  398. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  399. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  400. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  401. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  402. }
  403. return col;
  404. }
  405. public static System.Windows.Media.Color StringToMediaColor(string colorcode)
  406. {
  407. var col = Colors.Transparent;
  408. if (!string.IsNullOrEmpty(colorcode))
  409. {
  410. var code = colorcode.Replace("#", "");
  411. if (code.Length == 6)
  412. col = System.Windows.Media.Color.FromArgb(255,
  413. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  414. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  415. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  416. else if (code.Length == 8)
  417. col = System.Windows.Media.Color.FromArgb(
  418. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  419. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  420. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  421. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  422. }
  423. return col;
  424. }
  425. /// <summary>
  426. /// Creates color with corrected brightness.
  427. /// </summary>
  428. /// <param name="color">Color to correct.</param>
  429. /// <param name="correctionFactor">
  430. /// The brightness correction factor. Must be between -1 and 1.
  431. /// Negative values produce darker colors.
  432. /// </param>
  433. /// <returns>
  434. /// Corrected <see cref="Color" /> structure.
  435. /// </returns>
  436. public static System.Windows.Media.Color AdjustBrightness(this System.Windows.Media.Color color, float correctionFactor)
  437. {
  438. float red = color.R;
  439. float green = color.G;
  440. float blue = color.B;
  441. if (correctionFactor < 0)
  442. {
  443. correctionFactor = 1 + correctionFactor;
  444. red *= correctionFactor;
  445. green *= correctionFactor;
  446. blue *= correctionFactor;
  447. }
  448. else
  449. {
  450. red = (255 - red) * correctionFactor + red;
  451. green = (255 - green) * correctionFactor + green;
  452. blue = (255 - blue) * correctionFactor + blue;
  453. }
  454. return System.Windows.Media.Color.FromArgb(color.A, (byte)red, (byte)green, (byte)blue);
  455. }
  456. /// <summary>
  457. /// Takes a byte array and determines the image file type by
  458. /// comparing the first few bytes of the file to a list of known
  459. /// image file signatures.
  460. /// </summary>
  461. /// <param name="imageData">Byte array of the image data</param>
  462. /// <returns>ImageFormat corresponding to the image file format</returns>
  463. /// <exception cref="ArgumentException">Thrown if the image type can't be determined</exception>
  464. public static ImageFormat GetImageType(byte[] imageData)
  465. {
  466. foreach (var signatureEntry in SignatureTable)
  467. foreach (var signature in signatureEntry.Value)
  468. {
  469. var isMatch = true;
  470. for (var i = 0; i < signature.Length; i++)
  471. {
  472. var signatureByte = signature[i];
  473. // ToString("X") gets the hex representation and pads it to always be length 2
  474. var imageByte = imageData[i]
  475. .ToString("X2");
  476. if (signatureByte == imageByte)
  477. continue;
  478. isMatch = false;
  479. break;
  480. }
  481. if (isMatch) return signatureEntry.Key;
  482. }
  483. throw new ArgumentException("The byte array did not match any known image file signatures.");
  484. }
  485. public static System.Drawing.Bitmap Invert(this System.Drawing.Bitmap source)
  486. {
  487. Bitmap bmpDest = new Bitmap(source.Width,source.Height);
  488. ColorMatrix clrMatrix = new ColorMatrix(new float[][]
  489. {
  490. new float[] {-1, 0, 0, 0, 0},
  491. new float[] {0, -1, 0, 0, 0},
  492. new float[] {0, 0, -1, 0, 0},
  493. new float[] {0, 0, 0, 1, 0},
  494. new float[] {1, 1, 1, 0, 1}
  495. });
  496. using (ImageAttributes attrImage = new ImageAttributes())
  497. {
  498. attrImage.SetColorMatrix(clrMatrix);
  499. using (Graphics g = Graphics.FromImage(bmpDest))
  500. {
  501. g.DrawImage(source, new Rectangle(0, 0,
  502. source.Width, source.Height), 0, 0,
  503. source.Width, source.Height, GraphicsUnit.Pixel,
  504. attrImage);
  505. }
  506. }
  507. return bmpDest;
  508. }
  509. public static Font AdjustSize(this Font font, Graphics graphics, string text, int width)
  510. {
  511. Font result = null;
  512. for (int size = (int)font.Size; size > 0; size--)
  513. {
  514. result = new Font(font.Name, size, font.Style);
  515. SizeF adjustedSizeNew = graphics.MeasureString(text, result);
  516. if (width > Convert.ToInt32(adjustedSizeNew.Width))
  517. return result;
  518. }
  519. return result;
  520. }
  521. public static Bitmap WatermarkImage(this Bitmap image, String text, System.Windows.Media.Color color, int maxfontsize = 0)
  522. {
  523. return image.WatermarkImage(text, Color.FromArgb(color.A, color.R, color.G, color.B),maxfontsize);
  524. }
  525. public static Bitmap WatermarkImage(this Bitmap image, String text, Color color, int maxfontsize = 0)
  526. {
  527. int w = image.Width;
  528. int h = image.Height;
  529. Bitmap result = new System.Drawing.Bitmap(w, h);
  530. Graphics graphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)result);
  531. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  532. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  533. graphics.Clear(System.Drawing.Color.Transparent);
  534. graphics.DrawImage(image, 0, 0, w, h);
  535. Font drawFont = new System.Drawing.Font("Arial", 96).AdjustSize(graphics,text,(int)(image.Width * 0.9F));
  536. if ((maxfontsize > 0) && (drawFont.Size > maxfontsize))
  537. drawFont = new System.Drawing.Font("Arial", maxfontsize);
  538. SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
  539. StringFormat stringFormat = new StringFormat();
  540. stringFormat.Alignment = StringAlignment.Center;
  541. stringFormat.LineAlignment = StringAlignment.Center;
  542. graphics.DrawString(text, drawFont, drawBrush, new Rectangle(0,0,w,h), stringFormat);
  543. graphics.Dispose();
  544. return result;
  545. }
  546. private static System.Windows.Media.Color AdjustColor(System.Windows.Media.Color color, Action<HSL> action)
  547. {
  548. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R,color.G,color.B));
  549. action(hsl);
  550. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  551. return System.Windows.Media.Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
  552. }
  553. private static int AdjustPercentage(int original, int percentage)
  554. {
  555. int percent = Math.Min(100, Math.Max(-100, percentage));
  556. int newvalue = (percent < 0)
  557. ? (byte)((percent * original) / 100)
  558. : (byte)((percent * (100 - original)) / 100);
  559. return original + newvalue;
  560. }
  561. public static System.Windows.Media.Color AdjustHue(this System.Windows.Media.Color color, int degrees) =>
  562. AdjustColor(color, (hsl => hsl.H += degrees));
  563. public static System.Windows.Media.Color AdjustSaturation(this System.Windows.Media.Color color, int percentage) =>
  564. AdjustColor(color, (hsl =>
  565. {
  566. hsl.S = (byte)AdjustPercentage(hsl.S, percentage);
  567. }));
  568. public static System.Windows.Media.Color SetSaturation(this System.Windows.Media.Color color, int percentage) =>
  569. AdjustColor(color, (hsl => hsl.S = (byte)percentage));
  570. public static System.Windows.Media.Color AdjustLightness(this System.Windows.Media.Color color, int percentage) =>
  571. AdjustColor(color, (hsl =>
  572. {
  573. hsl.L = (byte)AdjustPercentage(hsl.L, percentage);
  574. }));
  575. public static System.Windows.Media.Color SetLightness(this System.Windows.Media.Color color, int percentage) =>
  576. AdjustColor(color, (hsl => hsl.L = (byte)percentage));
  577. public static System.Windows.Media.Color SetAlpha(this System.Windows.Media.Color color, byte alpha) =>
  578. System.Windows.Media.Color.FromArgb(alpha, color.R, color.G, color.B);
  579. public static HSL ToHSL(this System.Windows.Media.Color color)
  580. {
  581. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  582. }
  583. public static System.Windows.Media.Color ToColor(this HSL hsl)
  584. {
  585. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  586. return System.Windows.Media.Color.FromRgb(rgb.R, rgb.G, rgb.B);
  587. }
  588. public static HSL ToHSL(this System.Drawing.Color color)
  589. {
  590. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  591. }
  592. public static System.Windows.Media.Color GetForegroundColor(this System.Windows.Media.Color c, int threshold = 130)
  593. {
  594. var perceivedbrightness = (int)Math.Sqrt(
  595. c.R * c.R * .299 +
  596. c.G * c.G * .587 +
  597. c.B * c.B * .114);
  598. return perceivedbrightness >= threshold ? Colors.Black : Colors.White;
  599. }
  600. public static uint ToUint(this System.Drawing.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  601. public static uint ToUint(this System.Windows.Media.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  602. }
  603. }