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

问题描述 投票:0回答:1

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

ios arrays swift uiimage swift4
1个回答
0
投票

试试这个!!

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
}
© www.soinside.com 2019 - 2024. All rights reserved.