将图像的 NSData 转换为字符串 [英] convert NSData of an image into a string

查看:106
本文介绍了将图像的 NSData 转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 image 的 NSData 对象.这是一个非常小的 .png 文件.print(image) 显示:

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 274944415463f80f 040c0c0c 3831481e 0418c004 0e856015 5002a742 644560c3 c0041613 c9560800 782fe719 4293f80404040404040404040405

我正在尝试创建一个适用于所有潜在图像的 if 语句.我想让它检查前 16 个字符是否是 89504e47 0d0a1a0a(这意味着它是一个 png).但是,我不知道如何将 NSData 中的字符转换为字符串,以便将图像的前 16 个字符与我的字符串进行比较.

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.

问题

如何将 NSData 转换为字符串以便执行此操作?

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")
}

编辑 1

尝试:

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

给出:

Optional(襐乇ഊᨊ
䥈䑒

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

编辑 2

尝试:

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

给出错误:

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

推荐答案

无需将图像数据转换为字符串.只需测试如果第一个字节等于给定的字节序列,例如像这样:

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")
    }
}

这篇关于将图像的 NSData 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆