ImageUtils.cs 36 KB

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