ImageUtils.cs 36 KB

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