Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Windows;
  4. using System.Windows.Media.Imaging;
  5. using Catel.MVVM;
  6.  
  7. namespace ConvolutionWpf.Commands
  8. {
  9. public class BlurCommand : Command
  10. {
  11. private readonly Func<WriteableBitmap> _imageFactory;
  12.  
  13. public BlurCommand(Func<WriteableBitmap> imageFactory)
  14. : base(() => { })
  15. {
  16. _imageFactory = imageFactory;
  17. }
  18.  
  19. public void ExecuteCommand()
  20. {
  21. var image = _imageFactory();
  22. if (image == null)
  23. return;
  24.  
  25. var pixels = new byte[image.PixelHeight * image.BackBufferStride];
  26. image.CopyPixels(pixels, image.BackBufferStride, 0);
  27.  
  28. var resultPixels = new byte[image.PixelHeight * image.BackBufferStride];
  29.  
  30. double[] kernel = { 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0 };
  31.  
  32. var blurPixels = new byte[resultPixels.Length / kernel.Length];
  33.  
  34. for (int i = 0; i < image.PixelWidth - 1; ++i)
  35. {
  36. for (int j = 0; j < image.PixelHeight - 1; ++j)
  37. {
  38. int index = j * image.BackBufferStride + 4 * i;
  39.  
  40. for (int c = 0; c < 4; ++c)
  41. {
  42. resultPixels[index + c] = pixels[index + c];
  43. }
  44. }
  45. }
  46. for (int i = 0; i < resultPixels.Length; i += 9)
  47. {
  48. double[] sum = new double[kernel.Length];
  49. for (int c = 0; c < kernel.Length; c++)
  50. {
  51. sum[c] = resultPixels[i + c] * kernel[c];
  52. }
  53. var result = sum.Sum();
  54. var index = 0;
  55. for (; index < blurPixels.Length; index++)
  56. {
  57. blurPixels[index] = (byte)result;
  58. }
  59. }
  60.  
  61. image.WritePixels(new Int32Rect(0, 0, image.PixelWidth, image.PixelHeight), blurPixels, image.BackBufferStride, 0);
  62. }
  63.  
  64.  
  65. protected override void Execute(object parameter, bool ignoreCanExecuteCheck)
  66. {
  67. ExecuteCommand();
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement