我可以使用 [UIImage imageWithData:]
或 [UIImage initWithData:]
方法从 NSData
创建 UIImage
。
我想知道是否可以从现有的 UIImage
中获取 NSData
,类似于 NSData *myData = [myImage getData];
这样的操作?
我可以使用 [UIImage imageWithData:]
或 [UIImage initWithData:]
方法从 NSData
创建 UIImage
。
我想知道是否可以从现有的 UIImage
中获取 NSData
,类似于 NSData *myData = [myImage getData];
这样的操作?
NSData *imageData = UIImageJPEGRepresentation(image, 0.7); // 0.7 is JPG quality
或者NSData *imageData = UIImagePNGRepresentation(image);
根据您是想要PNG格式还是JPG格式来选择。
当使用init(data: originalData)
初始化UIImage
对象时,originalData
会被转换为某种内部格式的原始数据。稍后可以使用以下方法检索这些数据:
let rawData = myImage.cgImage?.dataProvider?.data as Data?
然而,由于rawData
是原始数据,因此它的大小甚至比使用UIImagePNGRepresentation
时还要大。
Swift 4.2
let dataPng = image.pngData() // return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format
let dataJpg = image.jpegData(compressionQuality: 1) // return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)
我偶然发现这篇文章,而且我喜欢Swift :)
以下是Caroline文章的Swift版本。
var imageData = UIImagePNGRepresentation(image)
或者
var imageData = UIImageJPEGRepresentation(image, 0.7)
你可以将UIImage视为一个用于显示格式的对象,因此它不会使用原始数据(可能是PNG或JPEG格式),而更有可能是像素数组或其他内部格式。换句话说,UIImage(data: foo)
不会保留 foo
。
If you just want to use it elsewhere in your program, the original UIImage will do fine (I presume that's not actually the case here)
If you want to serialise, UIImagePNGRepresentation(...)
will work but will be oversized if the original was a JPEG; UIImageJPEGRepresentation(...)
will often result in slightly oversize data and is slightly lossy if your original was PNG. It should be okay to pick one based on the way the image will be displayed and the format you expect to be provided. If you happen to be using PNG in and want PNG out, you should get a good file size and almost identical data, special PNG chunks aside.
If you want to get an exact copy of the original data (perhaps to save a file after thumbnailing, or to SHA1 it), then you need to retain it separately. You might do something like:
var image:UIImage
var imageData:NSData {
didSet {
image = UIImage(data: imageData)
}
}
我发现序列化/反序列化UIImage(通过Data)的唯一解决方案是使用this solution。
然后,您可以使用UIImage上的扩展方法进行序列化/反序列化,而不管UIImage是如何创建的:
let originalImage: UIImage = ...
let cgData = image.cgImage!.png!
let image = UIImage(data: cgData)!
自从上面的答案发布以来,情况已经发生了变化,对于那些仍在寻找解决方案的人,因为他们和CipherCom一样担心:iOS 5已经添加了CIImage property。
UIImageJPEGRepresentation
或UIImagePNGRepresentation
会改变数据并进行重新转换。有没有真正实现所要求的方式? - Patrik