How to resize a UIImage and get rid of the white line?

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.

  • Could you please provide a sample project that reproduces this issue? I am not able to reproduce this on my end.

Add a Comment

Accepted Reply

Right, fixed it. Started from scratch. There was an extension on UIImage that was kicking in and screwing it up.

Replies

How would I give you an MRE? It's part of my massive app. All I'd be doing is creating a new project and using the code I've already provided, and you've already done that, no?

So, in your code, that function works perfectly fine? You're able to resize one of the images included in the iPhone Simulator, and not get the white line?

Right, fixed it. Started from scratch. There was an extension on UIImage that was kicking in and screwing it up.