ImageUtils.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. return;
  341. using (var mem = new MemoryStream(imageData))
  342. {
  343. mem.Position = 0;
  344. image.BeginInit();
  345. image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
  346. image.CacheOption = BitmapCacheOption.OnLoad;
  347. image.UriSource = null;
  348. image.StreamSource = mem;
  349. image.EndInit();
  350. }
  351. image.Freeze();
  352. }
  353. public static Bitmap? MergeBitmaps(IEnumerable<Bitmap> bitmaps, int padding)
  354. {
  355. if (!bitmaps.Any())
  356. return null;
  357. var totalwidth = bitmaps.Aggregate(0, (total, next) => total + next.Width + (total > 0 ? padding : 0) );
  358. var maxheight = bitmaps.Aggregate(0, (max, next) => Math.Max(next.Height,max) );
  359. Bitmap result = new Bitmap(totalwidth, maxheight);
  360. using (Graphics g = Graphics.FromImage(result))
  361. {
  362. g.Clear(Color.Transparent);
  363. int left = 0;
  364. foreach (var bitmap in bitmaps)
  365. {
  366. g.DrawImage(bitmap, left, 0);
  367. left += bitmap.Width + padding;
  368. }
  369. }
  370. return result;
  371. }
  372. public static byte[] ToArray<T>(this BitmapImage image) where T : BitmapEncoder, new()
  373. {
  374. byte[] data;
  375. var encoder = new T();
  376. encoder.Frames.Add(BitmapFrame.Create(image));
  377. using (var ms = new MemoryStream())
  378. {
  379. encoder.Save(ms);
  380. data = ms.ToArray();
  381. }
  382. return data;
  383. }
  384. public static BitmapImage Resize(this BitmapImage image, int height, int width)
  385. {
  386. var buffer = image.ToArray<BmpBitmapEncoder>();
  387. var ms = new MemoryStream(buffer);
  388. var result = new BitmapImage();
  389. result.BeginInit();
  390. result.CacheOption = BitmapCacheOption.None;
  391. result.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  392. result.DecodePixelWidth = width;
  393. result.DecodePixelHeight = height;
  394. result.StreamSource = ms;
  395. result.Rotation = Rotation.Rotate0;
  396. result.EndInit();
  397. buffer = null;
  398. return result;
  399. }
  400. public static Bitmap Resize(this Bitmap bitmap, int width, int height)
  401. {
  402. if ((width == bitmap.Width) && (height == bitmap.Height))
  403. return bitmap;
  404. return new Bitmap(bitmap,new Size(width,height));
  405. }
  406. public static BitmapImage Scale(this BitmapImage image, int maxheight, int maxwidth)
  407. {
  408. var scaleHeight = maxheight / (float)image.Height;
  409. var scaleWidth = maxwidth / (float)image.Width;
  410. var scale = Math.Min(scaleHeight, scaleWidth);
  411. return image.Resize((int)(image.Height * scale), (int)(image.Width * scale));
  412. }
  413. public static Bitmap BitmapFromColor(Color color, int width, int height, Color frame)
  414. {
  415. var result = new Bitmap(width, height);
  416. var g = Graphics.FromImage(result);
  417. g.Clear(color);
  418. if (frame != Color.Transparent)
  419. g.DrawRectangle(new Pen(new SolidBrush(frame), 1), new Rectangle(0, 0, width-1, height-1));
  420. return result;
  421. }
  422. public static Bitmap BitmapFromColor(System.Windows.Media.Color color, int width, int height, System.Windows.Media.Color frame)
  423. {
  424. var result = new Bitmap(width, height);
  425. var g = Graphics.FromImage(result);
  426. g.Clear(Color.FromArgb(color.A,color.R,color.G,color.B));
  427. if (frame != Colors.Transparent)
  428. 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));
  429. return result;
  430. }
  431. public static Color MixColors(this Color color1, double factor, Color color2)
  432. {
  433. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  434. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  435. if (factor == 0) return color2;
  436. if (factor == 1) return color1;
  437. var factor1 = 1 - factor;
  438. return Color.FromArgb(
  439. (byte)(color1.A * factor + color2.A * factor1),
  440. (byte)(color1.R * factor + color2.R * factor1),
  441. (byte)(color1.G * factor + color2.G * factor1),
  442. (byte)(color1.B * factor + color2.B * factor1));
  443. }
  444. public static System.Windows.Media.Color MixColors(this System.Windows.Media.Color color1, double factor, System.Windows.Media.Color color2)
  445. {
  446. if (factor < 0) throw new Exception($"Factor {factor} must be >= 0.");
  447. if (factor > 1) throw new Exception($"Factor {factor} must be <= 1.");
  448. if (factor == 0) return color2;
  449. if (factor == 1) return color1;
  450. var factor1 = 1 - factor;
  451. return System.Windows.Media.Color.FromArgb(
  452. (byte)(color1.A * factor + color2.A * factor1),
  453. (byte)(color1.R * factor + color2.R * factor1),
  454. (byte)(color1.G * factor + color2.G * factor1),
  455. (byte)(color1.B * factor + color2.B * factor1));
  456. }
  457. public static string ColorToString(Color color)
  458. {
  459. return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",
  460. color.A,
  461. color.R,
  462. color.G,
  463. color.B
  464. );
  465. }
  466. public static Color StringToColor(string colorcode)
  467. {
  468. var col = Color.Transparent;
  469. if (!string.IsNullOrEmpty(colorcode))
  470. {
  471. var code = colorcode.Replace("#", "");
  472. if (code.Length == 6)
  473. col = Color.FromArgb(255,
  474. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  475. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  476. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  477. else if (code.Length == 8)
  478. col = Color.FromArgb(
  479. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  480. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  481. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  482. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  483. }
  484. return col;
  485. }
  486. public static System.Windows.Media.Color StringToMediaColor(string colorcode)
  487. {
  488. var col = Colors.Transparent;
  489. if (!string.IsNullOrEmpty(colorcode))
  490. {
  491. var code = colorcode.Replace("#", "");
  492. if (code.Length == 6)
  493. col = System.Windows.Media.Color.FromArgb(255,
  494. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  495. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  496. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber));
  497. else if (code.Length == 8)
  498. col = System.Windows.Media.Color.FromArgb(
  499. byte.Parse(code.Substring(0, 2), NumberStyles.HexNumber),
  500. byte.Parse(code.Substring(2, 2), NumberStyles.HexNumber),
  501. byte.Parse(code.Substring(4, 2), NumberStyles.HexNumber),
  502. byte.Parse(code.Substring(6, 2), NumberStyles.HexNumber));
  503. }
  504. return col;
  505. }
  506. /// <summary>
  507. /// Creates color with corrected brightness.
  508. /// </summary>
  509. /// <param name="color">Color to correct.</param>
  510. /// <param name="correctionFactor">
  511. /// The brightness correction factor. Must be between -1 and 1.
  512. /// Negative values produce darker colors.
  513. /// </param>
  514. /// <returns>
  515. /// Corrected <see cref="Color" /> structure.
  516. /// </returns>
  517. public static System.Windows.Media.Color AdjustBrightness(this System.Windows.Media.Color color, float correctionFactor)
  518. {
  519. float red = color.R;
  520. float green = color.G;
  521. float blue = color.B;
  522. if (correctionFactor < 0)
  523. {
  524. correctionFactor = 1 + correctionFactor;
  525. red *= correctionFactor;
  526. green *= correctionFactor;
  527. blue *= correctionFactor;
  528. }
  529. else
  530. {
  531. red = (255 - red) * correctionFactor + red;
  532. green = (255 - green) * correctionFactor + green;
  533. blue = (255 - blue) * correctionFactor + blue;
  534. }
  535. return System.Windows.Media.Color.FromArgb(color.A, (byte)red, (byte)green, (byte)blue);
  536. }
  537. /// <summary>
  538. /// Takes a byte array and determines the image file type by
  539. /// comparing the first few bytes of the file to a list of known
  540. /// image file signatures.
  541. /// </summary>
  542. /// <param name="imageData">Byte array of the image data</param>
  543. /// <returns>ImageFormat corresponding to the image file format</returns>
  544. /// <exception cref="ArgumentException">Thrown if the image type can't be determined</exception>
  545. public static ImageFormat GetImageType(byte[] imageData)
  546. {
  547. foreach (var signatureEntry in SignatureTable)
  548. foreach (var signature in signatureEntry.Value)
  549. {
  550. var isMatch = true;
  551. for (var i = 0; i < signature.Length; i++)
  552. {
  553. var signatureByte = signature[i];
  554. // ToString("X") gets the hex representation and pads it to always be length 2
  555. var imageByte = imageData[i]
  556. .ToString("X2");
  557. if (signatureByte == imageByte)
  558. continue;
  559. isMatch = false;
  560. break;
  561. }
  562. if (isMatch) return signatureEntry.Key;
  563. }
  564. throw new ArgumentException("The byte array did not match any known image file signatures.");
  565. }
  566. public static System.Drawing.Bitmap Invert(this System.Drawing.Bitmap source)
  567. {
  568. Bitmap bmpDest = new Bitmap(source.Width,source.Height);
  569. ColorMatrix clrMatrix = new ColorMatrix(new float[][]
  570. {
  571. new float[] {-1, 0, 0, 0, 0},
  572. new float[] {0, -1, 0, 0, 0},
  573. new float[] {0, 0, -1, 0, 0},
  574. new float[] {0, 0, 0, 1, 0},
  575. new float[] {1, 1, 1, 0, 1}
  576. });
  577. using (ImageAttributes attrImage = new ImageAttributes())
  578. {
  579. attrImage.SetColorMatrix(clrMatrix);
  580. using (Graphics g = Graphics.FromImage(bmpDest))
  581. {
  582. g.DrawImage(source, new Rectangle(0, 0,
  583. source.Width, source.Height), 0, 0,
  584. source.Width, source.Height, GraphicsUnit.Pixel,
  585. attrImage);
  586. }
  587. }
  588. return bmpDest;
  589. }
  590. public static Font AdjustSize(this Font font, Graphics graphics, string text, int width)
  591. {
  592. Font result = null;
  593. for (int size = (int)font.Size; size > 0; size--)
  594. {
  595. result = new Font(font.Name, size, font.Style);
  596. SizeF adjustedSizeNew = graphics.MeasureString(text, result);
  597. if (width > Convert.ToInt32(adjustedSizeNew.Width))
  598. return result;
  599. }
  600. return result;
  601. }
  602. public static Bitmap WatermarkImage(this Bitmap image, String text, System.Windows.Media.Color color, int maxfontsize = 0)
  603. {
  604. return image.WatermarkImage(text, Color.FromArgb(color.A, color.R, color.G, color.B),maxfontsize);
  605. }
  606. public static Bitmap WatermarkImage(this Bitmap image, String text, Color color, int maxfontsize = 0)
  607. {
  608. int w = image.Width;
  609. int h = image.Height;
  610. Bitmap result = new System.Drawing.Bitmap(w, h);
  611. Graphics graphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)result);
  612. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  613. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  614. graphics.Clear(System.Drawing.Color.Transparent);
  615. graphics.DrawImage(image, 0, 0, w, h);
  616. Font drawFont = new System.Drawing.Font("Arial", 96).AdjustSize(graphics,text,(int)(image.Width * 0.9F));
  617. if ((maxfontsize > 0) && (drawFont.Size > maxfontsize))
  618. drawFont = new System.Drawing.Font("Arial", maxfontsize);
  619. SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
  620. StringFormat stringFormat = new StringFormat();
  621. stringFormat.Alignment = StringAlignment.Center;
  622. stringFormat.LineAlignment = StringAlignment.Center;
  623. graphics.DrawString(text, drawFont, drawBrush, new Rectangle(0,0,w,h), stringFormat);
  624. graphics.Dispose();
  625. return result;
  626. }
  627. private static System.Windows.Media.Color AdjustColor(System.Windows.Media.Color color, Action<HSL> action)
  628. {
  629. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R,color.G,color.B));
  630. action(hsl);
  631. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  632. return System.Windows.Media.Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
  633. }
  634. private static int AdjustPercentage(int original, int percentage)
  635. {
  636. int percent = Math.Min(100, Math.Max(-100, percentage));
  637. int newvalue = (percent < 0)
  638. ? (byte)((percent * original) / 100)
  639. : (byte)((percent * (100 - original)) / 100);
  640. return original + newvalue;
  641. }
  642. public static System.Windows.Media.Color AdjustHue(this System.Windows.Media.Color color, int degrees) =>
  643. AdjustColor(color, (hsl => hsl.H += degrees));
  644. public static System.Windows.Media.Color AdjustSaturation(this System.Windows.Media.Color color, int percentage) =>
  645. AdjustColor(color, (hsl =>
  646. {
  647. hsl.S = (byte)AdjustPercentage(hsl.S, percentage);
  648. }));
  649. public static System.Windows.Media.Color SetSaturation(this System.Windows.Media.Color color, int percentage) =>
  650. AdjustColor(color, (hsl => hsl.S = (byte)percentage));
  651. public static System.Windows.Media.Color AdjustLightness(this System.Windows.Media.Color color, int percentage) =>
  652. AdjustColor(color, (hsl =>
  653. {
  654. hsl.L = (byte)AdjustPercentage(hsl.L, percentage);
  655. }));
  656. public static System.Windows.Media.Color SetLightness(this System.Windows.Media.Color color, int percentage) =>
  657. AdjustColor(color, (hsl => hsl.L = (byte)percentage));
  658. public static System.Windows.Media.Color SetAlpha(this System.Windows.Media.Color color, byte alpha) =>
  659. System.Windows.Media.Color.FromArgb(alpha, color.R, color.G, color.B);
  660. public static HSL ToHSL(this System.Windows.Media.Color color)
  661. {
  662. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  663. }
  664. public static System.Windows.Media.Color ToColor(this HSL hsl)
  665. {
  666. var rgb = ColorHelper.ColorConverter.HslToRgb(hsl);
  667. return System.Windows.Media.Color.FromRgb(rgb.R, rgb.G, rgb.B);
  668. }
  669. public static HSL ToHSL(this System.Drawing.Color color)
  670. {
  671. return ColorHelper.ColorConverter.RgbToHsl(new RGB(color.R, color.G, color.B));
  672. }
  673. public static System.Windows.Media.Color GetForegroundColor(this System.Windows.Media.Color c, int threshold = 130)
  674. {
  675. var perceivedbrightness = (int)Math.Sqrt(
  676. c.R * c.R * .299 +
  677. c.G * c.G * .587 +
  678. c.B * c.B * .114);
  679. return perceivedbrightness >= threshold ? Colors.Black : Colors.White;
  680. }
  681. public static uint ToUint(this System.Drawing.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  682. public static uint ToUint(this System.Windows.Media.Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
  683. public enum ImageEncoding
  684. {
  685. JPEG
  686. }
  687. public static ImageCodecInfo? GetEncoder(ImageFormat format)
  688. {
  689. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  690. foreach (ImageCodecInfo codec in codecs)
  691. {
  692. if (codec.FormatID == format.Guid)
  693. {
  694. return codec;
  695. }
  696. }
  697. return null;
  698. }
  699. public static byte[] GetPDFThumbnail(byte[] pdfData, int width, int height)
  700. {
  701. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  702. Bitmap image = loadeddoc.ExportAsImage(0, new SizeF(width, height), true);
  703. MemoryStream stream = new MemoryStream();
  704. image.Save(stream, ImageFormat.Jpeg);
  705. return stream.ToArray();
  706. }
  707. public static List<byte[]> RenderPDFToImages(byte[] pdfData, ImageEncoding encoding = ImageEncoding.JPEG)
  708. {
  709. var rendered = new List<byte[]>();
  710. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(pdfData);
  711. loadeddoc.FlattenAnnotations();
  712. Bitmap[] images = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  713. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  714. var quality = Encoder.Quality;
  715. var encodeParams = new EncoderParameters(1);
  716. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  717. if (images != null)
  718. foreach (var image in images)
  719. {
  720. using (var data = new MemoryStream())
  721. {
  722. image.Save(data, jpgEncoder, encodeParams);
  723. rendered.Add(data.ToArray());
  724. }
  725. }
  726. return rendered;
  727. }
  728. public static List<byte[]> RenderTextFileToImages(string textData)
  729. {
  730. var pdfDocument = new PdfDocument();
  731. var page = pdfDocument.Pages.Add();
  732. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  733. var textElement = new PdfTextElement(textData, font);
  734. var layoutFormat = new PdfLayoutFormat
  735. {
  736. Layout = PdfLayoutType.Paginate,
  737. Break = PdfLayoutBreakType.FitPage
  738. };
  739. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  740. using var docStream = new MemoryStream();
  741. pdfDocument.Save(docStream);
  742. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  743. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  744. var jpgEncoder = GetEncoder(ImageFormat.Jpeg)!;
  745. var quality = Encoder.Quality;
  746. var encodeParams = new EncoderParameters(1);
  747. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  748. var images = new List<byte[]>();
  749. if (bmpImages != null)
  750. foreach (var image in bmpImages)
  751. {
  752. using var data = new MemoryStream();
  753. image.Save(data, jpgEncoder, encodeParams);
  754. images.Add(data.ToArray());
  755. }
  756. return images;
  757. }
  758. public static ContentControl CreatePreviewWindowButtonContent(string caption, Bitmap bitmap)
  759. {
  760. Frame frame = new Frame();
  761. frame.Padding = new Thickness(0);
  762. frame.Margin = new Thickness(10, 10, 10, 5);
  763. Grid grid = new Grid();
  764. grid.Margin = new Thickness(0);
  765. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  766. grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  767. var img = new System.Windows.Controls.Image
  768. {
  769. Source = bitmap.AsBitmapImage(),
  770. Height = 32.0F,
  771. Width = 32.0F,
  772. Margin = new Thickness(10)
  773. };
  774. img.SetValue(Grid.RowProperty, 0);
  775. img.Margin = new Thickness(0);
  776. grid.Children.Add(img);
  777. var txt = new System.Windows.Controls.TextBox();
  778. txt.IsEnabled = false;
  779. txt.Text = caption;
  780. txt.BorderThickness = new Thickness(0);
  781. txt.TextWrapping = TextWrapping.WrapWithOverflow;
  782. txt.MaxWidth = 90;
  783. txt.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
  784. txt.SetValue(Grid.RowProperty, 1);
  785. grid.Children.Add(txt);
  786. frame.Content = grid;
  787. return frame;
  788. }
  789. public static String AsExtension(this ImageFormat format)
  790. {
  791. if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp))
  792. return "bmp";
  793. if (format.Equals(ImageFormat.Emf))
  794. return "emf";
  795. if (format.Equals(ImageFormat.Wmf))
  796. return "wmf";
  797. if (format.Equals(ImageFormat.Gif))
  798. return "gif";
  799. if (format.Equals(ImageFormat.Jpeg))
  800. return "jpeg";
  801. if (format.Equals(ImageFormat.Png))
  802. return "png";
  803. if (format.Equals(ImageFormat.Tiff))
  804. return "tiff";
  805. if (format.Equals(ImageFormat.Exif))
  806. return "exif";
  807. if (format.Equals(ImageFormat.Icon))
  808. return "ico";
  809. return "";
  810. }
  811. }
  812. }