Swift 从文件系统上的文件设置NSImage
如何在Swift macOS应用程序中设置NSImage,方法是为其提供文件系统上的路径 例如,我在Mac上的一个目录中有一个图像,我想把它变成一个NSImage 这就是我正在做的:Swift 从文件系统上的文件设置NSImage,swift,Swift,如何在Swift macOS应用程序中设置NSImage,方法是为其提供文件系统上的路径 例如,我在Mac上的一个目录中有一个图像,我想把它变成一个NSImage 这就是我正在做的: let str = "/Users/jin/Desktop/Images/tree.jpg" if let imageRef = NSImage(byReferencingFile: str) { print("image size \(imageRef.size.width):\(imageRef.s
let str = "/Users/jin/Desktop/Images/tree.jpg"
if let imageRef = NSImage(byReferencingFile: str) {
print("image size \(imageRef.size.width):\(imageRef.size.height)")
self.sliderImage.image = imageRef
print(str)
}
else {
print("Image not found")
print(str)
}
但是,它生成的图像的宽度和高度为0,0
,您可以使用
init(byReferencingFile:)
初始值设定项
NSImage
您可以在其中指定文件系统上文件的完整路径或相对路径:
filename
A full or relative path name specifying the file with the desired image data. Relative paths must be relative to the current working directory.
您还可以验证文件的存在性;也可以改用fileUrl:
guard FileManager.default.fileExists(atPath: str) else {
return
}
let fileUrl = URL.init(fileURLWithPath: str)
或者通过NSData加载和检查:
guard let imageData = NSData.init(contentsOfFile: str) else {
return
}
guard let image = NSImage.init(data: imageData as Data) else {
return
}
let str=“/Users/jin/Desktop/Images/tree.jpg”//let url=NSURL(string:str)如果let-imageRef=NSImage(byreferencengfile:str){print(“图像大小(imageRef.size.width):(imageRef.size.height)”)self.sliderImage.image=imageRef-print(str)}其他{print(“Image not found”)print(str)}这就是我正在做的。它以0和0的高度打印图像,0我将您的代码移到问题并更新了我的答案。图像路径有效,但高度和宽度为零。您是否在屏幕上实际显示图像后尝试打印尺寸?参考说明:“此方法延迟初始化图像对象。在应用程序尝试绘制图像或请求有关图像的信息之前,它不会实际打开指定的文件或从其数据创建任何图像表示。“是的,静态宽度和高度为零。在iOS和macOS中不应该这样做。有什么原因吗?除了用户自愿选择的文件之外,不应该打开其他文件。用户将浏览文件并选择图像。之后,图像应显示在应用程序中。