【问题标题】:Swift OS X - Save .jpeg's into array of NSImage'sSwift OS X - 将 .jpeg 保存到 NSImage 的数组中
【发布时间】:2015-08-03 01:02:15
【问题描述】:

我有一个用 Swift 编写的 OS X 应用程序,我正在尝试遍历一个目录并将每个图像保存到一个 NSImage 数组中,这样我就可以一次在一个 NSImageView 中显示它们。

我现在的代码如下:

func LoadImages() {
    let fileManager = NSFileManager.defaultManager()
    let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(strPhotoDirectory)!
    while let element = enumerator.nextObject() as? String {
        if element.hasSuffix("jpg") || element.hasSuffix("jpeg") {
            self.images.append(NSImage(contentsOfFile: element)!)
        }
    }

    self.imageCurrent.image = self.images[0]    // Sets my imageView to the first image
}

其中strPhotoDirectory 等于文件路径。

目前,调试器在最后一行崩溃(将 imageView 设置为第一个图像),因为数组超出范围,我认为这意味着图像从一开始就没有保存,所以数组为空。

我尝试poing 调试器控制台在运行时查找我的变量的一些值,并发现element.hasSuffix("XXX")jpgjpegJPG、@ 返回 false 987654328@。我要保存的图像具有文件名VH-YIZ VOZ B738 - YSSY - 26-07-2015 - 1 - Rotating on 34R 和扩展名.JPEG

我做错了什么?

提前致谢。

编辑 当我运行代码时,它到达上面指定的行并输出:

strPhotoDirectory = /Users/Matt/Downloads/Test/
Total Path = /Users/Matt/Downloads/Test/VH-YIZ VOZ B738 - YSSY - 10-04-2015 - 1 - On short final for 25.JPG

然后:

致命错误:在展开可选值时意外发现 nil

【问题讨论】:

  • enumerator.nextObject() 实际上会返回文件名而不是完整路径。您需要将其附加到目录路径,在本例中为 strPhotoDirectory,并在创建 NSImage 之前获取文件的完整路径。 HTH
  • 我将代码修改为self.images.append(NSImage(contentsOfFile: "\(strPhotoDirectory)\(element)")!),但仍然出现同样的错误。
  • strPhotoDirectory 的值是多少?也可以把生成的图片路径之一贴上去吗?
  • 我已经修改了问题以包含您提到的内容。希望这会有所帮助,感谢您帮助我:)

标签: macos swift file nsimage nsimageview


【解决方案1】:

通过确保从完整路径加载 NSImage,我让您的代码正常工作

   func LoadImages() {
        //
        // make certain to append a slash (/) at the end!
        let strPhotoDirectory = "/Users/me/Pictures/" 

        //
        let fileManager = NSFileManager.defaultManager()
        let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(strPhotoDirectory)!
        while let element = enumerator.nextObject() as? String {
            if element.hasSuffix("jpg") || element.hasSuffix("jpeg") {
                if let image = NSImage(contentsOfFile: strPhotoDirectory + element)
                {
                    self.images.append(image)
                }
            }
        }

        self.imageCurrent.image = self.images[0]    // Sets my imageView to the first image
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2013-10-18
    相关资源
    最近更新 更多