【问题标题】:swift image resize and save resolution issue快速调整图像大小并保存分辨率问题
【发布时间】:2017-04-28 11:01:12
【问题描述】:

图片大小有问题。

最初我有任何尺寸的图像,可以裁剪成正方形

func cropToSquare() -> NSImage? {
    let dimensions = [self.width, self.height]
    let lessValue = dimensions.min()
    let x = floor((self.width - lessValue!) / 2)
    let y = floor((self.height - lessValue!) / 2)
    let frame = NSMakeRect(x, y, lessValue!, lessValue!)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: NSSize(width: lessValue!, height: lessValue!))
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: NSMakeRect(0, 0, lessValue!, lessValue!),
                from: frame,
                operation: NSCompositingOperation.copy,
                fraction: 1.0,
                respectFlipped: false,
                hints: [:]) {
        return img
    }
    return nil
}

接下来我调整图像大小

func copyWithSize(size: NSSize) -> NSImage? {
    let frame = NSMakeRect(0, 0, size.width, size.height)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: size)
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: frame) {
        print(size, frame)
        return img
    }
    return nil
}

最终使用来自 answer 的 png 扩展名将图像保存到文件

通常一切正常...除了图像大小。 当我从某个大小开始并调整大小以假设为 100x100 时,我保存的图像具有双倍大小 (200x200)。

我的代码有什么问题?

【问题讨论】:

    标签: swift macos resize nsimage


    【解决方案1】:

    图像在@2x 中绘制,因为您有一台配备 Retina 显示屏的 Mac。

    使用lockFocus 会创建一个新图像以显示在屏幕上,如果要将其保存到文件中,这是不切实际的。

    您可以使用以下方法获得比例因子:

    NSScreen.main.backingScaleFactor

    并相应地调整您的调整大小。

    但最好的解决方案是创建一个NSBitmapImageRep 并手动将它的size 设置为您想要的图像大小。

    【讨论】:

    • 非常感谢奥斯卡!工作完美:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多