Created
October 31, 2014 17:09
-
-
Save akirahrkw/ce3c52ae79f3b5de5a01 to your computer and use it in GitHub Desktop.
manipulate pixel data by swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseImageProcessor { | |
func createARGBBitmapContext(imageRef : CGImageRef) -> CGContextRef! { | |
var pixelWidth:UInt = CGImageGetWidth(imageRef); | |
var pixelHeight:UInt = CGImageGetHeight(imageRef); | |
var bitmapBytesPerRow:UInt = (pixelWidth * 4) | |
var bitmapByteCount:UInt = (bitmapBytesPerRow * pixelHeight) | |
var colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB() | |
var bitmapData:UnsafeMutablePointer<Void> = malloc(bitmapByteCount) | |
if bitmapData == nil { | |
return nil | |
} | |
var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedFirst.toRaw())! | |
var context:CGContextRef = CGBitmapContextCreate(bitmapData, pixelWidth, pixelHeight, 8, bitmapBytesPerRow, colorSpace, bitmapInfo) | |
return context | |
} | |
func manipulatePixel(imageRef : CGImageRef) -> UIImage? { | |
var context = self.createARGBBitmapContext(imageRef) | |
var width:Int = Int(CGImageGetWidth(imageRef)) | |
var height:Int = Int(CGImageGetHeight(imageRef)) | |
var rect = CGRectMake(0, 0, CGFloat(width), CGFloat(height)) | |
CGContextDrawImage(context, rect, imageRef) | |
var data: UnsafeMutablePointer<Void> = CGBitmapContextGetData(context) | |
var dataType = UnsafeMutablePointer<UInt8>(data) | |
var alpha, red, green, blue:UInt8 | |
var base, offset:Int | |
for y in 0...(height - 1) { | |
base = y * height * 4 | |
for x in 0...(width - 1) { | |
offset = base + x * 4 | |
alpha = dataType[offset] | |
red = dataType[offset + 1] | |
green = dataType[offset + 2] | |
blue = dataType[offset + 3] | |
} | |
} | |
var imageRef = CGBitmapContextCreateImage(context); | |
var newImage = UIImage(CGImage: imageRef) | |
free(data) | |
return newImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment