像素阵列来的UIImage斯威夫特 [英] Pixel Array to UIImage in Swift

查看:201
本文介绍了像素阵列来的UIImage斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出如何RGB像素数据的数组转换为斯威夫特一个UIImage。

I've been trying to figure out how to convert an array of rgb pixel data to a UIImage in Swift.

我让每个像素的RGB数据在一个简单的结构:

I'm keeping the rgb data per pixel in a simple struct:

public struct PixelData {
   var a: Int
   var r: Int
   var g: Int
   var b: Int
}

我做了我的方式,下面的函数,但产生的图像是不正确:

I've made my way to the following function, but the resulting image is incorrect:

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)!
}

有关如何在RGB排列正确转换到一个UIImage的任何提示或指针?

Any tips or pointers on how to properly convert an rgb array to an UIImage?

推荐答案

您唯一的问题是,在你的 PixelData取出结构中的数据类型必须是 UINT8 。我创建了以下在操场测试图像:

Your only problem is that the data types in your PixelData structure need to be UInt8. I created a test image in a Playground with the following:

public struct PixelData {
    var a: UInt8
    var r: UInt8
    var g: UInt8
    var b: UInt8
}

var pixels = [PixelData]()

let red = PixelData(a: 255, r: 255, g: 0, b: 0)
let green = PixelData(a: 255, r: 0, g: 255, b: 0)
let blue = PixelData(a: 255, r: 0, g: 0, b: 255)

for i in 1...300 {
    pixels.append(red)
}
for i in 1...300 {
    pixels.append(green)
}
for i in 1...300 {
    pixels.append(blue)
}

let image = imageFromARGB32Bitmap(pixels, 30, 30)

这篇关于像素阵列来的UIImage斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆