在Swift中将字节数组转换为UIImage [英] convert byte array to UIImage in Swift
问题描述
我想在我的项目中将字节数组转换为 UIImage
。
为此,我在
请帮助解决此问题。
如果您使用引用的示例数据,则这些值不是 UInt
s-它们被签名为 Int
s。将负数传递给 UInt8()
确实确实会导致运行时崩溃-我以为它应该返回可选值。答案是使用带有 bitPattern:
签名的初始化程序,如下面的Playground示例所示:
let o = Int8(-127)
print(o.dynamicType)//可选(< Int8>)
//这是可选的,因此我们需要解开它...
如果让x = o {
print(x)// -127,如预期的那样
// let b = UInt8(x)//运行时崩溃
let b = UInt8(bitPattern:x)// 129,因为它应该是
}
因此您的函数应该是
func convierteImagen(cadenaImagen:String)-> UIImage? {
var字符串= cadenaImagen.componentsSeparatedByString(,)
var字节= [UInt8]()
对于0中的i。 strings.count {
if letsignedByte = Int8(strings [i]){
bytes.append(UInt8(bitPattern:signedByte))
} else {
//做点什么出现这种错误情况
}
}
让datos:NSData = NSData(bytes:bytes,length:bytes.count)
return UIImage(data:datos)//注意可选的。不要强行拆开!!!
}
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.
If you are using the example data that you quoted, those values are NOT UInt
s - they are signed 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. 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!!!
}
这篇关于在Swift中将字节数组转换为UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!