Skip to content

Instantly share code, notes, and snippets.

@igrechuhin
Forked from irskep/getUIImageForRGBAData.swift
Created September 6, 2016 13:53
Show Gist options
  • Save igrechuhin/0ad36eb55afa9ee212305f7812e2a0fa to your computer and use it in GitHub Desktop.
Save igrechuhin/0ad36eb55afa9ee212305f7812e2a0fa to your computer and use it in GitHub Desktop.
Convert RGBA bytes to UIImage in Swift
func getUIImageForRGBAData(#width: UInt, #height: UInt, #data: NSData) -> UIImage? {
let pixelData = data.bytes
let bytesPerPixel:UInt = 4
let scanWidth = bytesPerPixel * width
let provider = CGDataProviderCreateWithData(nil, pixelData, height * scanWidth, nil)
let colorSpaceRef = CGColorSpaceCreateDeviceRGB()
var bitmapInfo:CGBitmapInfo = .ByteOrderDefault;
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.Last.rawValue)
let renderingIntent = kCGRenderingIntentDefault;
let imageRef = CGImageCreate(width, height, 8, bytesPerPixel * 8, scanWidth, colorSpaceRef,
bitmapInfo, provider, nil, false, renderingIntent);
return UIImage(CGImage: imageRef)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment