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

主宰稳场 提交于 2020-01-07 00:47:53

问题


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
    }

}

回答1:


Change

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

to

let imgData: NSData! = imageWithNewSize.TIFFRepresentation!



回答2:


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)) 


来源:https://stackoverflow.com/questions/35831389/change-resolution-and-size-of-image-with-cocoa-osx-swift-no-mobile-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!