Tom J
Tom J

Reputation: 126

resizing image and saving to file

I have these functions that I've cobbled together to resize and save an image. But it doesn't seem to be resizing my images properly -- a 150x150 image attempted to be resized as 50x50 image ends up saved as 100x100. Any ideas what's causing it?

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)



}

Upvotes: 1

Views: 698

Answers (1)

Brad Hesse
Brad Hesse

Reputation: 668

OS X & iOS devices have scaling factors. The iPhone 5, 5S, 6, etc. all have a scaling factor of 2x. The iPhone 6 Plus has a scaling factor of 3x. The old non-retina iPhones have a 1x scaling factor. My OS X machine with a 4K display has a scaling factor of 2x.

What you should do is this:

let scalingFactor = NSScreen.mainScreen()?.backingScaleFactor;

let size = NSSize(width: 50 / scalingFactor!, height: 50 / scalingFactor!);

Upvotes: 2

Related Questions