从NSImage到NSData作为PNG Swift [英] NSImage to NSData as PNG Swift
问题描述
我正在编写基于iOS应用程序的Mac应用程序.下面的代码将UIImage转换为NSData,然后上传到Parse.com.
I am writing a Mac app based on an iOS app. The code below converts a UIImage to NSData to upload to Parse.com.
我想在Mac上做同样的事情,但似乎无法将其转换为NSData.我该怎么办?
I would like to do the same for Mac but I do not seem to be able to convert it to NSData. What should I be doing?
谢谢
var image = UIImage(named: "SmudgeInc")
let imageData = UIImagePNGRepresentation(image)
let imageFile = PFFile(name:"image.png", data:imageData)
推荐答案
You can use the NSImage
property TIFFRepresentation to convert your NSImage
to NSData
:
let imageData = yourImage.TIFFRepresentation
如果需要将图像数据保存到PNG文件,则可以使用NSBitmapImageRep(data:)
和representationUsingType
创建扩展名,以帮助您将Data
转换为PNG格式:
If you need to save your image data to a PNG file you can use NSBitmapImageRep(data:)
and representationUsingType
to create an extension to help you convert Data
to PNG format:
更新:Xcode 11•Swift 5.1
extension NSBitmapImageRep {
var png: Data? { representation(using: .png, properties: [:]) }
}
extension Data {
var bitmap: NSBitmapImageRep? { NSBitmapImageRep(data: self) }
}
extension NSImage {
var png: Data? { tiffRepresentation?.bitmap?.png }
}
用法
let picture = NSImage(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!)!
let imageURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("image.png")
if let png = picture.png {
do {
try png.write(to: imageURL)
print("PNG image saved")
} catch {
print(error)
}
}
这篇关于从NSImage到NSData作为PNG Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!