Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UIImage to byte array in swift

Tags:

ios

swift

How can I convert a UIimage into a Byte Array, so I can upload it into my web service?

like image 500
Diyaa Avatar asked Apr 19 '15 18:04

Diyaa


2 Answers

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. 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

--- update ---

Updated for Swift 5.1

like image 154
Benzy Avatar answered Sep 22 '22 17:09

Benzy


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!!!
like image 20
user3069232 Avatar answered Sep 21 '22 17:09

user3069232