I have a web service that I send images from iOS to. Before sending the images, I want to reduce the file size to a max. width of 1024 px to save bandwidth
I have tried
let size = CGSize(width: 1024, height: 768)
let renderer = UIGraphicsImageRenderer(size: size)
//https://nshipster.com/image-resizing/
let smallImage = renderer.image { (context) in
uiImage.draw(in: CGRect(origin: .zero, size: size))
}
but that always produces different output pixel sizes. What do I have to do to make sure that the output image does not exceed a width of 1024 px?
This one seems to work fine, you need to consider the scaling aspect of the different screens:
let scaleFactor = UIScreen.main.scale
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
let width = 1024 / scale.a
let height = 768 / scale.d
let size = CGSize(width: width, height: height)
let renderer = UIGraphicsImageRenderer(size: size)
let smallImage = renderer.image { (context) in
uiImage.draw(in: CGRect(origin: .zero, size: size))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.