ImageUtils.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 Bitmap? MergeBitmaps(IEnumerable<Bitmap> bitmaps, int padding)
  299. {
  300. if (!bitmaps.Any())
  301. return null;
  302. var totalwidth = bitmaps.Aggregate(0, (total, next) => total + next.Width + (total > 0 ? padding : 0) );
  303. var maxheight = bitmaps.Aggregate(0, (max, next) => Math.Max(next.Height,max) );
  304. Bitmap result = new Bitmap(totalwidth, maxheight);
  305. using (Graphics g = Graphics.FromImage(result))
  306. {
  307. g.Clear(Color.Transparent);
  308. int left = 0;
  309. foreach (var bitmap in bitmaps)
  310. {
  311. g.DrawImage(bitmap, left, 0);
  312. left += bitmap.Width + padding;
  313. }
  314. }
  315. return result;
  316. }
  317. public static byte[] ToArray<T>(this BitmapImage image) where T : BitmapEncoder, new()
  318. {
  319. byte[] data;
  320. var encoder = new T();
  321. encoder.Frames.Add(BitmapFrame.Create(image));
  322. using (var ms = new MemoryStream())
  323. {
  324. encoder.Save(ms);
  325. data = ms.ToArray();
  326. }
  327. return data;
  328. }
  329. public static BitmapImage Resize(this BitmapImage image, int height, int width)
  330. {
  331. var buffer = image.ToArray<BmpBitmapEncoder>();
  332. var ms = new MemoryStream(buffer);
  333. var result = new BitmapImage();
  334. result.BeginInit();
  335. result.CacheOption = BitmapCacheOption.None;
  336. result.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  337. result.DecodePixelWidth = width;
  338. result.DecodePixelHeight = height;
  339. result.StreamSource = ms;
  340. result.Rotation = Rotation.Rotate0;
  341. result.EndInit();
  342. buffer = null;
  343. return result;
  344. }
  345. public static Bitmap Resize(this Bitmap bitmap, int width, int height)
  346. {
  347. if ((width == bitmap.Width) && (height == bitmap.Height))
  348. return bitmap;
  349. return new Bitmap(bitmap,new Size(width,height));
  350. }
  351. public static BitmapImage Scale(this BitmapImage image, int maxheight, int maxwidth)
  352. {
  353. var scaleHeight = maxheight / (float)image.Height;
  354. var scaleWidth = maxwidth / (float)image.Width;
  355. var scale = Math.Min(scaleHeight, scaleWidth);
  356. return image.Resize((int)(image.Height * scale), (int)(image.Width * scale));
  357. }
  358. public static Bitmap BitmapFromColor(Color color, int width, int height, Color frame)
  359. {
  360. var result = new Bitmap(width, height);
  361. var g = Graphics.FromImage(result);
  362. g.Clear(color);
  363. if (frame != Color.Transparent)
  364. g.DrawRectangle(new Pen(new SolidBrush(frame), 1), new Rectangle(0, 0, width-1, height-1));
  365. return result;
  366. }
  367. public static Bitmap BitmapFromColor(System.Windows.Media.Color color, int width, int height, System.Windows.Media.Color frame)
  368. {
  369. var result = new Bitmap(width, height);
  370. var g = Graphics.FromImage(result);
  371. g.Clear(Color.FromArgb(color.A,color.R,color.G,color.B));
  372. if (frame != Colors.Transparent)
  373. 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));
  374. return result;
  375. }
  376. public static Color MixColors(this Color color1, double factor, Color color2)
  377. {
  378. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  379. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  380. if (factor == 0) return color2;
  381. if (factor == 1) return color1;
  382. var factor1 = 1 - factor;
  383. return Color.FromArgb(
  384. (byte)(color1.A * factor + color2.A * factor1),
  385. (byte)(color1.R * factor + color2.R * factor1),
  386. (byte)(color1.G * factor + color2.G * factor1),
  387. (byte)(color1.B * factor + color2.B * factor1));
  388. }
  389. public static System.Windows.Media.Color MixColors(this System.Windows.Media.Color color1, double factor, System.Windows.Media.Color color2)
  390. {
  391. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  392. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  393. if (factor == 0) return color2;
  394. if (factor == 1) return color1;
  395. var factor1 = 1 - factor;
  396. return System.Windows.Media.Color.FromArgb(
  397. (byte)(color1.A * factor + color2.A * factor1),
  398. (byte)(color1.R * factor + color2.R * factor1),
  399. (byte)(color1.G * factor + color2.G * factor1),
  400. (byte)(color1.B * factor + color2.B * factor1));
  401. }
  402. public static string ColorToString(Color color)
  403. {
  404. return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",
  405. color.A,
  406. color.R,
  407. color.G,
  408. color.B
  409. );
  410. }
  411. public static Color StringToColor(string colorcode)
  412. {
  413. var col = Color.Transparent;
  414. if (!string.IsNullOrEmpty(colorcode))
  415. {
  416. var code = colorcode.Replace("#", "");
  417. if (code.Length == 6)
  418. col = Color.FromArgb(255,
  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. else if (code.Length == 8)
  423. col = Color.FromArgb(
  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. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  428. }
  429. return col;
  430. }
  431. public static System.Windows.Media.Color StringToMediaColor(string colorcode)
  432. {
  433. var col = Colors.Transparent;
  434. if (!string.IsNullOrEmpty(colorcode))
  435. {
  436. var code = colorcode.Replace("#", "");
  437. if (code.Length == 6)
  438. col = System.Windows.Media.Color.FromArgb(255,
  439. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  440. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  441. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  442. else if (code.Length == 8)
  443. col = System.Windows.Media.Color.FromArgb(
  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. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  448. }
  449. return col;
  450. }
  451. /// <summary>
  452. /// Creates color with corrected brightness.
  453. /// </summary>
  454. /// <param name="color">Color to correct.</param>
  455. /// <param name="correctionFactor">
  456. /// The brightness correction factor. Must be between -1 and 1.
  457. /// Negative values produce darker colors.
  458. /// </param>
  459. /// <returns>
  460. /// Corrected <see cref="Color" /> structure.
  461. /// </returns>
  462. public static System.Windows.Media.Color AdjustBrightness(this System.Windows.Media.Color color, float correctionFactor)
  463. {
  464. float red = color.R;
  465. float green = color.G;
  466. float blue = color.B;
  467. if (correctionFactor < 0)
  468. {
  469. correctionFactor = 1 + correctionFactor;
  470. red *= correctionFactor;
  471. green *= correctionFactor;
  472. blue *= correctionFactor;
  473. }
  474. else
  475. {
  476. red = (255 - red) * correctionFactor + red;
  477. green = (255 - green) * correctionFactor + green;
  478. blue = (255 - blue) * correctionFactor + blue;
  479. }
  480. return System.Windows.Media.Color.FromArgb(color.A, (byte)red, (byte)green, (byte)blue);
  481. }
  482. /// <summary>
  483. /// Takes a byte array and determines the image file type by
  484. /// comparing the first few bytes of the file to a list of known
  485. /// image file signatures.
  486. /// </summary>
  487. /// <param name="imageData">Byte array of the image data</param>
  488. /// <returns>ImageFormat corresponding to the image file format</returns>
  489. /// <exception cref="ArgumentException">Thrown if the image type can't be determined</exception>
  490. public static ImageFormat GetImageType(byte[] imageData)
  491. {
  492. foreach (var signatureEntry in SignatureTable)
  493. foreach (var signature in signatureEntry.Value)
  494. {
  495. var isMatch = true;
  496. for (var i = 0; i < signature.Length; i++)
  497. {
  498. var signatureByte = signature[i];
  499. // ToString("X") gets the hex representation and pads it to always be length 2
  500. var imageByte = imageData[i]
  501. .ToString("X2");
  502. if (signatureByte == imageByte)
  503. continue;
  504. isMatch = false;
  505. break;
  506. }
  507. if (isMatch) return signatureEntry.Key;
  508. }
  509. throw new ArgumentException("The byte array did not match any known image file signatures.");
  510. }
  511. public static System.Drawing.Bitmap Invert(this System.Drawing.Bitmap source)
  512. {
  513. Bitmap bmpDest = new Bitmap(source.Width,source.Height);
  514. ColorMatrix clrMatrix = new ColorMatrix(new float[][]
  515. {
  516. new float[] {-1, 0, 0, 0, 0},
  517. new float[] {0, -1, 0, 0, 0},
  518. new float[] {0, 0, -1, 0, 0},
  519. new float[] {0, 0, 0, 1, 0},
  520. new float[] {1, 1, 1, 0, 1}
  521. });
  522. using (ImageAttributes attrImage = new ImageAttributes())
  523. {
  524. attrImage.SetColorMatrix(clrMatrix);
  525. using (Graphics g = Graphics.FromImage(bmpDest))
  526. {
  527. g.DrawImage(source, new Rectangle(0, 0,
  528. source.Width, source.Height), 0, 0,
  529. source.Width, source.Height, GraphicsUnit.Pixel,
  530. attrImage);
  531. }
  532. }
  533. return bmpDest;
  534. }
  535. public static Font AdjustSize(this Font font, Graphics graphics, string text, int width)
  536. {
  537. Font result = null;
  538. for (int size = (int)font.Size; size > 0; size--)
  539. {
  540. result = new Font(font.Name, size, font.Style);
  541. SizeF adjustedSizeNew = graphics.MeasureString(text, result);
  542. if (width > Convert.ToInt32(adjustedSizeNew.Width))
  543. return result;
  544. }
  545. return result;
  546. }
  547. public static Bitmap WatermarkImage(this Bitmap image, String text, System.Windows.Media.Color color, int maxfontsize = 0)
  548. {
  549. return image.WatermarkImage(text, Color.FromArgb(color.A, color.R, color.G, color.B),maxfontsize);
  550. }
  551. public static Bitmap WatermarkImage(this Bitmap image, String text, Color color, int maxfontsize = 0)
  552. {
  553. int w = image.Width;
  554. int h = image.Height;
  555. Bitmap result = new System.Drawing.Bitmap(w, h);
  556. Graphics graphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)result);
  557. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  558. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  559. graphics.Clear(System.Drawing.Color.Transparent);
  560. graphics.DrawImage(image, 0, 0, w, h);
  561. Font drawFont = new System.Drawing.Font("Arial", 96).AdjustSize(graphics,text,(int)(image.Width * 0.9F));
  562. if ((maxfontsize > 0) && (drawFont.Size > maxfontsize))
  563. drawFont = new System.Drawing.Font("Arial", maxfontsize);
  564. SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
  565. StringFormat stringFormat = new StringFormat();
  566. stringFormat.Alignment = StringAlignment.Center;
  567. stringFormat.LineAlignment = StringAlignment.Center;
  568. graphics.DrawString(text, drawFont, drawBrush, new Rectangle(0,0,w,h), stringFormat);
  569. graphics.Dispose();
  570. return result;
  571. }
  572. private static System.Windows.Media.Color AdjustColor(System.Windows.Media.Color color, Action<HSL> action)
  573. {
  574. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R,color.G,color.B));
  575. action(hsl);
  576. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  577. return System.Windows.Media.Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
  578. }
  579. private static int AdjustPercentage(int original, int percentage)
  580. {
  581. int percent = Math.Min(100, Math.Max(-100, percentage));
  582. int newvalue = (percent < 0)
  583. ? (byte)((percent * original) / 100)
  584. : (byte)((percent * (100 - original)) / 100);
  585. return original + newvalue;
  586. }
  587. public static System.Windows.Media.Color AdjustHue(this System.Windows.Media.Color color, int degrees) =>
  588. AdjustColor(color, (hsl => hsl.H += degrees));
  589. public static System.Windows.Media.Color AdjustSaturation(this System.Windows.Media.Color color, int percentage) =>
  590. AdjustColor(color, (hsl =>
  591. {
  592. hsl.S = (byte)AdjustPercentage(hsl.S, percentage);
  593. }));
  594. public static System.Windows.Media.Color SetSaturation(this System.Windows.Media.Color color, int percentage) =>
  595. AdjustColor(color, (hsl => hsl.S = (byte)percentage));
  596. public static System.Windows.Media.Color AdjustLightness(this System.Windows.Media.Color color, int percentage) =>
  597. AdjustColor(color, (hsl =>
  598. {
  599. hsl.L = (byte)AdjustPercentage(hsl.L, percentage);
  600. }));
  601. public static System.Windows.Media.Color SetLightness(this System.Windows.Media.Color color, int percentage) =>
  602. AdjustColor(color, (hsl => hsl.L = (byte)percentage));
  603. public static System.Windows.Media.Color SetAlpha(this System.Windows.Media.Color color, byte alpha) =>
  604. System.Windows.Media.Color.FromArgb(alpha, color.R, color.G, color.B);
  605. public static HSL ToHSL(this System.Windows.Media.Color color)
  606. {
  607. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  608. }
  609. public static System.Windows.Media.Color ToColor(this HSL hsl)
  610. {
  611. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  612. return System.Windows.Media.Color.FromRgb(rgb.R, rgb.G, rgb.B);
  613. }
  614. public static HSL ToHSL(this System.Drawing.Color color)
  615. {
  616. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  617. }
  618. public static System.Windows.Media.Color GetForegroundColor(this System.Windows.Media.Color c, int threshold = 130)
  619. {
  620. var perceivedbrightness = (int)Math.Sqrt(
  621. c.R * c.R * .299 +
  622. c.G * c.G * .587 +
  623. c.B * c.B * .114);
  624. return perceivedbrightness >= threshold ? Colors.Black : Colors.White;
  625. }
  626. public static uint ToUint(this System.Drawing.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  627. public static uint ToUint(this System.Windows.Media.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  628. public enum ImageEncoding
  629. {
  630. JPEG
  631. }
  632. public static ImageCodecInfo? GetEncoder(ImageFormat format)
  633. {
  634. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  635. foreach (ImageCodecInfo codec in codecs)
  636. {
  637. if (codec.FormatID == format.Guid)
  638. {
  639. return codec;
  640. }
  641. }
  642. return null;
  643. }
  644. public static List<byte[]> RenderPDFToImages(byte[] pdfData, ImageEncoding encoding = ImageEncoding.JPEG)
  645. {
  646. var rendered = new List<byte[]>();
  647. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  648. Bitmap[] images = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  649. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  650. var quality = Encoder.Quality;
  651. var encodeParams = new EncoderParameters(1);
  652. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  653. if (images != null)
  654. foreach (var image in images)
  655. {
  656. using (var data = new MemoryStream())
  657. {
  658. image.Save(data, jpgEncoder, encodeParams);
  659. rendered.Add(data.ToArray());
  660. }
  661. }
  662. return rendered;
  663. }
  664. }
  665. }