Skip to content

Instantly share code, notes, and snippets.

@eiskalteschatten
Last active January 24, 2024 15:58
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469 to your computer and use it in GitHub Desktop.
Save eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469 to your computer and use it in GitHub Desktop.
A function written in Swift to resize an NSImage proportionately
//
// ImageResizer.swift
//
// Created by Alex Seifert on 18/06/2016.
// http://www.alexseifert.com
//
import Foundation
import Cocoa
// Function for resizing an NSImage
// Parameters:
// image:NSImage -> The NSImage that will be resized
// maxSize:NSSize -> An NSSize object that will define the new size of the image
func resizeImage(image:NSImage, maxSize:NSSize) -> NSImage {
var ratio:Float = 0.0
let imageWidth = Float(image.size.width)
let imageHeight = Float(image.size.height)
let maxWidth = Float(maxSize.width)
let maxHeight = Float(maxSize.height)
// Get ratio (landscape or portrait)
if (imageWidth > imageHeight) {
// Landscape
ratio = maxWidth / imageWidth;
}
else {
// Portrait
ratio = maxHeight / imageHeight;
}
// Calculate new size based on the ratio
let newWidth = imageWidth * ratio
let newHeight = imageHeight * ratio
// Create a new NSSize object with the newly calculated size
let newSize:NSSize = NSSize(width: Int(newWidth), height: Int(newHeight))
// Cast the NSImage to a CGImage
var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
// Create NSImage from the CGImage using the new size
let imageWithNewSize = NSImage(CGImage: imageRef!, size: newSize)
// Return the new image
return imageWithNewSize
}
@olivier38070
Copy link

be careful, this does not resize anything !

@georgbachmann
Copy link

Yep... unfortunately this really does not resize anything...
Anybody has a good working solution for macOS?

@eiskalteschatten
Copy link
Author

Could you provide more details about the problems your having with it?

I've used this code verbatim in two different Swift-based projects without a problem...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment