Ho cercato di capire come convertire un array di dati di pixel RGB in un UIImage in Swift.Pixel Array to UIImage in Swift
sto mantenendo i dati RGB per pixel in una semplice struct:
public struct PixelData {
var a: Int
var r: Int
var g: Int
var b: Int
}
Ho fatto la mia strada verso la seguente funzione, ma l'immagine risultante non è corretto:
func imageFromARGB32Bitmap(pixels:[PixelData], width: Int, height: Int)-> UIImage {
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.rawValue)
let bitsPerComponent:Int = 8
let bitsPerPixel:Int = 32
assert(pixels.count == Int(width * height))
var data = pixels // Copy to mutable []
let providerRef = CGDataProviderCreateWithCFData(
NSData(bytes: &data, length: data.count * sizeof(PixelData))
)
let cgim = CGImageCreate(
width,
height,
bitsPerComponent,
bitsPerPixel,
width * Int(sizeof(PixelData)),
rgbColorSpace,
bitmapInfo,
providerRef,
nil,
true,
kCGRenderingIntentDefault
)
return UIImage(CGImage: cgim)!
}
Qualche consiglio o suggerimento su come convertire correttamente un array rgb in un UIImage?
Questo è veramente buono ma è un po 'prolisso. Suggerirei di cambiare le asserzioni con semplici istruzioni 'guard' e usando' guard let' invece di 'if'ing for nils. Nella mia implementazione ho anche usato 'UInt' per evitare larghezza e altezze negative. – huwr