Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert byte array to UIImage in Swift

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.

EXC_BAD_INSTRUCTION

Please help to solve this problem.

like image 919
Mrugesh Tank Avatar asked Jul 11 '16 13:07

Mrugesh Tank


1 Answers

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!!!
}
like image 157
Grimxn Avatar answered Oct 05 '22 21:10

Grimxn