Extension for Resizing an image within a For Loop

I have written an extension to resize a given image:



extension NSImage {
        func resizeImage(width: CGFloat, _ height: CGFloat) -> NSImage {
            let img = NSImage(size: CGSize(width:width, height:height))
           
            img.lockFocus()
            let ctx = NSGraphicsContext.current()
            ctx?.imageInterpolation = .high
            self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: .copy, fraction: 1)
            img.unlockFocus()
           
            return img
        }
    }


But I don't know how to use it within a for loop:



   for image in images
    {
       image.resizeImage(width: CGFloat(rwidth),CGFloat(rheight))
       // I intent to resize the image and save it to a file
       // resize -> save to local file
    }


This does not work... nor I can assign the resized image to the old one. Should I create a temporary variable, assign the resized image to it and save it? This would be waste of memory I guess.



How can I solve this problem?

Accepted Reply

when you write

for image in images,

image is a constant, that cannot be modified.


So you have 2 ways :

declare as a var :

for var image in images {…


or create a temporary var:

   for image in images 
    {
       var modifiedImage = image
       modifiedImage.resizeImage(width: CGFloat(rwidth),CGFloat(rheight))
       // I intent to resize the image and save it to a file
       // resize -> save modifiedImage to local file
    }

Replies

when you write

for image in images,

image is a constant, that cannot be modified.


So you have 2 ways :

declare as a var :

for var image in images {…


or create a temporary var:

   for image in images 
    {
       var modifiedImage = image
       modifiedImage.resizeImage(width: CGFloat(rwidth),CGFloat(rheight))
       // I intent to resize the image and save it to a file
       // resize -> save modifiedImage to local file
    }

Thanks ... followed the second approach already 🙂