我使用以下代码将NSImage保存为不同的格式。但是由于许多SO问题中提到的视网膜屏幕问题,保存的图像具有2X分辨率。我知道使用lockfocus()
会导致此问题。但我不在代码中的任何地方使用lockfocus()
。
如何修改此代码使其无论屏幕大小/分辨率如何都能正常工作
func saveimage(xdata:NSImage,imageURL:String,format:String) -> Bool
{
let bMImg = NSBitmapImageRep(data: (xdata.tiffRepresentation)!)
switch format {
case ".png":
let filepath=URL(fileURLWithPath: imageURL+".png")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.png, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to: filepath)
return true
} catch
{
return false
}
case ".jpg":
let filepath=URL(fileURLWithPath: imageURL+".jpg")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to:filepath)
return true
} catch
{
return false
}
case ".tif":
let filepath=URL(fileURLWithPath: imageURL+".tif")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.tiff, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to:filepath)
return true
} catch
{
return false
}
case ".bmp":
let filepath=URL(fileURLWithPath: imageURL+".bmp")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.bmp, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to:filepath)
return true
} catch
{
return false
}
case ".gif":
let filepath=URL(fileURLWithPath: imageURL+".gif")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.gif, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to:filepath)
return true
} catch
{
return false
}
default:
return true
}
}