ImageUtils.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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. using Syncfusion.Pdf.Graphics;
  25. using Syncfusion.Pdf;
  26. using System.Diagnostics.CodeAnalysis;
  27. using System.Runtime;
  28. using System.Text;
  29. using Encoder = System.Drawing.Imaging.Encoder;
  30. namespace InABox.WPF
  31. {
  32. public static class ImageUtils
  33. {
  34. // https://en.wikipedia.org/wiki/List_of_file_signatures
  35. /* Bytes in c# have a range of 0 to 255 so each byte can be represented as
  36. * a two digit hex string. */
  37. private static readonly Dictionary<ImageFormat, string[][]> SignatureTable = new()
  38. {
  39. {
  40. ImageFormat.Jpeg,
  41. new[]
  42. {
  43. new[] { "FF", "D8", "FF", "DB" },
  44. new[] { "FF", "D8", "FF", "EE" },
  45. new[] { "FF", "D8", "FF", "E0", "00", "10", "4A", "46", "49", "46", "00", "01" }
  46. }
  47. },
  48. {
  49. ImageFormat.Gif,
  50. new[]
  51. {
  52. new[] { "47", "49", "46", "38", "37", "61" },
  53. new[] { "47", "49", "46", "38", "39", "61" }
  54. }
  55. },
  56. {
  57. ImageFormat.Png,
  58. new[]
  59. {
  60. new[] { "89", "50", "4E", "47", "0D", "0A", "1A", "0A" }
  61. }
  62. },
  63. {
  64. ImageFormat.Bmp,
  65. new[]
  66. {
  67. new[] { "42", "4D" }
  68. }
  69. }
  70. };
  71. public static Size Adjust(this Size src, double maxWidth, double maxHeight, bool enlarge = false)
  72. {
  73. maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
  74. maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
  75. var rnd = Math.Min((decimal)maxWidth / src.Width, (decimal)maxHeight / src.Height);
  76. return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
  77. }
  78. public static Bitmap AsGrayScale(this Bitmap source)
  79. {
  80. //create a blank bitmap the same size as original
  81. var newBitmap = new Bitmap(source.Width, source.Height);
  82. //get a graphics object from the new image
  83. var g = Graphics.FromImage(newBitmap);
  84. //create the grayscale ColorMatrix
  85. var colorMatrix = new ColorMatrix(
  86. new[]
  87. {
  88. new[] { .3f, .3f, .3f, 0, 0 },
  89. new[] { .59f, .59f, .59f, 0, 0 },
  90. new[] { .11f, .11f, .11f, 0, 0 },
  91. new float[] { 0, 0, 0, 1, 0 },
  92. new float[] { 0, 0, 0, 0, 1 }
  93. });
  94. //create some image attributes
  95. var attributes = new ImageAttributes();
  96. //set the color matrix attribute
  97. attributes.SetColorMatrix(colorMatrix);
  98. //draw the original image on the new image
  99. //using the grayscale color matrix
  100. g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
  101. 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
  102. //dispose the Graphics object
  103. g.Dispose();
  104. return newBitmap;
  105. }
  106. public static BitmapImage AsBitmapImage(this Bitmap src, int height, int width, bool transparent = true)
  107. {
  108. var resized = new Bitmap(src, new Size(width, height));
  109. return AsBitmapImage(resized, transparent);
  110. }
  111. public static BitmapImage AsBitmapImage(this Bitmap src, Color transparent)
  112. {
  113. src.MakeTransparent(transparent);
  114. return src.AsBitmapImage();
  115. }
  116. public static Bitmap ChangeColor(this Bitmap image, Color fromColor, Color toColor)
  117. {
  118. var attributes = new ImageAttributes();
  119. attributes.SetRemapTable(new ColorMap[]
  120. {
  121. new()
  122. {
  123. OldColor = fromColor,
  124. NewColor = toColor
  125. }
  126. }, ColorAdjustType.Bitmap);
  127. using (var g = Graphics.FromImage(image))
  128. {
  129. g.DrawImage(
  130. image,
  131. new Rectangle(Point.Empty, image.Size),
  132. 0, 0, image.Width, image.Height,
  133. GraphicsUnit.Pixel,
  134. attributes);
  135. }
  136. return image;
  137. }
  138. public static Bitmap Fade(this Bitmap source, float opacity)
  139. {
  140. var result = new Bitmap(source.Width, source.Height);
  141. //create a graphics object from the image
  142. using (var gfx = Graphics.FromImage(result))
  143. {
  144. if (opacity < 1.0)
  145. gfx.Clear(Color.White);
  146. //create a color matrix object
  147. var matrix = new ColorMatrix();
  148. //set the opacity
  149. matrix.Matrix33 = opacity;
  150. //create image attributes
  151. var attributes = new ImageAttributes();
  152. //set the color(opacity) of the image
  153. attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
  154. //now draw the image
  155. gfx.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel,
  156. attributes);
  157. }
  158. return result;
  159. }
  160. public static BitmapImage AsBitmapImage(this Bitmap src, Color replace, Color with)
  161. {
  162. return src.ChangeColor(replace, with).AsBitmapImage(false);
  163. }
  164. public static Bitmap AsBitmap(this BitmapImage bitmapImage)
  165. {
  166. using (var outStream = new MemoryStream())
  167. {
  168. BitmapEncoder enc = new BmpBitmapEncoder();
  169. enc.Frames.Add(BitmapFrame.Create(bitmapImage));
  170. enc.Save(outStream);
  171. var bitmap = new Bitmap(outStream);
  172. return new Bitmap(bitmap);
  173. }
  174. }
  175. public static Bitmap AsBitmap(this BitmapSource source)
  176. {
  177. var width = source.PixelWidth;
  178. var height = source.PixelHeight;
  179. var stride = width * ((source.Format.BitsPerPixel + 7) / 8);
  180. var ptr = IntPtr.Zero;
  181. try
  182. {
  183. ptr = Marshal.AllocHGlobal(height * stride);
  184. source.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
  185. using (var btm = new Bitmap(width, height, stride, PixelFormat.Format1bppIndexed, ptr))
  186. {
  187. return new Bitmap(btm);
  188. }
  189. }
  190. finally
  191. {
  192. if (ptr != IntPtr.Zero)
  193. Marshal.FreeHGlobal(ptr);
  194. }
  195. }
  196. public static Bitmap AsBitmap2(this BitmapSource source)
  197. {
  198. var bmp = new Bitmap(
  199. source.PixelWidth,
  200. source.PixelHeight,
  201. PixelFormat.Format32bppPArgb);
  202. var data = bmp.LockBits(
  203. new Rectangle(Point.Empty, bmp.Size),
  204. ImageLockMode.WriteOnly,
  205. PixelFormat.Format32bppPArgb);
  206. source.CopyPixels(
  207. Int32Rect.Empty,
  208. data.Scan0,
  209. data.Height * data.Stride,
  210. data.Stride);
  211. bmp.UnlockBits(data);
  212. return bmp;
  213. }
  214. public static BitmapImage? BitmapImageFromBase64(string base64)
  215. {
  216. return BitmapImageFromBytes(Convert.FromBase64String(base64));
  217. }
  218. public static BitmapImage? BitmapImageFromBytes(byte[]? data)
  219. {
  220. if (data?.Any() != true)
  221. return null;
  222. var imageSource = new BitmapImage();
  223. using (var ms = new MemoryStream(data))
  224. {
  225. imageSource.BeginInit();
  226. imageSource.StreamSource = ms;
  227. imageSource.CacheOption = BitmapCacheOption.OnLoad;
  228. imageSource.EndInit();
  229. }
  230. return imageSource;
  231. }
  232. public static BitmapImage? BitmapImageFromStream(Stream data)
  233. {
  234. var imageSource = new BitmapImage();
  235. imageSource.BeginInit();
  236. imageSource.StreamSource = data;
  237. imageSource.CacheOption = BitmapCacheOption.OnLoad;
  238. imageSource.EndInit();
  239. return imageSource;
  240. }
  241. public static BitmapImage AsBitmapImage(this Bitmap src, bool transparent = true)
  242. {
  243. if (transparent)
  244. {
  245. var pixel = src.GetPixel(0, 0);
  246. if(pixel.A == byte.MaxValue)
  247. {
  248. src.MakeTransparent(pixel);
  249. }
  250. }
  251. var bitmapImage = new BitmapImage();
  252. using (var memory = new MemoryStream())
  253. {
  254. src.Save(memory, ImageFormat.Png);
  255. memory.Position = 0;
  256. bitmapImage.BeginInit();
  257. bitmapImage.StreamSource = memory;
  258. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  259. bitmapImage.EndInit();
  260. }
  261. return bitmapImage;
  262. }
  263. public static BitmapSource AsBitmapSource(this Metafile metafile, int width, int height, Color background)
  264. {
  265. var src = new Bitmap(metafile.Width, metafile.Height);
  266. src.SetResolution(metafile.HorizontalResolution, metafile.VerticalResolution);
  267. using (var g = Graphics.FromImage(src))
  268. {
  269. g.DrawImage(metafile, 0, 0, metafile.Width, metafile.Height);
  270. }
  271. var scale = Math.Min(width / (float)metafile.Width, height / (float)metafile.Height);
  272. var scaleWidth = src.Width * scale;
  273. var scaleHeight = src.Height * scale;
  274. var xoffset = (width - scaleWidth) / 2.0F;
  275. var yoffset = (height - scaleHeight) / 2.0F;
  276. using (var bmp = new Bitmap(width, height))
  277. {
  278. bmp.SetResolution(metafile.HorizontalResolution, metafile.VerticalResolution);
  279. using (var g = Graphics.FromImage(bmp))
  280. {
  281. g.InterpolationMode = InterpolationMode.High;
  282. g.CompositingQuality = CompositingQuality.HighQuality;
  283. g.SmoothingMode = SmoothingMode.AntiAlias;
  284. g.FillRectangle(new SolidBrush(background), new RectangleF(0, 0, width, height));
  285. g.DrawImage(src, xoffset, yoffset, scaleWidth, scaleHeight);
  286. }
  287. bmp.Save("c:\\development\\emf2bmp.png");
  288. return Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  289. }
  290. }
  291. public static Bitmap BitmapSourceToBitmap(BitmapSource source)
  292. {
  293. if (source == null)
  294. return null;
  295. var pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb; //Bgr32 equiv default
  296. if (source.Format == PixelFormats.Bgr24)
  297. pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  298. else if (source.Format == PixelFormats.Pbgra32)
  299. pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
  300. else if (source.Format == PixelFormats.Prgba64)
  301. pixelFormat = System.Drawing.Imaging.PixelFormat.Format64bppPArgb;
  302. Bitmap bmp = new Bitmap(
  303. source.PixelWidth,
  304. source.PixelHeight,
  305. pixelFormat);
  306. BitmapData data = bmp.LockBits(
  307. new Rectangle(System.Drawing.Point.Empty, bmp.Size),
  308. ImageLockMode.WriteOnly,
  309. pixelFormat);
  310. source.CopyPixels(
  311. Int32Rect.Empty,
  312. data.Scan0,
  313. data.Height * data.Stride,
  314. data.Stride);
  315. bmp.UnlockBits(data);
  316. return bmp;
  317. }
  318. public static BitmapImage ToBitmapImage(this Bitmap bitmap)
  319. {
  320. using (var memory = new MemoryStream())
  321. {
  322. bitmap.Save(memory, ImageFormat.Png);
  323. memory.Position = 0;
  324. var bitmapImage = new BitmapImage();
  325. bitmapImage.BeginInit();
  326. bitmapImage.StreamSource = memory;
  327. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  328. bitmapImage.EndInit();
  329. bitmapImage.Freeze();
  330. return bitmapImage;
  331. }
  332. }
  333. /// <summary>
  334. /// Load an image from image data; this will return <see langword="null"/> if <paramref name="imageData"/> is <see langword="null"/> or empty.
  335. /// </summary>
  336. /// <param name="imageData"></param>
  337. /// <returns></returns>
  338. public static BitmapImage? LoadImage(byte[]? imageData)
  339. {
  340. if(imageData is null || imageData.Length == 0)
  341. {
  342. return null;
  343. }
  344. var result = new BitmapImage();
  345. result.LoadImage(imageData);
  346. return result;
  347. }
  348. private static void LoadImage(this BitmapImage image, byte[] imageData)
  349. {
  350. using (var mem = new MemoryStream(imageData))
  351. {
  352. mem.Position = 0;
  353. image.BeginInit();
  354. image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
  355. image.CacheOption = BitmapCacheOption.OnLoad;
  356. image.UriSource = null;
  357. image.StreamSource = mem;
  358. image.EndInit();
  359. }
  360. image.Freeze();
  361. }
  362. public static Bitmap? MergeBitmaps(IEnumerable<Bitmap> bitmaps, int padding)
  363. {
  364. if (!bitmaps.Any())
  365. return null;
  366. var totalwidth = bitmaps.Aggregate(0, (total, next) => total + next.Width + (total > 0 ? padding : 0) );
  367. var maxheight = bitmaps.Aggregate(0, (max, next) => Math.Max(next.Height,max) );
  368. Bitmap result = new Bitmap(totalwidth, maxheight);
  369. using (Graphics g = Graphics.FromImage(result))
  370. {
  371. g.Clear(Color.Transparent);
  372. int left = 0;
  373. foreach (var bitmap in bitmaps)
  374. {
  375. g.DrawImage(bitmap, left, 0);
  376. left += bitmap.Width + padding;
  377. }
  378. }
  379. return result;
  380. }
  381. public static byte[] ToArray<T>(this BitmapImage image) where T : BitmapEncoder, new()
  382. {
  383. byte[] data;
  384. var encoder = new T();
  385. encoder.Frames.Add(BitmapFrame.Create(image));
  386. using (var ms = new MemoryStream())
  387. {
  388. encoder.Save(ms);
  389. data = ms.ToArray();
  390. }
  391. return data;
  392. }
  393. public static BitmapImage Resize(this BitmapImage image, int height, int width)
  394. {
  395. var buffer = image.ToArray<BmpBitmapEncoder>();
  396. var ms = new MemoryStream(buffer);
  397. var result = new BitmapImage();
  398. result.BeginInit();
  399. result.CacheOption = BitmapCacheOption.None;
  400. result.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  401. result.DecodePixelWidth = width;
  402. result.DecodePixelHeight = height;
  403. result.StreamSource = ms;
  404. result.Rotation = Rotation.Rotate0;
  405. result.EndInit();
  406. buffer = null;
  407. return result;
  408. }
  409. public static Bitmap Resize(this Bitmap bitmap, int width, int height)
  410. {
  411. if ((width == bitmap.Width) && (height == bitmap.Height))
  412. return bitmap;
  413. return new Bitmap(bitmap,new Size(width,height));
  414. }
  415. public static BitmapImage Scale(this BitmapImage image, int maxheight, int maxwidth)
  416. {
  417. var scaleHeight = maxheight / (float)image.Height;
  418. var scaleWidth = maxwidth / (float)image.Width;
  419. var scale = Math.Min(scaleHeight, scaleWidth);
  420. return image.Resize((int)(image.Height * scale), (int)(image.Width * scale));
  421. }
  422. public static Bitmap BitmapFromColor(Color color, int width, int height, Color frame)
  423. {
  424. var result = new Bitmap(width, height);
  425. var g = Graphics.FromImage(result);
  426. g.Clear(color);
  427. if (frame != Color.Transparent)
  428. g.DrawRectangle(new Pen(new SolidBrush(frame), 1), new Rectangle(0, 0, width-1, height-1));
  429. return result;
  430. }
  431. public static Bitmap BitmapFromColor(System.Windows.Media.Color color, int width, int height, System.Windows.Media.Color frame)
  432. {
  433. var result = new Bitmap(width, height);
  434. var g = Graphics.FromImage(result);
  435. g.Clear(Color.FromArgb(color.A,color.R,color.G,color.B));
  436. if (frame != Colors.Transparent)
  437. 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));
  438. return result;
  439. }
  440. public static Color MixColors(this Color color1, double factor, Color color2)
  441. {
  442. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  443. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  444. if (factor == 0) return color2;
  445. if (factor == 1) return color1;
  446. var factor1 = 1 - factor;
  447. return Color.FromArgb(
  448. (byte)(color1.A * factor + color2.A * factor1),
  449. (byte)(color1.R * factor + color2.R * factor1),
  450. (byte)(color1.G * factor + color2.G * factor1),
  451. (byte)(color1.B * factor + color2.B * factor1));
  452. }
  453. public static System.Windows.Media.Color MixColors(this System.Windows.Media.Color color1, double factor, System.Windows.Media.Color color2)
  454. {
  455. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  456. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  457. if (factor == 0) return color2;
  458. if (factor == 1) return color1;
  459. var factor1 = 1 - factor;
  460. return System.Windows.Media.Color.FromArgb(
  461. (byte)(color1.A * factor + color2.A * factor1),
  462. (byte)(color1.R * factor + color2.R * factor1),
  463. (byte)(color1.G * factor + color2.G * factor1),
  464. (byte)(color1.B * factor + color2.B * factor1));
  465. }
  466. public static string ColorToString(Color color)
  467. {
  468. return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",
  469. color.A,
  470. color.R,
  471. color.G,
  472. color.B
  473. );
  474. }
  475. public static Color StringToColor(string colorcode)
  476. {
  477. var col = Color.Transparent;
  478. if (!string.IsNullOrEmpty(colorcode))
  479. {
  480. var code = colorcode.Replace("#", "");
  481. if (code.Length == 6)
  482. col = Color.FromArgb(255,
  483. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  484. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  485. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  486. else if (code.Length == 8)
  487. col = Color.FromArgb(
  488. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  489. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  490. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  491. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  492. }
  493. return col;
  494. }
  495. public static System.Windows.Media.Color StringToMediaColor(string colorcode)
  496. {
  497. var col = Colors.Transparent;
  498. if (!string.IsNullOrEmpty(colorcode))
  499. {
  500. var code = colorcode.Replace("#", "");
  501. if (code.Length == 6)
  502. col = System.Windows.Media.Color.FromArgb(255,
  503. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  504. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  505. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  506. else if (code.Length == 8)
  507. col = System.Windows.Media.Color.FromArgb(
  508. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  509. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  510. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  511. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  512. }
  513. return col;
  514. }
  515. /// <summary>
  516. /// Creates color with corrected brightness.
  517. /// </summary>
  518. /// <param name="color">Color to correct.</param>
  519. /// <param name="correctionFactor">
  520. /// The brightness correction factor. Must be between -1 and 1.
  521. /// Negative values produce darker colors.
  522. /// </param>
  523. /// <returns>
  524. /// Corrected <see cref="Color" /> structure.
  525. /// </returns>
  526. public static System.Windows.Media.Color AdjustBrightness(this System.Windows.Media.Color color, float correctionFactor)
  527. {
  528. float red = color.R;
  529. float green = color.G;
  530. float blue = color.B;
  531. if (correctionFactor < 0)
  532. {
  533. correctionFactor = 1 + correctionFactor;
  534. red *= correctionFactor;
  535. green *= correctionFactor;
  536. blue *= correctionFactor;
  537. }
  538. else
  539. {
  540. red = (255 - red) * correctionFactor + red;
  541. green = (255 - green) * correctionFactor + green;
  542. blue = (255 - blue) * correctionFactor + blue;
  543. }
  544. return System.Windows.Media.Color.FromArgb(color.A, (byte)red, (byte)green, (byte)blue);
  545. }
  546. public static bool TryGetImageType(byte[] imageData, [NotNullWhen(true)] out ImageFormat? format)
  547. {
  548. foreach (var signatureEntry in SignatureTable)
  549. foreach (var signature in signatureEntry.Value)
  550. {
  551. var isMatch = true;
  552. for (var i = 0; i < signature.Length; i++)
  553. {
  554. var signatureByte = signature[i];
  555. // ToString("X") gets the hex representation and pads it to always be length 2
  556. var imageByte = imageData[i]
  557. .ToString("X2");
  558. if (signatureByte == imageByte)
  559. continue;
  560. isMatch = false;
  561. break;
  562. }
  563. if (isMatch)
  564. {
  565. format = signatureEntry.Key;
  566. return true;
  567. }
  568. }
  569. format = null;
  570. return false;
  571. }
  572. /// <summary>
  573. /// Takes a byte array and determines the image file type by
  574. /// comparing the first few bytes of the file to a list of known
  575. /// image file signatures.
  576. /// </summary>
  577. /// <param name="imageData">Byte array of the image data</param>
  578. /// <returns>ImageFormat corresponding to the image file format</returns>
  579. /// <exception cref="ArgumentException">Thrown if the image type can't be determined</exception>
  580. public static ImageFormat GetImageType(byte[] imageData)
  581. {
  582. if(TryGetImageType(imageData, out var format))
  583. {
  584. return format;
  585. }
  586. throw new ArgumentException("The byte array did not match any known image file signatures.");
  587. }
  588. public static System.Drawing.Bitmap Invert(this System.Drawing.Bitmap source)
  589. {
  590. Bitmap bmpDest = new Bitmap(source.Width,source.Height);
  591. ColorMatrix clrMatrix = new ColorMatrix(new float[][]
  592. {
  593. new float[] {-1, 0, 0, 0, 0},
  594. new float[] {0, -1, 0, 0, 0},
  595. new float[] {0, 0, -1, 0, 0},
  596. new float[] {0, 0, 0, 1, 0},
  597. new float[] {1, 1, 1, 0, 1}
  598. });
  599. using (ImageAttributes attrImage = new ImageAttributes())
  600. {
  601. attrImage.SetColorMatrix(clrMatrix);
  602. using (Graphics g = Graphics.FromImage(bmpDest))
  603. {
  604. g.DrawImage(source, new Rectangle(0, 0,
  605. source.Width, source.Height), 0, 0,
  606. source.Width, source.Height, GraphicsUnit.Pixel,
  607. attrImage);
  608. }
  609. }
  610. return bmpDest;
  611. }
  612. public static Font AdjustSize(this Font font, Graphics graphics, string text, int width)
  613. {
  614. Font result = null;
  615. for (int size = (int)font.Size; size > 0; size--)
  616. {
  617. result = new Font(font.Name, size, font.Style);
  618. SizeF adjustedSizeNew = graphics.MeasureString(text, result);
  619. if (width > Convert.ToInt32(adjustedSizeNew.Width))
  620. return result;
  621. }
  622. return result;
  623. }
  624. public static Bitmap WatermarkImage(this Bitmap image, String text, System.Windows.Media.Color color, int maxfontsize = 0)
  625. {
  626. return image.WatermarkImage(text, Color.FromArgb(color.A, color.R, color.G, color.B),maxfontsize);
  627. }
  628. public static Bitmap WatermarkImage(this Bitmap image, String text, Color color, int maxfontsize = 0)
  629. {
  630. int w = image.Width;
  631. int h = image.Height;
  632. Bitmap result = new System.Drawing.Bitmap(w, h);
  633. Graphics graphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)result);
  634. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  635. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  636. graphics.Clear(System.Drawing.Color.Transparent);
  637. graphics.DrawImage(image, 0, 0, w, h);
  638. Font drawFont = new System.Drawing.Font("Arial", 96).AdjustSize(graphics,text,(int)(image.Width * 0.9F));
  639. if ((maxfontsize > 0) && (drawFont.Size > maxfontsize))
  640. drawFont = new System.Drawing.Font("Arial", maxfontsize);
  641. SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
  642. StringFormat stringFormat = new StringFormat();
  643. stringFormat.Alignment = StringAlignment.Center;
  644. stringFormat.LineAlignment = StringAlignment.Center;
  645. graphics.DrawString(text, drawFont, drawBrush, new Rectangle(0,0,w,h), stringFormat);
  646. graphics.Dispose();
  647. return result;
  648. }
  649. private static System.Windows.Media.Color AdjustColor(System.Windows.Media.Color color, Action<HSL> action)
  650. {
  651. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R,color.G,color.B));
  652. action(hsl);
  653. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  654. return System.Windows.Media.Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
  655. }
  656. private static int AdjustPercentage(int original, int percentage)
  657. {
  658. int percent = Math.Min(100, Math.Max(-100, percentage));
  659. int newvalue = (percent < 0)
  660. ? (byte)((percent * original) / 100)
  661. : (byte)((percent * (100 - original)) / 100);
  662. return original + newvalue;
  663. }
  664. public static System.Windows.Media.Color AdjustHue(this System.Windows.Media.Color color, int degrees) =>
  665. AdjustColor(color, (hsl => hsl.H += degrees));
  666. public static System.Windows.Media.Color AdjustSaturation(this System.Windows.Media.Color color, int percentage) =>
  667. AdjustColor(color, (hsl =>
  668. {
  669. hsl.S = (byte)AdjustPercentage(hsl.S, percentage);
  670. }));
  671. public static System.Windows.Media.Color SetSaturation(this System.Windows.Media.Color color, int percentage) =>
  672. AdjustColor(color, (hsl => hsl.S = (byte)percentage));
  673. public static System.Windows.Media.Color AdjustLightness(this System.Windows.Media.Color color, int percentage) =>
  674. AdjustColor(color, (hsl =>
  675. {
  676. hsl.L = (byte)AdjustPercentage(hsl.L, percentage);
  677. }));
  678. public static System.Windows.Media.Color SetLightness(this System.Windows.Media.Color color, int percentage) =>
  679. AdjustColor(color, (hsl => hsl.L = (byte)percentage));
  680. public static System.Windows.Media.Color SetAlpha(this System.Windows.Media.Color color, byte alpha) =>
  681. System.Windows.Media.Color.FromArgb(alpha, color.R, color.G, color.B);
  682. public static HSL ToHSL(this System.Windows.Media.Color color)
  683. {
  684. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  685. }
  686. public static System.Windows.Media.Color ToColor(this HSL hsl)
  687. {
  688. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  689. return System.Windows.Media.Color.FromRgb(rgb.R, rgb.G, rgb.B);
  690. }
  691. public static HSL ToHSL(this System.Drawing.Color color)
  692. {
  693. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  694. }
  695. public static System.Windows.Media.Color GetForegroundColor(this System.Windows.Media.Color c, int threshold = 130)
  696. {
  697. var perceivedbrightness = (int)Math.Sqrt(
  698. c.R * c.R * .299 +
  699. c.G * c.G * .587 +
  700. c.B * c.B * .114);
  701. return perceivedbrightness >= threshold ? Colors.Black : Colors.White;
  702. }
  703. public static uint ToUint(this System.Drawing.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  704. public static uint ToUint(this System.Windows.Media.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  705. public enum ImageEncoding
  706. {
  707. JPEG
  708. }
  709. public static ImageCodecInfo? GetEncoder(ImageFormat format)
  710. {
  711. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  712. foreach (ImageCodecInfo codec in codecs)
  713. {
  714. if (codec.FormatID == format.Guid)
  715. {
  716. return codec;
  717. }
  718. }
  719. return null;
  720. }
  721. public static byte[] BitmapToPdf(Bitmap bitmap)
  722. {
  723. byte[]? _result = null;
  724. using (var _stream = new MemoryStream())
  725. {
  726. bitmap.Save(_stream, ImageFormat.Png);
  727. _result = BitmapToPdf(_stream);
  728. }
  729. return _result;
  730. }
  731. public static byte[] BitmapToPdf(byte[] bitmap)
  732. {
  733. byte[] _result = null;
  734. using (var _stream = new MemoryStream(bitmap))
  735. _result = BitmapToPdf(_stream);
  736. return _result;
  737. }
  738. public static byte[] BitmapToPdf(Stream stream)
  739. {
  740. byte[]? _result = null;
  741. PdfDocument _doc = new PdfDocument();
  742. PdfPage _page = _doc.Pages.Add();
  743. PdfGraphics _graphics = _page.Graphics;
  744. stream.Position = 0;
  745. PdfBitmap _image = new PdfBitmap(stream);
  746. _graphics.DrawImage(_image, 0, 0);
  747. using (var _out = new MemoryStream())
  748. {
  749. _doc.Save(_out);
  750. _out.Position = 0;
  751. _doc.Close(true);
  752. _result = _out.ToArray();
  753. }
  754. return _result;
  755. }
  756. public static bool IsPdf(byte[] data)
  757. {
  758. var pdfBytes = Encoding.ASCII.GetBytes("%PDF-");
  759. return data.Take(pdfBytes.Length).SequenceEqual(pdfBytes);
  760. }
  761. public static byte[] GetPDFThumbnail(byte[] pdfData, int width, int height)
  762. {
  763. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  764. Bitmap image = loadeddoc.ExportAsImage(0, new SizeF(width, height), true);
  765. MemoryStream stream = new MemoryStream();
  766. image.Save(stream, ImageFormat.Jpeg);
  767. return stream.ToArray();
  768. }
  769. public static byte[] PDFToBitmap(byte[] pdfData, int page)
  770. {
  771. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  772. Bitmap image = loadeddoc.ExportAsImage(page, new ImageExportSettings() { KeepAspectRatio = true });
  773. MemoryStream stream = new MemoryStream();
  774. image.Save(stream, ImageFormat.Jpeg);
  775. return stream.ToArray();
  776. }
  777. [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  778. public static extern bool DeleteObject(IntPtr hObject);
  779. public static List<ImageSource> RenderPDFToImageSources(byte[] pdfData, ImageEncoding encoding = ImageEncoding.JPEG)
  780. {
  781. using var profiler = new Profiler(true);
  782. var rendered = new List<ImageSource>();
  783. var loadeddoc = new PdfLoadedDocument(pdfData);
  784. loadeddoc.FlattenAnnotations();
  785. var images = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  786. if (images != null)
  787. foreach (var image in images)
  788. {
  789. var hBitmap = image.GetHbitmap();
  790. try
  791. {
  792. var source = (ImageSource)Imaging.CreateBitmapSourceFromHBitmap(
  793. hBitmap,
  794. IntPtr.Zero,
  795. Int32Rect.Empty,
  796. BitmapSizeOptions.FromEmptyOptions());
  797. source.Freeze();
  798. rendered.Add(source);
  799. }
  800. finally
  801. {
  802. DeleteObject(hBitmap);
  803. }
  804. }
  805. return rendered;
  806. }
  807. public static List<byte[]> RenderPDFToImageBytes(byte[] pdfData, ImageEncoding encoding = ImageEncoding.JPEG)
  808. {
  809. var rendered = new List<byte[]>();
  810. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  811. loadeddoc.FlattenAnnotations();
  812. Bitmap[] images = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  813. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  814. var quality = Encoder.Quality;
  815. var encodeParams = new EncoderParameters(1);
  816. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  817. if (images != null)
  818. foreach (var image in images)
  819. {
  820. using (var data = new MemoryStream())
  821. {
  822. image.Save(data, jpgEncoder, encodeParams);
  823. rendered.Add(data.ToArray());
  824. }
  825. }
  826. return rendered;
  827. }
  828. public static List<byte[]> RenderTextFileToImages(string textData)
  829. {
  830. var pdfDocument = new PdfDocument();
  831. var page = pdfDocument.Pages.Add();
  832. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  833. var textElement = new PdfTextElement(textData, font);
  834. var layoutFormat = new PdfLayoutFormat
  835. {
  836. Layout = PdfLayoutType.Paginate,
  837. Break = PdfLayoutBreakType.FitPage
  838. };
  839. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  840. using var docStream = new MemoryStream();
  841. pdfDocument.Save(docStream);
  842. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  843. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  844. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  845. var quality = Encoder.Quality;
  846. var encodeParams = new EncoderParameters(1);
  847. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  848. var images = new List<byte[]>();
  849. if (bmpImages != null)
  850. foreach (var image in bmpImages)
  851. {
  852. using var data = new MemoryStream();
  853. image.Save(data, jpgEncoder, encodeParams);
  854. images.Add(data.ToArray());
  855. }
  856. return images;
  857. }
  858. public static ContentControl CreatePreviewWindowButtonContent(string caption, Bitmap bitmap)
  859. {
  860. Frame frame = new Frame();
  861. frame.Padding = new Thickness(0);
  862. frame.Margin = new Thickness(10, 10, 10, 5);
  863. Grid grid = new Grid();
  864. grid.Margin = new Thickness(0);
  865. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  866. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  867. var img = new System.Windows.Controls.Image
  868. {
  869. Source = bitmap.AsBitmapImage(),
  870. Height = 32.0F,
  871. Width = 32.0F,
  872. Margin = new Thickness(10)
  873. };
  874. img.SetValue(Grid.RowProperty, 0);
  875. img.Margin = new Thickness(0);
  876. grid.Children.Add(img);
  877. var txt = new System.Windows.Controls.TextBox();
  878. txt.IsEnabled = false;
  879. txt.Text = caption;
  880. txt.BorderThickness = new Thickness(0);
  881. txt.TextWrapping = TextWrapping.WrapWithOverflow;
  882. txt.MaxWidth = 90;
  883. txt.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
  884. txt.SetValue(Grid.RowProperty, 1);
  885. grid.Children.Add(txt);
  886. frame.Content = grid;
  887. return frame;
  888. }
  889. public static String AsExtension(this ImageFormat format)
  890. {
  891. if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp))
  892. return "bmp";
  893. if (format.Equals(ImageFormat.Emf))
  894. return "emf";
  895. if (format.Equals(ImageFormat.Wmf))
  896. return "wmf";
  897. if (format.Equals(ImageFormat.Gif))
  898. return "gif";
  899. if (format.Equals(ImageFormat.Jpeg))
  900. return "jpeg";
  901. if (format.Equals(ImageFormat.Png))
  902. return "png";
  903. if (format.Equals(ImageFormat.Tiff))
  904. return "tiff";
  905. if (format.Equals(ImageFormat.Exif))
  906. return "exif";
  907. if (format.Equals(ImageFormat.Icon))
  908. return "ico";
  909. return "";
  910. }
  911. public static bool IsEqual(this BitmapImage? image1, BitmapImage? image2)
  912. {
  913. if (image1 == null || image2 == null)
  914. return false;
  915. return image1.ToBytes().SequenceEqual(image2.ToBytes());
  916. }
  917. public static byte[] ToBytes(this BitmapImage image)
  918. {
  919. byte[] data = new byte[] { };
  920. if (image != null)
  921. {
  922. try
  923. {
  924. var encoder = new BmpBitmapEncoder();
  925. encoder.Frames.Add(BitmapFrame.Create(image));
  926. using (MemoryStream ms = new MemoryStream())
  927. {
  928. encoder.Save(ms);
  929. data = ms.ToArray();
  930. }
  931. return data;
  932. }
  933. catch (Exception ex)
  934. {
  935. }
  936. }
  937. return data;
  938. }
  939. }
  940. }