ImageUtils.cs 31 KB

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