简体   繁体   English

在Swift中将字节数组转换为UIImage

[英]convert byte array to UIImage in Swift

I want to convert byte array to UIImage in my project. 我想在我的项目中将字节数组转换为UIImage
For that I found something here . 为此我在这里找到了一些东西。
After that I tried to convert that code in swift but failed. 之后,我尝试在swift中转换该代码但失败了。

Here is my swift version of the code. 这是我的代码的快速版本。

func convierteImagen(cadenaImagen: NSMutableString) -> UIImage {
        var strings: [AnyObject] = cadenaImagen.componentsSeparatedByString(",")
        let c: UInt = UInt(strings.count)
        var bytes = [UInt8]()
        for (var i = 0; i < Int(c); i += 1) {
            let str: String = strings[i] as! String
            let byte: Int = Int(str)!
            bytes.append(UInt8(byte))
//            bytes[i] = UInt8(byte)
        }
        let datos: NSData = NSData(bytes: bytes as [UInt8], length: Int(c))
        let image: UIImage = UIImage(data: datos)!
        return image
    }


but I'm getting error: 但是我收到了错误:

EXC_BAD_INSTRUCTION EXC_BAD_INSTRUCTION

which is displayed in screenshot as follow. 屏幕截图显示如下。

EXC_BAD_INSTRUCTION

Please help to solve this problem. 请帮忙解决这个问题。

If you are using the example data that you quoted, those values are NOT UInt s - they are signed Int s. 如果您使用的是您引用的示例数据,那么这些值不是UInt - 它们是对Int s进行签名的。 Passing a negative number into UInt8() does indeed seem to cause a runtime crash - I would have thought it should return an optional. 将负数传递给UInt8()确实会导致运行时崩溃 - 我原以为它应该返回一个可选项。 The answer is to use the initialiser using the bitPattern: signature, as shown in the Playground example below: 答案是使用bitPattern: signature使用初始化器,如下面的Playground示例所示:

let o = Int8("-127")
print(o.dynamicType) // Optional(<Int8>)
// It's optional, so we need to unwrap it...
if let x = o {
    print(x) // -127, as expected
    //let b = UInt8(x) // Run time crash
    let b = UInt8(bitPattern: x) // 129, as it should be
}

Therefore your function should be 因此你的功能应该是

func convierteImagen(cadenaImagen: String) -> UIImage? {
    var strings = cadenaImagen.componentsSeparatedByString(",")
    var bytes = [UInt8]()
    for i in 0..< strings.count {
        if let signedByte = Int8(strings[i]) {
            bytes.append(UInt8(bitPattern: signedByte))
        } else {
            // Do something with this error condition
        }
    }
    let datos: NSData = NSData(bytes: bytes, length: bytes.count)
    return UIImage(data: datos) // Note it's optional. Don't force unwrap!!!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM