Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save irlabs/58aed5c5394485c0780ffb78f774f582 to your computer and use it in GitHub Desktop.
Save irlabs/58aed5c5394485c0780ffb78f774f582 to your computer and use it in GitHub Desktop.
Manipulate pixel data in swift 3.0
class BaseImageProcessor {
func createARGBBitmapContext(image: CGImage) -> CGContext? {
let pixelWidth = image.width
let pixelHeight = image.height
let bitmapBytesPerRow = pixelWidth * 4
let bitmapByteCount = bitmapBytesPerRow * pixelHeight
let bitmapData: UnsafeMutableRawPointer = malloc(bitmapByteCount)
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
guard let bitmapContext = CGContext(data: bitmapData,
width: pixelWidth,
height: pixelHeight,
bitsPerComponent: 8,
bytesPerRow: bitmapBytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil
}
return bitmapContext
}
func manipulatePixel(of image: CGImage) -> UIImage? {
guard let context = createARGBBitmapContext(image: image) else {
return nil
}
let width = context.width
let height = context.height
var rect = CGRect(x: 0, y: 0, width: width, height: height)
CGContextDrawImage(context, rect, image)
guard let pixelData = image.dataProvider?.data else {
return nil
}
let pixelBuffer: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var alpha, red, green, blue: UInt8
var base, offset:Int
for y in 0...(height - 1) {
base = y * width * 4
for x in 0...(width - 1) {
offset = base + x * 4
alpha = pixelBuffer[offset]
red = pixelBuffer[offset + 1]
green = pixelBuffer[offset + 2]
blue = pixelBuffer[offset + 3]
}
}
var imageRef = CGBitmapContextCreateImage(context);
var newImage = UIImage(CGImage: imageRef)
return newImage
}
}
@irlabs
Copy link
Author

irlabs commented Jun 9, 2017

Warning, this code will not yet work on swift 3.0 (Especially the newImage creation is not converted and checked)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment