ImageUtils.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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 Bitmap BitmapSourceToBitmap(BitmapSource source)
  282. {
  283. if (source == null)
  284. return null;
  285. var pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb; //Bgr32 equiv default
  286. if (source.Format == PixelFormats.Bgr24)
  287. pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  288. else if (source.Format == PixelFormats.Pbgra32)
  289. pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
  290. else if (source.Format == PixelFormats.Prgba64)
  291. pixelFormat = System.Drawing.Imaging.PixelFormat.Format64bppPArgb;
  292. Bitmap bmp = new Bitmap(
  293. source.PixelWidth,
  294. source.PixelHeight,
  295. pixelFormat);
  296. BitmapData data = bmp.LockBits(
  297. new Rectangle(System.Drawing.Point.Empty, bmp.Size),
  298. ImageLockMode.WriteOnly,
  299. pixelFormat);
  300. source.CopyPixels(
  301. Int32Rect.Empty,
  302. data.Scan0,
  303. data.Height * data.Stride,
  304. data.Stride);
  305. bmp.UnlockBits(data);
  306. return bmp;
  307. }
  308. public static BitmapImage ToBitmapImage(this Bitmap bitmap)
  309. {
  310. using (var memory = new MemoryStream())
  311. {
  312. bitmap.Save(memory, ImageFormat.Png);
  313. memory.Position = 0;
  314. var bitmapImage = new BitmapImage();
  315. bitmapImage.BeginInit();
  316. bitmapImage.StreamSource = memory;
  317. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  318. bitmapImage.EndInit();
  319. bitmapImage.Freeze();
  320. return bitmapImage;
  321. }
  322. }
  323. public static BitmapImage LoadImage(byte[] imageData)
  324. {
  325. var result = new BitmapImage();
  326. result.LoadImage(imageData);
  327. return result;
  328. }
  329. public static void LoadImage(this BitmapImage image, byte[]? imageData)
  330. {
  331. if (imageData == null || imageData.Length == 0)
  332. return;
  333. using (var mem = new MemoryStream(imageData))
  334. {
  335. mem.Position = 0;
  336. image.BeginInit();
  337. image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
  338. image.CacheOption = BitmapCacheOption.OnLoad;
  339. image.UriSource = null;
  340. image.StreamSource = mem;
  341. image.EndInit();
  342. }
  343. image.Freeze();
  344. }
  345. public static Bitmap? MergeBitmaps(IEnumerable<Bitmap> bitmaps, int padding)
  346. {
  347. if (!bitmaps.Any())
  348. return null;
  349. var totalwidth = bitmaps.Aggregate(0, (total, next) => total + next.Width + (total > 0 ? padding : 0) );
  350. var maxheight = bitmaps.Aggregate(0, (max, next) => Math.Max(next.Height,max) );
  351. Bitmap result = new Bitmap(totalwidth, maxheight);
  352. using (Graphics g = Graphics.FromImage(result))
  353. {
  354. g.Clear(Color.Transparent);
  355. int left = 0;
  356. foreach (var bitmap in bitmaps)
  357. {
  358. g.DrawImage(bitmap, left, 0);
  359. left += bitmap.Width + padding;
  360. }
  361. }
  362. return result;
  363. }
  364. public static byte[] ToArray<T>(this BitmapImage image) where T : BitmapEncoder, new()
  365. {
  366. byte[] data;
  367. var encoder = new T();
  368. encoder.Frames.Add(BitmapFrame.Create(image));
  369. using (var ms = new MemoryStream())
  370. {
  371. encoder.Save(ms);
  372. data = ms.ToArray();
  373. }
  374. return data;
  375. }
  376. public static BitmapImage Resize(this BitmapImage image, int height, int width)
  377. {
  378. var buffer = image.ToArray<BmpBitmapEncoder>();
  379. var ms = new MemoryStream(buffer);
  380. var result = new BitmapImage();
  381. result.BeginInit();
  382. result.CacheOption = BitmapCacheOption.None;
  383. result.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  384. result.DecodePixelWidth = width;
  385. result.DecodePixelHeight = height;
  386. result.StreamSource = ms;
  387. result.Rotation = Rotation.Rotate0;
  388. result.EndInit();
  389. buffer = null;
  390. return result;
  391. }
  392. public static Bitmap Resize(this Bitmap bitmap, int width, int height)
  393. {
  394. if ((width == bitmap.Width) && (height == bitmap.Height))
  395. return bitmap;
  396. return new Bitmap(bitmap,new Size(width,height));
  397. }
  398. public static BitmapImage Scale(this BitmapImage image, int maxheight, int maxwidth)
  399. {
  400. var scaleHeight = maxheight / (float)image.Height;
  401. var scaleWidth = maxwidth / (float)image.Width;
  402. var scale = Math.Min(scaleHeight, scaleWidth);
  403. return image.Resize((int)(image.Height * scale), (int)(image.Width * scale));
  404. }
  405. public static Bitmap BitmapFromColor(Color color, int width, int height, Color frame)
  406. {
  407. var result = new Bitmap(width, height);
  408. var g = Graphics.FromImage(result);
  409. g.Clear(color);
  410. if (frame != Color.Transparent)
  411. g.DrawRectangle(new Pen(new SolidBrush(frame), 1), new Rectangle(0, 0, width-1, height-1));
  412. return result;
  413. }
  414. public static Bitmap BitmapFromColor(System.Windows.Media.Color color, int width, int height, System.Windows.Media.Color frame)
  415. {
  416. var result = new Bitmap(width, height);
  417. var g = Graphics.FromImage(result);
  418. g.Clear(Color.FromArgb(color.A,color.R,color.G,color.B));
  419. if (frame != Colors.Transparent)
  420. 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));
  421. return result;
  422. }
  423. public static Color MixColors(this Color color1, double factor, Color color2)
  424. {
  425. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  426. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  427. if (factor == 0) return color2;
  428. if (factor == 1) return color1;
  429. var factor1 = 1 - factor;
  430. return Color.FromArgb(
  431. (byte)(color1.A * factor + color2.A * factor1),
  432. (byte)(color1.R * factor + color2.R * factor1),
  433. (byte)(color1.G * factor + color2.G * factor1),
  434. (byte)(color1.B * factor + color2.B * factor1));
  435. }
  436. public static System.Windows.Media.Color MixColors(this System.Windows.Media.Color color1, double factor, System.Windows.Media.Color color2)
  437. {
  438. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  439. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  440. if (factor == 0) return color2;
  441. if (factor == 1) return color1;
  442. var factor1 = 1 - factor;
  443. return System.Windows.Media.Color.FromArgb(
  444. (byte)(color1.A * factor + color2.A * factor1),
  445. (byte)(color1.R * factor + color2.R * factor1),
  446. (byte)(color1.G * factor + color2.G * factor1),
  447. (byte)(color1.B * factor + color2.B * factor1));
  448. }
  449. public static string ColorToString(Color color)
  450. {
  451. return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",
  452. color.A,
  453. color.R,
  454. color.G,
  455. color.B
  456. );
  457. }
  458. public static Color StringToColor(string colorcode)
  459. {
  460. var col = Color.Transparent;
  461. if (!string.IsNullOrEmpty(colorcode))
  462. {
  463. var code = colorcode.Replace("#", "");
  464. if (code.Length == 6)
  465. col = Color.FromArgb(255,
  466. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  467. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  468. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  469. else if (code.Length == 8)
  470. col = Color.FromArgb(
  471. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  472. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  473. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  474. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  475. }
  476. return col;
  477. }
  478. public static System.Windows.Media.Color StringToMediaColor(string colorcode)
  479. {
  480. var col = Colors.Transparent;
  481. if (!string.IsNullOrEmpty(colorcode))
  482. {
  483. var code = colorcode.Replace("#", "");
  484. if (code.Length == 6)
  485. col = System.Windows.Media.Color.FromArgb(255,
  486. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  487. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  488. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  489. else if (code.Length == 8)
  490. col = System.Windows.Media.Color.FromArgb(
  491. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  492. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  493. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  494. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  495. }
  496. return col;
  497. }
  498. /// <summary>
  499. /// Creates color with corrected brightness.
  500. /// </summary>
  501. /// <param name="color">Color to correct.</param>
  502. /// <param name="correctionFactor">
  503. /// The brightness correction factor. Must be between -1 and 1.
  504. /// Negative values produce darker colors.
  505. /// </param>
  506. /// <returns>
  507. /// Corrected <see cref="Color" /> structure.
  508. /// </returns>
  509. public static System.Windows.Media.Color AdjustBrightness(this System.Windows.Media.Color color, float correctionFactor)
  510. {
  511. float red = color.R;
  512. float green = color.G;
  513. float blue = color.B;
  514. if (correctionFactor < 0)
  515. {
  516. correctionFactor = 1 + correctionFactor;
  517. red *= correctionFactor;
  518. green *= correctionFactor;
  519. blue *= correctionFactor;
  520. }
  521. else
  522. {
  523. red = (255 - red) * correctionFactor + red;
  524. green = (255 - green) * correctionFactor + green;
  525. blue = (255 - blue) * correctionFactor + blue;
  526. }
  527. return System.Windows.Media.Color.FromArgb(color.A, (byte)red, (byte)green, (byte)blue);
  528. }
  529. /// <summary>
  530. /// Takes a byte array and determines the image file type by
  531. /// comparing the first few bytes of the file to a list of known
  532. /// image file signatures.
  533. /// </summary>
  534. /// <param name="imageData">Byte array of the image data</param>
  535. /// <returns>ImageFormat corresponding to the image file format</returns>
  536. /// <exception cref="ArgumentException">Thrown if the image type can't be determined</exception>
  537. public static ImageFormat GetImageType(byte[] imageData)
  538. {
  539. foreach (var signatureEntry in SignatureTable)
  540. foreach (var signature in signatureEntry.Value)
  541. {
  542. var isMatch = true;
  543. for (var i = 0; i < signature.Length; i++)
  544. {
  545. var signatureByte = signature[i];
  546. // ToString("X") gets the hex representation and pads it to always be length 2
  547. var imageByte = imageData[i]
  548. .ToString("X2");
  549. if (signatureByte == imageByte)
  550. continue;
  551. isMatch = false;
  552. break;
  553. }
  554. if (isMatch) return signatureEntry.Key;
  555. }
  556. throw new ArgumentException("The byte array did not match any known image file signatures.");
  557. }
  558. public static System.Drawing.Bitmap Invert(this System.Drawing.Bitmap source)
  559. {
  560. Bitmap bmpDest = new Bitmap(source.Width,source.Height);
  561. ColorMatrix clrMatrix = new ColorMatrix(new float[][]
  562. {
  563. new float[] {-1, 0, 0, 0, 0},
  564. new float[] {0, -1, 0, 0, 0},
  565. new float[] {0, 0, -1, 0, 0},
  566. new float[] {0, 0, 0, 1, 0},
  567. new float[] {1, 1, 1, 0, 1}
  568. });
  569. using (ImageAttributes attrImage = new ImageAttributes())
  570. {
  571. attrImage.SetColorMatrix(clrMatrix);
  572. using (Graphics g = Graphics.FromImage(bmpDest))
  573. {
  574. g.DrawImage(source, new Rectangle(0, 0,
  575. source.Width, source.Height), 0, 0,
  576. source.Width, source.Height, GraphicsUnit.Pixel,
  577. attrImage);
  578. }
  579. }
  580. return bmpDest;
  581. }
  582. public static Font AdjustSize(this Font font, Graphics graphics, string text, int width)
  583. {
  584. Font result = null;
  585. for (int size = (int)font.Size; size > 0; size--)
  586. {
  587. result = new Font(font.Name, size, font.Style);
  588. SizeF adjustedSizeNew = graphics.MeasureString(text, result);
  589. if (width > Convert.ToInt32(adjustedSizeNew.Width))
  590. return result;
  591. }
  592. return result;
  593. }
  594. public static Bitmap WatermarkImage(this Bitmap image, String text, System.Windows.Media.Color color, int maxfontsize = 0)
  595. {
  596. return image.WatermarkImage(text, Color.FromArgb(color.A, color.R, color.G, color.B),maxfontsize);
  597. }
  598. public static Bitmap WatermarkImage(this Bitmap image, String text, Color color, int maxfontsize = 0)
  599. {
  600. int w = image.Width;
  601. int h = image.Height;
  602. Bitmap result = new System.Drawing.Bitmap(w, h);
  603. Graphics graphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)result);
  604. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  605. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  606. graphics.Clear(System.Drawing.Color.Transparent);
  607. graphics.DrawImage(image, 0, 0, w, h);
  608. Font drawFont = new System.Drawing.Font("Arial", 96).AdjustSize(graphics,text,(int)(image.Width * 0.9F));
  609. if ((maxfontsize > 0) && (drawFont.Size > maxfontsize))
  610. drawFont = new System.Drawing.Font("Arial", maxfontsize);
  611. SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
  612. StringFormat stringFormat = new StringFormat();
  613. stringFormat.Alignment = StringAlignment.Center;
  614. stringFormat.LineAlignment = StringAlignment.Center;
  615. graphics.DrawString(text, drawFont, drawBrush, new Rectangle(0,0,w,h), stringFormat);
  616. graphics.Dispose();
  617. return result;
  618. }
  619. private static System.Windows.Media.Color AdjustColor(System.Windows.Media.Color color, Action<HSL> action)
  620. {
  621. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R,color.G,color.B));
  622. action(hsl);
  623. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  624. return System.Windows.Media.Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
  625. }
  626. private static int AdjustPercentage(int original, int percentage)
  627. {
  628. int percent = Math.Min(100, Math.Max(-100, percentage));
  629. int newvalue = (percent < 0)
  630. ? (byte)((percent * original) / 100)
  631. : (byte)((percent * (100 - original)) / 100);
  632. return original + newvalue;
  633. }
  634. public static System.Windows.Media.Color AdjustHue(this System.Windows.Media.Color color, int degrees) =>
  635. AdjustColor(color, (hsl => hsl.H += degrees));
  636. public static System.Windows.Media.Color AdjustSaturation(this System.Windows.Media.Color color, int percentage) =>
  637. AdjustColor(color, (hsl =>
  638. {
  639. hsl.S = (byte)AdjustPercentage(hsl.S, percentage);
  640. }));
  641. public static System.Windows.Media.Color SetSaturation(this System.Windows.Media.Color color, int percentage) =>
  642. AdjustColor(color, (hsl => hsl.S = (byte)percentage));
  643. public static System.Windows.Media.Color AdjustLightness(this System.Windows.Media.Color color, int percentage) =>
  644. AdjustColor(color, (hsl =>
  645. {
  646. hsl.L = (byte)AdjustPercentage(hsl.L, percentage);
  647. }));
  648. public static System.Windows.Media.Color SetLightness(this System.Windows.Media.Color color, int percentage) =>
  649. AdjustColor(color, (hsl => hsl.L = (byte)percentage));
  650. public static System.Windows.Media.Color SetAlpha(this System.Windows.Media.Color color, byte alpha) =>
  651. System.Windows.Media.Color.FromArgb(alpha, color.R, color.G, color.B);
  652. public static HSL ToHSL(this System.Windows.Media.Color color)
  653. {
  654. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  655. }
  656. public static System.Windows.Media.Color ToColor(this HSL hsl)
  657. {
  658. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  659. return System.Windows.Media.Color.FromRgb(rgb.R, rgb.G, rgb.B);
  660. }
  661. public static HSL ToHSL(this System.Drawing.Color color)
  662. {
  663. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  664. }
  665. public static System.Windows.Media.Color GetForegroundColor(this System.Windows.Media.Color c, int threshold = 130)
  666. {
  667. var perceivedbrightness = (int)Math.Sqrt(
  668. c.R * c.R * .299 +
  669. c.G * c.G * .587 +
  670. c.B * c.B * .114);
  671. return perceivedbrightness >= threshold ? Colors.Black : Colors.White;
  672. }
  673. public static uint ToUint(this System.Drawing.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  674. public static uint ToUint(this System.Windows.Media.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  675. public enum ImageEncoding
  676. {
  677. JPEG
  678. }
  679. public static ImageCodecInfo? GetEncoder(ImageFormat format)
  680. {
  681. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  682. foreach (ImageCodecInfo codec in codecs)
  683. {
  684. if (codec.FormatID == format.Guid)
  685. {
  686. return codec;
  687. }
  688. }
  689. return null;
  690. }
  691. public static List<byte[]> RenderPDFToImages(byte[] pdfData, ImageEncoding encoding = ImageEncoding.JPEG)
  692. {
  693. var rendered = new List<byte[]>();
  694. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  695. Bitmap[] images = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  696. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  697. var quality = Encoder.Quality;
  698. var encodeParams = new EncoderParameters(1);
  699. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  700. if (images != null)
  701. foreach (var image in images)
  702. {
  703. using (var data = new MemoryStream())
  704. {
  705. image.Save(data, jpgEncoder, encodeParams);
  706. rendered.Add(data.ToArray());
  707. }
  708. }
  709. return rendered;
  710. }
  711. public static ContentControl CreatePreviewWindowButtonContent(string caption, Bitmap bitmap)
  712. {
  713. Frame frame = new Frame();
  714. frame.Padding = new Thickness(0);
  715. frame.Margin = new Thickness(10, 10, 10, 5);
  716. Grid grid = new Grid();
  717. grid.Margin = new Thickness(0);
  718. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  719. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  720. var img = new System.Windows.Controls.Image
  721. {
  722. Source = bitmap.AsBitmapImage(),
  723. Height = 32.0F,
  724. Width = 32.0F,
  725. Margin = new Thickness(10)
  726. };
  727. img.SetValue(Grid.RowProperty, 0);
  728. img.Margin = new Thickness(0);
  729. grid.Children.Add(img);
  730. var txt = new System.Windows.Controls.TextBox();
  731. txt.IsEnabled = false;
  732. txt.Text = caption;
  733. txt.BorderThickness = new Thickness(0);
  734. txt.TextWrapping = TextWrapping.WrapWithOverflow;
  735. txt.MaxWidth = 90;
  736. txt.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
  737. txt.SetValue(Grid.RowProperty, 1);
  738. grid.Children.Add(txt);
  739. frame.Content = grid;
  740. return frame;
  741. }
  742. }
  743. }