[英]Convert UIImage to byte array in swift
如何将 UIimage 转换为字节数组,以便将其上传到我的 Web 服务中?
You can actually use a couple of lines to do it你实际上可以使用几行来做到这一点
guard let image = UIImage(named: "someImage"),
let data = image.jpegData(compressionQuality: 1.0) else { return }
// OR
guard let image = UIImage(named: "someImage"),
let data = image.pngData() else { return }
The number should range from 0.0 to 1.0 and sets the jpeg quality.该数字应在 0.0 到 1.0 之间,并设置 jpeg 质量。 PNG is lossless so there is no need for compression quality identifier but be aware that the file size can be about 10 times higher
PNG 是无损的,因此不需要压缩质量标识符,但请注意,文件大小可能大 10 倍左右
--- update ---
Updated for Swift 5.1为 Swift 5.1 更新
You can convert UIImage
to NSData
and pass it to this method您可以将
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
}
Swift 5, iOS 14 version based on toofani answer, minimal changes Swift 5,iOS 14 版本基于toofani答案,改动最小
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
}
So a complete sequence looks like this... assuming I got a UIImage I extract the data and then recombine it.所以一个完整的序列看起来像这样......假设我有一个 UIImage 我提取数据然后重新组合它。
let data = imageX.pngData()
bytes = getArrayOfBytesFromImage(imageData: data! as NSData)
let datos: NSData = NSData(bytes: bytes, length: bytes.count)
newImage = UIImage(data: datos as Data) // Note it's optional. Don't force unwrap!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.