Swift5 MacOS ImageResize内存问题

编程入门 行业动态 更新时间:2024-10-18 10:35:55
本文介绍了Swift5 MacOS ImageResize内存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是使用Swift进行Mac OS App开发的新手.但是我尝试制作简单的ImageResizer应用.我必须调整50k图像的大小.10小时后,内存已增加到每GB 120GB.我以为Swift也有垃圾收集器.为什么增加内存?我将向您展示我的代码.

for i in 0 ..< paths.count {让路径=路径[i]如果让image = NSImage(contentsOf:path){...如果self.resize(image:image,size:size,to:URL(fileURLWithPath:resizedImagePath)){print(图像已保存到\(resizedImagePath)")继续}}}func resize(image:NSImage,size:Int,to url:URL)->布尔{如果!image.isValid {打印(无效图片")返回假}警卫队,让pixelWide = image.representations.first?.pixelsWide else {返回假}令因子:CGFloat = CGFloat(pixelsWide)/image.size.widthvar width:CGFloat = CGFloat(size)var高度:CGFloat = CGFloat(大小)如果image.size.width>image.size.height {高度=宽度* image.size.height/image.size.width} 别的 {宽度=高度* image.size.width/image.size.height}让rep = NSBitmapImageRep(bitmapDataPlanes:nil,pixelWide:Int(width),pixelHigh:Int(高度),bitsPerSample:8samplesPerPixel:4hasAlpha:是的,isPlanar:否,colorSpaceName:.deviceRGB,bytesPerRow:Int(宽度* 4),bitsPerPixel:32)rep?.size = NSSize(宽度:宽度/因数,高度:高度/因数)让ctx = NSGraphicsContext(bitmapImageRep:rep!)NSGraphicsContext.saveGraphicsState()NSGraphicsContext.current = ctximage.draw(在:NSMakeRect(0,0,宽度/因数,高度/因数))ctx?.flushGraphics()NSGraphicsContext.restoreGraphicsState()//获取NSData并保存let data = rep?.representation(using:.png,properties:[:])//属性为![String:任何])//做 {尝试数据?.写(到:url)返回真}抓住 {返回假}}

解决方案

您可以将整个代码放入自动释放池:

如果您编写一个创建许多临时对象的循环.您可以使用循环内的自动释放池块以处理这些对象在下一次迭代之前.在循环中使用自动释放池块有助于减少应用程序的最大内存占用.

for path.indices中的iautoreleasepool {//您所有的图片大小调整代码都在这里}}

I am new to Mac OS App Development with Swift. But I tried to make the simple ImageResizer app. I have to resize 50k images. After 10 hours, the memory has increased to nealy 120GB. I thought Swift also has Garbage collector. Why does it increase memory? I will show you my code.

for i in 0..<paths.count { let path = paths[i] if let image = NSImage(contentsOf: path) { ... if self.resize(image: image, size: size, to: URL(fileURLWithPath: resizedImagePath)) { print("Image saved to \(resizedImagePath)") continue } } } func resize(image: NSImage, size: Int, to url: URL) -> Bool { if !image.isValid { print("invalid image") return false } guard let pixelsWide = image.representations.first?.pixelsWide else { return false } let factor: CGFloat = CGFloat(pixelsWide) / image.size.width var width: CGFloat = CGFloat(size) var height: CGFloat = CGFloat(size) if image.size.width > image.size.height { height = width * image.size.height / image.size.width } else { width = height * image.size.width / image.size.height } let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: Int(width * 4), bitsPerPixel: 32) rep?.size = NSSize(width: width / factor, height: height / factor) let ctx = NSGraphicsContext(bitmapImageRep: rep!) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = ctx image.draw(in: NSMakeRect(0, 0, width / factor, height / factor)) ctx?.flushGraphics() NSGraphicsContext.restoreGraphicsState() // Get NSData, and save it let data = rep?.representation(using: .png, properties: [:]) // properties as! [String : Any]) // do { try data?.write(to: url) return true } catch { return false } }

解决方案

You can put your whole code that it is inside your loop inside an autoreleasepool:

If you write a loop that creates many temporary objects. You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.

for i in paths.indices { autoreleasepool { // all your image resizing code goes here } }

更多推荐

Swift5 MacOS ImageResize内存问题

本文发布于:2023-11-26 13:29:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   MacOS   ImageResize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!