How to resize image to have maximum width of 1280px

63 Views Asked by At

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

1

There are 1 best solutions below

0
Den Andreychuk On

We need to determine the scale and size, and then use UIGraphicsImageRenderer to render the image:

extension UIImage {
    func scaled(toWidth: CGFloat) -> UIImage? {
        let scale = toWidth / size.width
        let newHeight = size.height * scale
        let size = CGSize(width: toWidth, height: newHeight)
        let rect = CGRect(origin: .zero, size: size)
        let format = UIGraphicsImageRendererFormat()
        format.scale = self.scale
        return UIGraphicsImageRenderer(size: size, format: format).image { _ in
            draw(in: rect)
        }
    }
}