7

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.

0

1 Answer 1

3

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!!!
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. It really helped me. I just changed in my code from UInt8 to Int8 and it worked. I can not use UInt8 cause I have signed Int in my array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.