Last active
April 15, 2024 02:58
-
-
Save jmcd/a28248aca0e8f0ce486c9ab0d55f24e1 to your computer and use it in GitHub Desktop.
Create CGContext (then images) from raw pixel data
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
import QuartzCore | |
extension CGContext { | |
private static let colorSpace = CGColorSpaceCreateDeviceRGB() | |
private static let bitmapInfo = | |
CGBitmapInfo.byteOrder32Big.rawValue | | |
CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue | |
static func from(pixels: [UInt32], width: Int) -> CGContext? { | |
var mutPixels = pixels | |
let mutBufPtr = UnsafeMutableBufferPointer(start: &mutPixels, count: pixels.count) | |
let height = pixels.count / width | |
let bytesPerRow = width * 4 | |
return CGContext(data: mutBufPtr.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) | |
} | |
} |
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
import UIKit | |
// 0xAABBGGRR | |
let b: UInt32 = 0xffff0000 | |
let g: UInt32 = 0xff00ff00 | |
let y: UInt32 = 0xff00ffff | |
let px = [ | |
b, b, y, y, | |
b, b, b, y, | |
g, g, b, b, | |
g, g, g, g, | |
] | |
if let ctx = CGContext.from(pixels: px, width: 4), let cgImage = ctx.makeImage() { | |
let uiImage = UIImage(cgImage: cgImage) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment