繁体   English   中英

如何在 Swift 中从文件夹中获取 UIImage 数组?

[英]How to get array of UIImage, from folder, in Swift?

我有一个像这样的普通 Xcode 项目......

在此处输入图片说明

请注意有一个名为“images”的文件夹(它是一个实际的文件夹 - 不仅仅是一个组)。 它包含 25 个“.png”图像。

我想要做的就是用这些图像中的每一个制作一个UIimage数组

(或者甚至是图像名称或类似名称的数组,那很好 - 然后可以加载它们UIImage(named: )

我如何进入该文件夹“图像”? 子文件夹“图像/汽车”怎么样?

我试过这样的事情,但它什么也没找到......

override func viewDidLoad()
    {
    let imageArray = NSBundle.mainBundle().URLsForResourcesWithExtension(
          "png", subdirectory: "images")
    print("test...")
    for n:NSURL in imageArray!
        { print("found ..." ,n) }
    }

我们假设图像在应用程序的资源包中。 如果不是,您需要确保您的图像目录列在目标“构建阶段”的“复制捆绑资源”中。

在此处输入图片说明

编辑这只会将图像复制到应用程序包中,如果您需要按照下面的代码将文件夹复制到应用程序包中,请使用以下StackOverflow 问题进行正确设置。

这为我们提供了一个 URL 数组,然后我们可以使用 UIImage(data:) 和 NSData(contentsOfURL:) 在需要时创建图像。

获取包的资源路径并附加图像目录,然后获取目录的内容。

     if let path = NSBundle.mainBundle().resourcePath {

        let imagePath = path + "/images"
        let url = NSURL(fileURLWithPath: imagePath)
        let fileManager = NSFileManager.defaultManager()

        let properties = [NSURLLocalizedNameKey,
                          NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]

        do {
            let imageURLs = try fileManager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)

            print("image URLs: \(imageURLs)")
            // Create image from URL
            var myImage =  UIImage(data: NSData(contentsOfURL: imageURLs[0])!)

        } catch let error1 as NSError {
            print(error1.description)
        }
    }

请尝试以下操作:

在此处输入图片说明

  1. 您必须将图像注册到“复制捆绑资源”。

  2. 您必须在主 Bundle 中添加过滤器模块。 在此处输入图片说明

它在我这边运行良好。 也许您可以将过滤器从“jpg”格式更改为“png”格式。

我已经在 iOS 10.x 之后的 Swift 3.0 和 xcode 8.1 版本上进行了测试。

我建议不要一次将所有图像加载到数组中。 图像往往很大,很容易耗尽内存和崩溃。

除非您绝对必须一次将所有图像保存在内存中,否则最好保留一组路径或 URL 并根据需要一次加载一个图像。

假设您的应用程序包中包含充满图像的文件夹,您可以使用 NSBundle 方法URLsForResourcesWithExtension:subdirectory:NSURL数组获取到您的图像子目录中的所有文件,具有特定文件类型或所有文件(如果您为扩展传递 nil。)

一旦你有一个文件 url 数组,你可以根据需要将它映射到一个路径数组,然后将映射到一个图像数组。

斯威夫特 4

    if let path = Bundle.main.resourcePath {
        let imagePath = path + "/images"
        let url = NSURL(fileURLWithPath: imagePath)
        let fileManager = FileManager.default

        let properties = [URLResourceKey.localizedNameKey,
                          URLResourceKey.creationDateKey, 
                          URLResourceKey.localizedTypeDescriptionKey]

        do {
            let imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)

            print("image URLs: \(imageURLs)")
            // Create image from URL
            let firstImageURL = imageURLs[0]
            let firstImageData = try Data(contentsOf: firstImageURL)
            let firstImage = UIImage(data: firstImageData)

            // Do something with first image

        } catch let error as NSError {
            print(error.description)
        }
    }

您可以按照以下步骤下载它们:

  1. 在finder中创建一个新文件夹并添加所有图像(或文件夹,......一切)。

  2. 更改文件夹名称 + “.bundle”(例如:YourListImage -> YourListImage.bundle)。

  3. 将文件夹添加到项目。

  4. 添加文件管理器扩展:

     extension FileManager { func getListFileNameInBundle(bundlePath: String) -> [String] { let fileManager = FileManager.default let bundleURL = Bundle.main.bundleURL let assetURL = bundleURL.appendingPathComponent(bundlePath) do { let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles) return contents.map{$0.lastPathComponent} } catch { return [] } } func getImageInBundle(bundlePath: String) -> UIImage? { let bundleURL = Bundle.main.bundleURL let assetURL = bundleURL.appendingPathComponent(bundlePath) return UIImage.init(contentsOfFile: assetURL.relativePath) } }
  5. 使用:

     let fm = FileManager.default let listImageName = fm.getListFileNameInBundle(bundlePath: "YourListImage.bundle") for imgName in listImageName { let image = fm.getImageInBundle(bundlePath: "YourListImage.bundle/\\(imgName)") }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM