Skip to content

Instantly share code, notes, and snippets.

@figgleforth
Last active January 17, 2023 19:26
Show Gist options
  • Save figgleforth/3046ffe2b90a6cea8cfd to your computer and use it in GitHub Desktop.
Save figgleforth/3046ffe2b90a6cea8cfd to your computer and use it in GitHub Desktop.
Extract RGBA pixel data from an UIImage in Swift
//
// UIImage+pixelData.swift
//
// Created by Bojan Percevic on 5/25/15.
// Copyright (c) 2015. All rights reserved.
//
import Foundation
extension UIImage {
func pixelData() -> [Pixel] {
var bmp = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
var data: UnsafePointer<UInt8> = CFDataGetBytePtr(bmp)
var r, g, b, a: UInt8
var pixels: [Pixel] = []
for row in 0..<Int(self.size.height) {
for col in 0..<Int(self.size.width) {
r = data.memory
data = data.advancedBy(1)
g = data.memory
data = data.advancedBy(1)
b = data.memory
data = data.advancedBy(1)
a = data.memory
data = data.advancedBy(1)
pixels.append(Pixel(r: r, g: g, b: b, a: a, row: row, col: col))
}
}
return pixels
}
}
struct Pixel {
var r: Float
var g: Float
var b: Float
var a: Float
var row: Int
var col: Int
init(r: UInt8, g: UInt8, b: UInt8, a: UInt8, row: Int, col: Int) {
self.r = Float(r)
self.g = Float(g)
self.b = Float(b)
self.a = Float(a)
self.row = row
self.col = col
}
var color: UIColor {
return UIColor(red: CGFloat(r/255.0), green: CGFloat(g/255.0), blue: CGFloat(b/255.0), alpha: CGFloat(a/255.0))
}
var description: String {
return "RGBA(\(r), \(g), \(b), \(a))"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment