Hi all. I've spent six hours today trying to resize images from the Photos Library on the iPhone Simulator, but no matter what I try - and I've tried everything on StackOverflow - I always get a white line at the bottom of the image, even when trying the suggestions that specifically say "this one even gets rid of the white line!"
This is just one of the many attempts:
let image: UIImage = <whatever>
let size = CGSize(width: 800, height: 600)
guard let data = resizeImage(image: image, size: size, scale: 1).jpegData(compressionQuality: 0.75) ?? image.pngData() else {
return false
}
func resizeImage(image: UIImage, size: CGSize, scale: CGFloat) -> UIImage {
let availableRect = AVFoundation.AVMakeRect(aspectRatio: image.size, insideRect: .init(origin: .zero, size: maxSize))
let targetSize = availableRect.size
let format = UIGraphicsImageRendererFormat()
format.scale = scale
let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
let resized = renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: targetSize))
}
return resized
}
I've read that image.draw(in:)
adds that white line because it's using non-integer values and the background of a JPEG is white, so I floor()
d and round()
ed the size values, but I always get the white line.
I just can't seem to get it to work. Does anyone have a working function that will resize one of the JPEG images included in the Simulator without putting that white line down there?
Note: The pink/purple flowers image always resizes and comes back upside down, and the only difference I can see in the six images included in the Simulator is that that one is HEIF while all the others are JPEG. I'll also need any function to handle HEIF/HEIC, too, I guess...
This is on Xcode 15.0.1 (15A507) with Simulator iOS 17.0.1. I've also tried it on a real device (iPhone 15 Pro Max, iOS 17.4) and the same thing happens, so it's not like the Simulator images are banjaxed in some way.