How to resize image to have maximum width of 1280px while keeping the aspect ratio, before uploading image to server in SwiftUI AlamoFire.
func resizeImage(image: UIImage, maxWidth: CGFloat) -> UIImage? {
let oldWidth = image.size.width
let oldHeight = image.size.height
let scaleFactor = maxWidth / oldWidth
let newHeight = oldHeight * scaleFactor
let newWidth = oldWidth * scaleFactor
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
i want resize my image before uploading to server
We need to determine the scale and size, and then use
UIGraphicsImageRendererto render the image: