convert byte array to UIImage in Swift

你说的曾经没有我的故事 提交于 2019-12-23 08:55:14

问题


I want to convert byte array to UIImage in my project.
For that I found something here.
After that I tried to convert that code in swift but failed.

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

which is displayed in screenshot as follow.

Please help to solve this problem.


回答1:


If you are using the example data that you quoted, those values are NOT UInts - they are signed Ints. Passing a negative number into UInt8() does indeed seem to cause a runtime crash - I would have thought it should return an optional. The answer is to use the initialiser using the bitPattern: signature, as shown in the Playground example below:

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


来源:https://stackoverflow.com/questions/38308757/convert-byte-array-to-uiimage-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!