ImageUtils.cs 42 KB

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