12

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

4 Answers 4

28

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does unpackedImage refer to image? Or is there another process that needs to be implemented between creating image and creating data?
Sorry for that, UIImage() initialiser usually returns an optional, obviously it has to be unwrapped since the UIImageJPEGRepresentation method only accepts unwrapped objects
7

You 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

how can i perform reverse...how can i get image from bytes
get your image back from the array of bytes ---> static func getImag(from bytes: [NSNumber]) -> UIImage? { return UIImage.init(data: Data.init(bytes: bytes.map({ $0.uint8Value }))) }
2

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

What if I just want raw data and not pngData. pngData seems to change the bytes so it thinks it is a png image.
I think you need to convert it to png data because Apple is not going to publish their internal formats for you to play around with.
0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.