change resolution and size of image with cocoa/osx/swift (no mobile apps)

1.8k Views Asked by At

I try to change the size and the resolution of an image programmatically, afterwards I save this image.

The imagesize in the imageView is changing, but when I look at my file "file3.png" it always has the original resolution of 640x1142.

I googled around but can't find a solution. I try to redraw the image. But maybe it's the wrong strategy.

thanks

@IBAction func pickOneImageBtn(sender: AnyObject) {


    //load image from path
    pickedImage.image = loadImageFromPath(fileInDocumentsDirectory("Angebote.png"))


    let newSize = NSSize(width: 10, height: 10)


    if let image = pickedImage.image {

        print("found image")


        //cast to CGImage
        var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
        let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)

        if let imageRefExists = imageRef {
            print("Cast to CGImage worked \(imageRefExists)")
        }

        //redraw to NSImage with new size
        let imageWithNewSize = NSImage(CGImage: imageRef!, size: newSize)


        //save on disk
        let imgData: NSData! = imageWithNewSize.TIFFRepresentation!
        let bitmap: NSBitmapImageRep! = NSBitmapImageRep(data: imgData!)
        if let pngCoverImage = bitmap!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) {
            pngCoverImage.writeToFile("/...correctpath.../imageSourceForResize/file3.png", atomically: false)
            print("saved new image")
        }

       //the size is smaller
       pickedImage.image = imageWithNewSize
    }

}
2

There are 2 best solutions below

1
On

Change

let imgData: NSData! = pickedImage.image!.TIFFRepresentation!

to

let imgData: NSData! = imageWithNewSize.TIFFRepresentation!
0
On

I tried to change the size of a NSImage for Mac application and here is the working function to resize an image written in swift.

    func resize(image: NSImage, w: Int, h: Int) -> NSImage 
    {

      let destSize = NSMakeSize(CGFloat(w), CGFloat(h))
      let newImage = NSImage(size: destSize)
      newImage.lockFocus()
      image.drawInRect(NSMakeRect(0, 0, destSize.width, destSize.height),  fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeCopy, fraction: 1.0)

      newImage.unlockFocus()
      newImage.size = destSize
      return NSImage(data: newImage.TIFFRepresentation!)!
   }

You need to pass 3 parameters to call this function i.e NSImage, width, height and this function will return resized image.

    targetimage = resize(source, w: Int(targetwidth), h: Int(targetheight))