1

我尝试以编程方式更改图像的大小和分辨率,然后保存此图像。

imageView 中的图像大小正在发生变化,但是当我查看我的文件“file3.png”时,它始终具有 640x1142 的原始分辨率。

我用谷歌搜索,但找不到解决方案。我尝试重绘图像。但也许这是错误的策略。

谢谢

@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
    }

}
4

2 回答 2

0

Change

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

to

let imgData: NSData! = imageWithNewSize.TIFFRepresentation!
于 2016-03-06T20:29:42.853 回答
0

我试图更改 NSImage for Mac 应用程序的大小,这是调整用 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!)!
   }

您需要传递 3 个参数来调用此函数,即 NSImage、宽度、高度,此函数将返回调整大小的图像。

    targetimage = resize(source, w: Int(targetwidth), h: Int(targetheight)) 
于 2016-08-04T09:19:36.313 回答