使用Cocoa / osx / swift更改图像的分辨率和大小(无移动应用程序) [英] change resolution and size of image with cocoa/osx/swift (no mobile apps)

查看:229
本文介绍了使用Cocoa / osx / swift更改图像的分辨率和大小(无移动应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

imageView中的图像大小正在更改,但是当我看时在我的文件 file3.png中,它的原始分辨率始终为640x1142。

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

我在Google周围搜索,但找不到解决方案。我尝试重新绘制图像。

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

谢谢

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

}


推荐答案

我尝试更改用于Mac应用程序的NSImage的大小,这是重新调整以swift编写的图像大小的有效功能。

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

您需要传递3个参数来调用此函数,即NSImage,width,height

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

这篇关于使用Cocoa / osx / swift更改图像的分辨率和大小(无移动应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆