【发布时间】:2025-11-22 23:10:01
【问题描述】:
我正在尝试从用户的相机胶卷中检索图像,但遇到了内存不足的问题。我一次加载 50 张图像,但不幸的是,在几次加载后,它会耗尽内存并崩溃。我尝试将整个语句包装在自动释放池中,但事实证明这并不有效。这是我的代码...
func retrieveImages(thumbnail: Bool, indexOfLibrary: Int) {
/* Retrieve the items in order of modification date, ascending */
var indexSet: NSIndexSet!
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]
/* Then get an object of type PHFetchResult that will contain
all our image assets */
let assetResults = PHAsset.fetchAssetsWithMediaType(.Image,
options: options)
if totalPostsCounted == false {
assetResults.enumerateObjectsUsingBlock { (object: AnyObject!, count: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if object is PHAsset {
self.totalPosts = count
} else {
self.totalPostsCounted = true
}
}
}
if thumbnail == true {
if totalPosts - libraryImageThumbnails.count < 50 {
allImagesLoaded = true
} else {
if firstTimeLoadedThumb == true {
} else {
firstTimeLoadedThumb = true
}
}
} else {
if totalPosts - libraryImages.count < 50 {
allImagesLoaded = true
} else {
if firstTimeLoaded == true {
} else {
firstTimeLoaded = true
}
}
}
if thumbnail == true {
fiftyIncrementThumb = fiftyIncrementThumb + 50
increment = fiftyIncrementThumb
} else {
fiftyIncrement = fiftyIncrement + 50
increment = fiftyIncrement
}
let imageManager = PHCachingImageManager()
autoreleasepool { () -> () in
assetResults.enumerateObjectsUsingBlock { (object, count: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if object is PHAsset {
var imageSize: CGSize!
var array: NSArray!
if thumbnail == true {
array = self.libraryImageThumbnails
} else {
array = self.libraryImages
}
autoreleasepool {
if count >= array.count && count <= increment {
if thumbnail == true {
imageSize = CGSize(width: 100, height: 100)
} else {
imageSize = CGSize(width: self.cameraView.bounds.width, height: self.cameraView.bounds.height)
}
let asset = object as! PHAsset
let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat
options.synchronous = true
imageManager.requestImageForAsset(asset,
targetSize: imageSize,
contentMode: .AspectFill,
options: options,
resultHandler: { (image, _: [NSObject : AnyObject]?) -> Void in
if thumbnail == true {
self.libraryImageThumbnails.append(image!)
} else {
self.libraryImages.append(image!)
}
})
}
}
}
}
}
}
我也试过这个,它返回 nil 并崩溃了......
let library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group: ALAssetsGroup!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
group.enumerateAssetsUsingBlock({ (asset, count: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if asset != nil {
self.libraryImageThumbnails.append(asset)
self.collectionTable.reloadData()
}
})
}, failureBlock: { (error: NSError!) -> Void in
})
如果您需要更多信息,请告诉我!谢谢!
【问题讨论】:
-
您需要做的是获取图像的 url,然后使用来自该 url 的
dispatch_async将图像加载到后台队列中。 -
@DhaivatVyas 如何使用文件 URL 从我的相机胶卷中检索图像?