Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在Swift 4中将UIImage转换为字节数组_Ios_Arrays_Swift_Uiimage_Swift4 - Fatal编程技术网

Ios 如何在Swift 4中将UIImage转换为字节数组

Ios 如何在Swift 4中将UIImage转换为字节数组,ios,arrays,swift,uiimage,swift4,Ios,Arrays,Swift,Uiimage,Swift4,我正在尝试将UIimage转换为swift中的字节数组。我搜索了很多,但解决方案要么太旧(对于swift 2),要么不起作用。 有人知道这样做的方法吗?! 谢谢试试这个 guard let image = UIImage(named: "someImage") else { return } let data = UIImageJPEGRepresentation(image, 1.0) OR you can convert UIImage to NSData func getArray

我正在尝试将UIimage转换为swift中的字节数组。我搜索了很多,但解决方案要么太旧(对于swift 2),要么不起作用。 有人知道这样做的方法吗?! 谢谢

试试这个

guard let image = UIImage(named: "someImage") else { return } 

let data = UIImageJPEGRepresentation(image, 1.0)

OR you can convert UIImage to NSData

func getArrayOfBytesFromImage(imageData:NSData) -> NSMutableArray
{

    // the number of elements:
    let count = data.length / MemoryLayout<UInt8>.size

    // create array of appropriate length:
    var bytes = [UInt8](repeating: 0, count: count)
    // copy bytes into array
    imageData.getBytes(&bytes, length:count)

    var byteArray:NSMutableArray = NSMutableArray()

    for (var i = 0; i < count; i++) {
        byteArray.addObject(NSNumber(unsignedChar: bytes[i]))
    }

    return byteArray
}
guard let image=UIImage(名为:“someImage”)else{return}
让数据=UIImageJPEG表示(图像,1.0)
也可以将UIImage转换为NSData
func GetArrayOfBytes fromImage(imageData:NSData)->NSMutableArray
{
//元素的数量:
let count=data.length/MemoryLayout.size
//创建适当长度的数组:
变量字节=[UInt8](重复:0,计数:计数)
//将字节复制到数组中
imageData.getBytes(&bytes,长度:计数)
var byteArray:NSMutableArray=NSMutableArray()
对于(变量i=0;i
上述解决方案不正确,每个字节的复制速度非常慢 大图像需要4秒,下面是0.02s(Swift3的新构造函数)


我试过了,虽然sizeof(UInt8)不再可用,但有什么想法吗<代码>打印(“位宽度:\(UInt8.bitWidth)内存布局:\(MemoryLayout.size)”)显示:
位宽度:8内存布局:1
此方法非常慢!什么是你的
pngData()
?谢谢你的发现,我漏掉了一个词:
image.pngData()
 let data: [UInt8] = [...]
 let image = UIImage(data: Data(bytes: data, count: data.count))

 guard let dataPng: Data = image.pngData() else { return [] }
 let finalData = [UInt8](dataPng)