如何将UIimage转换为字节数组,以便将其上传到我的网络服务中?
答案 0 :(得分:18)
您实际上可以使用一行来执行此操作
guard let image = UIImage(named: "someImage") else { return }
guard let data = image.jpegData(compressionQuality: 1.0) else { return }
该数字的范围应为0.0到1.0,并设置jpeg质量
--- update ---
针对Swift 4.2进行了更新
答案 1 :(得分:6)
您可以将UIImage
转换为NSData
并将其传递给此方法
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
}
答案 2 :(得分:0)
基于toofani答案的Swift 5,iOS 14版本,更改最少
npm install
所以一个完整的序列看起来像这样...假设我得到了UIImage,我提取了数据然后重新组合。
func getArrayOfBytesFromImage(imageData:NSData) -> Array<UInt8>
{
// the number of elements:
let count = imageData.length / MemoryLayout<Int8>.size
// create array of appropriate length:
var bytes = [UInt8](repeating: 0, count: count)
// copy bytes into array
imageData.getBytes(&bytes, length:count * MemoryLayout<Int8>.size)
var byteArray:Array = Array<UInt8>()
for i in 0 ..< count {
byteArray.append(bytes[i])
}
return byteArray
}