How can I convert a UIimage into a Byte Array, so I can upload it into my web service?
4 Answers
This can be done with one or two lines of code
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 }
In the first instance, the number should range from 0.0 to 1.0 and sets the jpeg quality. PNG is lossless so there is no need for a compression quality value but be aware that the file size can be about 10 times higher
--- update ---
Updated for Swift 5.1
2 Comments
unpackedImage refer to image? Or is there another process that needs to be implemented between creating image and creating data?UIImage() initialiser usually returns an optional, obviously it has to be unwrapped since the UIImageJPEGRepresentation method only accepts unwrapped objectsYou can convert UIImage to NSData and pass it to this method
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 Comments
Swift 5, iOS 14 version based on toofani answer, minimal changes
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.
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!!!
2 Comments
Little modifying for @user3069232
We can pass the image and compression parameter to get byte array.
func getByteArrayForImage(_ image: UIImage, compression: CGFloat = 1.0) -> Array<UInt8> {
guard let imageData = image.jpegData(compressionQuality: compression) as? NSData else { return [] }
let count = imageData.length / MemoryLayout<Int8>.size
var bytes = [UInt8](repeating: 0, count: count)
imageData.getBytes(&bytes, length:count * MemoryLayout<Int8>.size)
var byteArray = Array<UInt8>()
for byte in bytes {
byteArray.append(byte)
}
return byteArray
}