首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift5 MacOS ImageResize内存问题

Swift5 MacOS ImageResize内存问题
EN

Stack Overflow用户
提问于 2020-06-04 18:08:24
回答 2查看 233关注 0票数 1

我是新的Mac应用程序开发与Swift。但我试着制作简单的ImageResizer应用程序。我必须重新调整50k图像的大小。10小时后,内存增加到了120 to。我以为斯威夫特也有垃圾收集器。为什么它会增加记忆?我会给你看我的密码。

代码语言:javascript
复制
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
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-04 19:13:29

您可以将循环中的全部代码放入自释放池中。

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

代码语言:javascript
复制
for i in paths.indices {
    autoreleasepool {
        // all your image resizing code goes here
    }
}
票数 3
EN

Stack Overflow用户

发布于 2020-06-04 18:31:14

Swift使用ARC (自动引用计数),这意味着当对该对象的强引用数达到零时,对象将被取消分配。我没有立即在代码中看到问题所在,但我怀疑代码中肯定有其他位置,您在代码中保存了对图像的引用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62201378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档