I'm using the following code to Resize an NSimage
func resizeinbuilt(withSize targetSize: NSSize) -> NSImage? {
let frame = NSRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
guard let representation = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
return nil
}
let image = NSImage(size: targetSize, flipped: false, drawingHandler: { (_) -> Bool in
return representation.draw(in: frame)
})
return image
}
Strangely the saved image size in pixels is 400x400 even though on debugging I can clearly see the size as the 100x100
This is the save to disk code
func saveimage(face:NSImage,imageURL:String,format:String) -> Bool
{
let cgRef = face.cgImage(forProposedRect: nil, context: nil, hints: nil)
var newRep: NSBitmapImageRep? = nil
if let aRef = cgRef {
newRep = NSBitmapImageRep(cgImage: aRef)
}
newRep?.size = face.size ?? NSSize.zero
switch format {
case ".png":
let filepath=URL(fileURLWithPath: imageURL+".png")
let dataToSave = newRep?.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 = newRep?.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 = newRep?.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 = newRep?.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 = newRep?.representation(using: NSBitmapImageRep.FileType.gif, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to:filepath)
return true
} catch
{
return false
}
default:
return true
}
}