Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added a grayscale category to UIImage

  • Loading branch information...
commit 1916350239ef56ecee82590636c7bdfab00c91d4 1 parent bb2def2
@jk authored
Showing with 84 additions and 0 deletions.
  1. +13 −0 UIImage+grayscale.h
  2. +71 −0 UIImage+grayscale.m
View
13 UIImage+grayscale.h
@@ -0,0 +1,13 @@
+//
+// UIImage+grayscale.h
+// JobStairs
+//
+// Created by Jens Kohl on 12.09.11.
+// Copyright (c) 2011 milch & zucker AG. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface UIImage (grayscale)
+- (UIImage *)convertToGrayscale;
+@end
View
71 UIImage+grayscale.m
@@ -0,0 +1,71 @@
+//
+// UIImage+grayscale.m
+// JobStairs
+//
+// Created by Jens Kohl on 12.09.11.
+// Copyright (c) 2011 milch & zucker AG. All rights reserved.
+//
+
+#import "UIImage+grayscale.h"
+
+@implementation UIImage (grayscale)
+
+typedef enum {
+ ALPHA = 0,
+ BLUE = 1,
+ GREEN = 2,
+ RED = 3
+} PIXELS;
+
+- (UIImage *)convertToGrayscale {
+ CGSize size = [self size];
+ int width = size.width;
+ int height = size.height;
+
+ // the pixels will be painted to this array
+ uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
+
+ // clear the pixels so any transparency is preserved
+ memset(pixels, 0, width * height * sizeof(uint32_t));
+
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+
+ // create a context with RGBA pixels
+ CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
+ kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
+
+ // paint the bitmap to our context which will fill in the pixels array
+ CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self CGImage]);
+
+ for(int y = 0; y < height; y++) {
+ for(int x = 0; x < width; x++) {
+ uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
+
+ // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
+ uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
+
+ // set the pixels to gray
+ rgbaPixel[RED] = gray;
+ rgbaPixel[GREEN] = gray;
+ rgbaPixel[BLUE] = gray;
+ }
+ }
+
+ // create a new CGImageRef from our context with the modified pixels
+ CGImageRef image = CGBitmapContextCreateImage(context);
+
+ // we're done with the context, color space, and pixels
+ CGContextRelease(context);
+ CGColorSpaceRelease(colorSpace);
+ free(pixels);
+
+ // make a new UIImage to return
+ UIImage *resultUIImage = [UIImage imageWithCGImage:image];
+
+ // we're done with image now too
+ CGImageRelease(image);
+
+ return resultUIImage;
+}
+
+@end
Please sign in to comment.
Something went wrong with that request. Please try again.