0

I have a json as below. I need to convert the image to a byte array and post it as a String.

I can convert the image to byte array but how can I convert it to String? I am getting an error while converting byte array to String.

Error:

"not a valid UTF-8 sequence"

JSON:

"photo1": "[255,216,255,224,0,16,74,70,73, ..... ,]"

Image Data to Byte Array:

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
}

Using getArrayOfBytesFromImage Function:

if let string = String(bytes: getArrayOfBytesFromImage(imageData: imageData), encoding: .utf8) {
        print(string)
    } else {
        print("not a valid UTF-8 sequence")
    }
4
  • What is the error that you are getting? Commented Nov 19, 2021 at 8:22
  • "not a valid UTF-8 sequence" here the else block always works. Commented Nov 19, 2021 at 8:23
  • Hang on, is the JSON that you showed the desired result? Commented Nov 19, 2021 at 8:29
  • json there is an example. It shows the value I will send as an example. I looked at what type of value to send json using app.quicktype.io website. I need to send this array as string. Commented Nov 19, 2021 at 8:32

1 Answer 1

1

Those are not UTF-8 bytes, so don't say encoding: .utf8. Those bytes do not form a string, so you should not use String.init(bytes:encoding:). You should get the value of those bytes, and get their description one way or another (e.g. by string interpolation).

You don't even need a byte array here. Just go straight to strings, since that's what you're after.

let imageData = Data([1, 2, 3, 4, 5]) // for example
let string = "[\(imageData.map { "\($0)" }.joined(separator: ","))]"
print(string) // prints [1,2,3,4,5]
Sign up to request clarification or add additional context in comments.

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.