ImageUtils.cs 39 KB

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