gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:19:01 24 4
gpt4 key购买 nike

我将这些功能拼凑在一起以调整图像大小和保存图像。但它似乎没有正确调整我的图像大小——一张 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)



}

最佳答案

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!);

关于swift - 调整图像大小并保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com