NSData 和 UIImage
我正在尝试从 NSData
加载 UIImage
对象,示例代码是 NSImage
,我想它们应该是相同的。 但刚刚加载图像,我想知道解决 UIImage
加载 NSData
问题的最佳方法是什么。
I am trying to load UIImage
object from NSData
, and the sample code was to NSImage
, I guess they should be the same. But just now loading the image, I am wondering what's the best to troubleshoot the UIImage
loading NSData
issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我之前没有尝试过
UIImageJPEGRepresentation()
,但是UIImagePNGRepresentation
对我来说效果很好,并且NSData
和UIImage
之间的转换> 非常简单:I didn't try
UIImageJPEGRepresentation()
before, butUIImagePNGRepresentation
works fine for me, and conversion betweenNSData
andUIImage
is dead simple:UIImage 有一个 -
initWithData:
方法。 来自文档:“数据参数中的数据必须格式化以匹配系统支持的图像类型之一的文件格式。”UIImage has an -
initWithData:
method. From the docs: "The data in the data parameter must be formatted to match the file format of one of the system’s supported image types."尝试将图像转换为 NSdata:
Try this to convert an image to NSdata:
theData 应该是一个已经包含数据的 NSData 对象。 在使用之前,您需要将文件加载/下载到
NSData
对象。 您可以通过在 theData 上使用NSLog
来检查它,看看它是否包含有效数据。theData should be a
NSData
object which already contains the data. You need to do the file loading/downloading to theNSData
object before it is used. You can inspect it by usingNSLog
on theData and see if it contains the valid data.为了安全执行代码,请使用带有 Data 的 if-let 块,因为函数 UIImagePNGRepresentation 返回可选值。
通用图像操作(如 png 和 jpg 两者):
通过使用扩展:
For safe execution of code, use if-let block with Data, as function UIImagePNGRepresentation returns, optional value.
Generic image operations (like png & jpg both):
By using extension: