ImageUtils.cs 31 KB

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