Rorschach Rorschach - 4 months ago 19
Swift Question

convert NSData of an image into a string

I have an NSData object called image. It is a very small .png file.

print(image)
displays:

<89504e47 0d0a1a0a 0000000d 49484452 0000000a 0000000a 08060000 008d32cf bd000000 01735247 4200aece 1ce90000 00097048 59730000 16250000 16250149 5224f000 00001c69 444f5400 00000200 00000000 00000500 00002800 00000500 00000500 00005ec1 07ed5500 00002a49 44415428 1562f88f 04181818 fea36398 34038c01 a2d11581 f8308060 11ab109b 691826e2 5284ac10 000000ff ff232a1e 6b000000 27494441 5463f80f 040c0c0c 3831481e 0418c004 0e856015 5002a742 644560c3 c0041613 c9560800 782fe719 4293f838 00000000 49454e44 ae426082>


I am trying to make an if statement that will work for all potential images. I want it to check if the first 16 characters are
89504e47 0d0a1a0a
(which means its a png). But, I can't figure out how to convert the characters from the NSData into a string so that I can compare the image's first 16 characters to my string.

Question

How do I convert the NSData into a string so that I can do this?

if (string_of_image[1,18] == '89504e47 0d0a1a0a') {
print("This is a .png")
}


EDIT 1

trying:

var string1 = NSString(data: image, encoding: NSUnicodeStringEncoding)
print(string1)


gives:

Optional(襐乇ഊᨊ
䥈䑒

ࠆ㋏봀ų則䈀껎ᳩ 灈女ᘥᘥʼn判ᱩ䑏吀ȀԀ⠀ԀԀ廁߭唀⩉䑁吨ᕢИ᠘ﺣ掘㐃谁ꋑᖁ聠ᆫႛ椘⛢劄감ÿC⨞欀❉䑁呣Ќఌ㠱䠞И쀄຅怕倂Ꝃ摅惃쀄ᘓ쥖ࠀ砯䊓䥅乄깂悂)
n


EDIT 2

trying:

var string1 = NSString(data: image, encoding: UInt)


gives the error:

cannot convert value of type UInt.Type to expected argument type UInt

Answer

There is no need to convert the image data to a string. Just test the first bytes if they are equal to the given byte sequence, for example like this:

let pngHeader: [UInt8] = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
if imageData.length >= pngHeader.count {
    if memcmp(imageData.bytes, pngHeader, pngHeader.count) == 0 {
        print("PNG File")
    }
}