调整图像大小并保存到文件

时间:2016-10-15 20:57:19

标签: swift xcode cocoa swift3

我有这些功能,我拼凑在一起调整大小并保存图像。但它似乎没有正确调整我的图像大小 - 150x150图像试图调整大小,因为50x50图像最终保存为100x100。有什么想法会导致它吗?

extension NSImage {
    @discardableResult
    func saveAsPNG(url: URL) -> Bool {
        guard let tiffData = self.tiffRepresentation else {
            print("failed to get tiffRepresentation. url: \(url)")
            return false
        }
        let imageRep = NSBitmapImageRep(data: tiffData)
        guard let imageData = imageRep?.representation(using: .PNG, properties: [:]) else {
            print("failed to get PNG representation. url: \(url)")
            return false
        }
        do {
            try imageData.write(to: url)
            return true
        } catch {
            print("failed to write to disk. url: \(url)")
            return false
        }
    }
}

enum error:Error {
    case imageCreationFailure
}


func resizeImageByFactor(_ url:URL) throws {
    let image = NSImage(byReferencing: url)
    guard image.isValid else { throw error.imageCreationFailure }

    let reSize  = NSSize(width: 50, height: 50)

    let oldRect = CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height)
    let newRect = CGRect(x: 0.0, y: 0.0, width: reSize.width, height: reSize.height)

    let newImage = NSImage(size: reSize)

    newImage.lockFocus()
    image.draw(in: newRect, from: oldRect, operation: .copy, fraction: 1.0)
    newImage.unlockFocus()

    newImage.size

    let url = URL(fileURLWithPath: "test.jpg", relativeTo: url.deletingLastPathComponent())
    newImage.saveAsPNG(url: url)



}

1 个答案:

答案 0 :(得分:2)

OS X& iOS设备具有缩放因子。 iPhone 5,5S,6等都具有2倍的缩放系数。 iPhone 6 Plus的缩放系数为3倍。旧的非视网膜iPhone具有1倍的缩放因子。带有4K显示屏的我的OS X机器具有2倍的缩放系数。

你应该做的是:

let scalingFactor = NSScreen.mainScreen()?.backingScaleFactor;

let size = NSSize(width: 50 / scalingFactor!, height: 50 / scalingFactor!);