gpt4 book ai didi

swift - OSX - 使用 Swift 加载图像并将其保存为较小的 png 文件

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

我正在寻找一种方法来上传图像文件,调整它的大小(以减少总文件大小),然后将其另存为 png。我认为一定有一种相当直接的方法可以做到这一点,但是数小时的搜索没有产生有效的结果。通过将图像导出为压缩的 JPEG,我已经能够达到所需的文件大小,但我需要保持透明度。这是我用来获取 JPEG 的代码:

func chooseImage ()  {
var image = NSImage()

//choose image from hard disk
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]

let chosenFile = panel.URL

//convert to NSData and send to Jpeg function
if chosenFile != nil {
image = NSImage(contentsOfURL: chosenFile!)!
let imageData = image.TIFFRepresentation
self.saveAsJpeg(imageData!, compression: 0.5)
}
}




func saveAsJpeg (image:NSData, compression:NSNumber) {
// make imagerep and define properties
let imgRep = NSBitmapImageRep(data: image)
let props = NSDictionary.init(object: compression, forKey: NSImageCompressionFactor)
let pingy = imgRep?.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: props as! [String : AnyObject])

//save to disk
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")

let g = GetUniqueID()
let fileName = g.getUniqueID() + ".jpeg"

do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)

if let pid = pingy {
pid.writeToURL(url, atomically: false)
} else {
print("error saving image")
}
}

我试图使用下面的代码来缩放图像以创建一个较小的 .png 文件,但无论我为大小输入什么值,生成的文件都是相同的大小(都是在高度/宽度方面和整体文件大小):

func chooseImage (size:String) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]

let chosenFile = panel.URL

if chosenFile != nil {
let image = NSImage(contentsOfURL: chosenFile!)
self.scaleImage(image!)
}
}


func scaleImage (image:NSImage) {

//create resized image
let newSize = NSSize(width: 10, height: 10)
var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
let resizedImage = NSImage(CGImage: imageRef!, size: newSize)

let imageData = resizedImage.TIFFRepresentation

//make imagerep
let imgRep = NSBitmapImageRep(data: imageData!)
let pingy = imgRep?.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])

//save to disk
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let g = GetUniqueID()
let fileName = g.getUniqueID() + ".png"

let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")
do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)
if let pid = pingy {
pid.writeToURL(url, atomically: false)
print("image is at \(documentURL)")
} else {
print("error saving image")
}
}

如有任何建议,我们将不胜感激。

最佳答案

我终于能够使用此处找到的扩展来做到这一点: https://gist.github.com/raphaelhanneken/cb924aa280f4b9dbb480

这就是我最终给他们打电话的方式,以防有人遇到类似的问题:

func chooseImage (size:String) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.runModal()
panel.allowedFileTypes = ["png", "jpeg", "jpg"]

let chosenFile = panel.URL

if chosenFile != nil {
let image = NSImage(contentsOfURL: chosenFile!)
self.scaleImageUsingExtensions(image!)
}
}

func scaleImageUsingExtensions (image:NSImage){
let size: NSSize = NSMakeSize(10, 10)
let resizedImage = image.resizeWhileMaintainingAspectRatioToSize(size)
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let g = GetUniqueID()
let fileName = g.getUniqueID() + ".png"

let folderURL = documentURL.URLByAppendingPathComponent("KKNightlife Data")
do {
try NSFileManager.defaultManager().createDirectoryAtURL(folderURL, withIntermediateDirectories: false, attributes: nil)
} catch {
print("cannot create directory - folder Exists?")
}
let url = folderURL.URLByAppendingPathComponent(fileName)
do {

try resizedImage?.savePNGRepresentationToURL(url)

}
catch {
print("error saving file")
}
}

关于swift - OSX - 使用 Swift 加载图像并将其保存为较小的 png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39218764/

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