BitmapUtils.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections.Generic;
  2. using System.Windows.Media;
  3. using System.Windows.Media.Imaging;
  4. using PixiEditor.Models.Layers;
  5. using PixiEditor.Models.Position;
  6. namespace PixiEditor.Models.ImageManipulation
  7. {
  8. public static class BitmapUtils
  9. {
  10. /// <summary>
  11. /// Converts pixel bytes to WriteableBitmap
  12. /// </summary>
  13. /// <param name="currentBitmapWidth">Width of bitmap</param>
  14. /// <param name="currentBitmapHeight">Height of bitmap</param>
  15. /// <param name="byteArray">Bitmap byte array</param>
  16. /// <returns>WriteableBitmap</returns>
  17. public static WriteableBitmap BytesToWriteableBitmap(int currentBitmapWidth, int currentBitmapHeight,
  18. byte[] byteArray)
  19. {
  20. WriteableBitmap bitmap = BitmapFactory.New(currentBitmapWidth, currentBitmapHeight);
  21. bitmap.FromByteArray(byteArray);
  22. return bitmap;
  23. }
  24. /// <summary>
  25. /// Converts layers bitmaps into one bitmap.
  26. /// </summary>
  27. /// <param name="layers">Layers to combine</param>
  28. /// <param name="width">Width of final bitmap</param>
  29. /// <param name="height">Height of final bitmap</param>
  30. /// <returns>WriteableBitmap of layered bitmaps</returns>
  31. public static WriteableBitmap CombineLayers(Layer[] layers, int width, int height)
  32. {
  33. WriteableBitmap finalBitmap = BitmapFactory.New(width, height);
  34. using (finalBitmap.GetBitmapContext())
  35. {
  36. for (int i = 0; i < layers.Length; i++)
  37. {
  38. for (int y = 0; y < finalBitmap.Height; y++)
  39. {
  40. for (int x = 0; x < finalBitmap.Width; x++)
  41. {
  42. Color color = layers[i].GetPixelWithOffset(x, y);
  43. color = Color.FromArgb((byte)(color.A * layers[i].Opacity), color.R, color.G, color.B);
  44. if (color.A != 0 || color.R != 0 || color.B != 0 || color.G != 0)
  45. {
  46. finalBitmap.SetPixel(x, y, color);
  47. }
  48. }
  49. }
  50. }
  51. }
  52. return finalBitmap;
  53. }
  54. public static Dictionary<Layer, Color[]> GetPixelsForSelection(Layer[] layers, Coordinates[] selection)
  55. {
  56. Dictionary<Layer, Color[]> result = new Dictionary<Layer, Color[]>();
  57. for (int i = 0; i < layers.Length; i++)
  58. {
  59. Color[] pixels = new Color[selection.Length];
  60. using (layers[i].LayerBitmap.GetBitmapContext())
  61. {
  62. for (int j = 0; j < pixels.Length; j++)
  63. {
  64. Coordinates position = layers[i].GetRelativePosition(selection[j]);
  65. if (position.X < 0 || position.X > layers[i].Width - 1 || position.Y < 0 ||
  66. position.Y > layers[i].Height - 1)
  67. {
  68. continue;
  69. }
  70. pixels[j] = layers[i].GetPixel(position.X, position.Y);
  71. }
  72. }
  73. result[layers[i]] = pixels;
  74. }
  75. return result;
  76. }
  77. }
  78. }