在swift中将UIImage转换为字节数组

Diy*_*yaa 9 ios swift

如何将UIimage转换为字节数组,以便将其上传到我的Web服务中?

Ben*_*nzy 19

您实际上可以使用一行来完成它

guard let image = UIImage(named: "someImage") else { return }
guard let data = image?.jpegData(compressionQuality: 1.0) else { return }
// OR
guard let data = image?.pngData() else { return }
Run Code Online (Sandbox Code Playgroud)

数字应在0.0到1.0之间,并设置jpeg质量

--- update ---

针对Swift 4.2进行了更新


too*_*ani 6

您可以转换UIImageNSData并将其传递给此方法

func getArrayOfBytesFromImage(imageData:NSData) -> NSMutableArray
{

    // the number of elements:
    let count = imageData.length / sizeof(UInt8)

    // create array of appropriate length:
    var bytes = [UInt8](count: count, repeatedValue: 0)

    // copy bytes into array
    imageData.getBytes(&bytes, length:count * sizeof(UInt8))

    var byteArray:NSMutableArray = NSMutableArray()

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

    return byteArray


}
Run Code Online (Sandbox Code Playgroud)