Image by Pixabay

How to resize UIImage with Swift

Jimmy Chen
iOS Funny World
Published in
2 min readDec 6, 2022

--

First, let’s talk about why we have the requirement of resizing UIImage .

When we upload or download the image data, if the image data size is smaller the task will take less time, so we can resize the UIImage to boost its processing speed, or even we can compress UIImage quality to make its data even smaller.

I will extend UIImage, this can let us more conveniently to call the func.

The above code gives a new width and the UIImage will scale to fit the new width, so you just call it like following.

let originImage = UIImage(named:"apple")
let resizeImage = originImage?.scale(newWidth: 640)

I think the code before row 12 you can understand, but you may be confused about ` UIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)`, it’s all right, I will explain it in the next paragraph.

What the meaning of UIGraphicsBeginImageContextWithOptions(_:_:_:)

The function will open a drawing space from the UIImage and draw in the space, you can see there are three parameters, let’s talk about what is each of these for.

  • size: Set the UIImage new size, such as. 1980x1024 or 640x480.
  • opaque: It means the UIImage will become transparent, if set to true it means not transparent, if set to false it means transparent, normally I set it to true.
  • scale: The parameter meaning scale factor, if set to 0, it means not scale, normally you can set it to 0.

Now, you have some sense of code at row 13. Then let's see other rows, row 14 which means implement draw.

The code of row 16 means to get the UIImage from the current draw space and named it newImage.

Finally, return the newImage if there is some error, it will return the origin UIImage.

Above is today’s article, stay tuned, I will write more of these article and share to you, if the article can save you a little bit time, please give me a clap, thanks.

--

--