【发布时间】:2015-12-17 08:27:23
【问题描述】:
我尝试使用以下代码从 pdf 页面生成 jpeg 文件。 这个应用程序的内存需求随着每次迭代而增加,但 Instruments 没有显示任何泄漏。 似乎只有在 for 循环完成时才会释放内存,因此对于 1000 页的 pdf,应用程序会消耗所有内存并且系统开始使用虚拟内存。 有什么提示吗?
let pdf = PDFDocument(URL: sourceURL)
var thumbImageURL:NSURL
var pdfImage:NSImage
let thumbRect = NSMakeRect(0.0, 0.0, ceil(CGFloat(Float(pdf.pageAtIndex(0).boundsForBox(kPDFDisplayBoxMediaBox).width) * self.thumbHeight / Float(pdf.pageAtIndex(0).boundsForBox(kPDFDisplayBoxMediaBox).height))), CGFloat(self.thumbHeight))
let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil, pixelsWide: Int(thumbRect.width), pixelsHigh: Int(thumbRect.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
NSGraphicsContext.saveGraphicsState()
let myContext = NSGraphicsContext.init(bitmapImageRep: rep)
NSGraphicsContext.setCurrentContext(myContext)
var jpegImage:NSData
for i in 0 ..< pdf.pageCount(){
thumbImageURL = self.targetURL!.URLByAppendingPathComponent("/pages/\(i+1)-thumb.jpg")
pdfImage = NSImage.init(data: pdf.pageAtIndex(i).dataRepresentation())!
pdfImage.drawInRect(thumbRect, fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeCopy, fraction: 1.0)
jpegImage = rep.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: [:])!
jpegImage.writeToURL(thumbImageURL, atomically: false)
}
NSGraphicsContext.restoreGraphicsState()
【问题讨论】:
标签: macos swift for-loop memory