ImageUtils.cs 29 KB

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