[英]NSData and UIImage
I am trying to load UIImage
object from NSData
, and the sample code was to NSImage
, I guess they should be the same. 我试图从
NSData
加载UIImage
对象,示例代码是NSImage
,我猜他们应该是相同的。 But just now loading the image, I am wondering what's the best to troubleshoot the UIImage
loading NSData
issue. 但是刚刚加载图像,我想知道什么是最好的解决
UIImage
加载NSData
问题。
I didn't try UIImageJPEGRepresentation()
before, but UIImagePNGRepresentation
works fine for me, and conversion between NSData
and UIImage
is dead simple: 我之前没有尝试过
UIImageJPEGRepresentation()
,但UIImagePNGRepresentation
对我来说很好, NSData
和UIImage
之间的转换很简单:
NSData *imageData = UIImagePNGRepresentation(image);
UIImage *image=[UIImage imageWithData:imageData];
UIImage has an - initWithData:
method. UIImage有一个 -
initWithData:
方法。 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." 从文档:“数据参数中的数据必须格式化,以匹配系统支持的图像类型之一的文件格式。”
Try this to convert an image to NSdata: 试试这个将图像转换为NSdata:
UIImage *img = [UIImage imageNamed:@"image.png"];
NSData *data1 = UIImagePNGRepresentation(img);
theData should be a NSData
object which already contains the data. theData应该是一个已经包含数据的
NSData
对象。 You need to do the file loading/downloading to the NSData
object before it is used. 在使用之前,您需要将文件加载/下载到
NSData
对象。 You can inspect it by using NSLog
on theData and see if it contains the valid data. 您可以使用Data上的
NSLog
检查它,看它是否包含有效数据。
For safe execution of code, use if-let block with Data, as function UIImagePNGRepresentation returns, optional value. 为了安全执行代码,使用带有Data的if-let块,因为函数UIImagePNGRepresentation返回,可选值。
if let img = UIImage(named: "Hello.png") {
if let data:Data = UIImagePNGRepresentation(img) {
// Handle operations with data here...
}
}
Note:
Data is Swift 3 class.
注意: 数据是Swift 3类。 Use Data instead of NSData with Swift 3
在Swift 3中使用Data而不是NSData
Generic image operations (like png & jpg both): 通用图像操作(如png和jpg):
if let img = UIImage(named: "Hello.png") {
if let data:Data = UIImagePNGRepresentation(img) {
handleOperationWithData(data: data)
} else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
By using extension: 通过使用扩展名:
extension UIImage {
var pngRepresentationData: Data? {
return UIImagePNGRepresentation(img)
}
var jpegRepresentationData: Data? {
return UIImageJPEGRepresentation(self, 1.0)
}
}
*******
if let img = UIImage(named: "Hello.png") {
if let data = img.pngRepresentationData {
handleOperationWithData(data: data)
} else if let data = jpegRepresentationData {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.