UIImage+Blurring.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // UIImage+Blurring.m
  3. // NYXImagesKit
  4. //
  5. // Created by @Nyx0uf on 03/06/11.
  6. // Copyright 2012 Nyx0uf. All rights reserved.
  7. // www.cocoaintheshell.com
  8. //
  9. #import "UIImage+Blurring.h"
  10. #import <Accelerate/Accelerate.h>
  11. static int16_t __s_gaussianblur_kernel_5x5[25] = {
  12. 1, 4, 6, 4, 1,
  13. 4, 16, 24, 16, 4,
  14. 6, 24, 36, 24, 6,
  15. 4, 16, 24, 16, 4,
  16. 1, 4, 6, 4, 1
  17. };
  18. @implementation UIImage (NYX_Blurring)
  19. -(UIImage*)gaussianBlurWithBias:(NSInteger)bias
  20. {
  21. /// Create an ARGB bitmap context
  22. const size_t width = (size_t)self.size.width;
  23. const size_t height = (size_t)self.size.height;
  24. const size_t bytesPerRow = width * kNyxNumberOfComponentsPerARBGPixel;
  25. CGContextRef bmContext = NYXCreateARGBBitmapContext(width, height, bytesPerRow);
  26. if (!bmContext)
  27. return nil;
  28. /// Draw the image in the bitmap context
  29. CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, self.CGImage);
  30. /// Grab the image raw data
  31. UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);
  32. if (!data)
  33. {
  34. CGContextRelease(bmContext);
  35. return nil;
  36. }
  37. const size_t n = sizeof(UInt8) * width * height * 4;
  38. void* outt = malloc(n);
  39. vImage_Buffer src = {data, height, width, bytesPerRow};
  40. vImage_Buffer dest = {outt, height, width, bytesPerRow};
  41. vImageConvolveWithBias_ARGB8888(&src, &dest, NULL, 0, 0, __s_gaussianblur_kernel_5x5, 5, 5, 256/*divisor*/, (int)bias, NULL, kvImageCopyInPlace);
  42. memcpy(data, outt, n);
  43. free(outt);
  44. CGImageRef blurredImageRef = CGBitmapContextCreateImage(bmContext);
  45. UIImage* blurred = [UIImage imageWithCGImage:blurredImageRef];
  46. /// Cleanup
  47. CGImageRelease(blurredImageRef);
  48. CGContextRelease(bmContext);
  49. return blurred;
  50. }
  51. @end