Reputation: 5103
I'm trying to use UIGraphicsImageRenderer to fix the orientation of images before uploading to my web server, and the following code works but the images it produces have a higher PPI than I want:
let imageRendererFormat = UIGraphicsImageRendererFormat()
let imageRenderer = UIGraphicsImageRenderer(size: image.size, format: imageRendererFormat)
let pngData = imageRenderer.pngData(actions: { context in
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
image.draw(in: rect)
})
The images that are produced have the correct resolution, but the PPI is 216 instead of the expected 72. I observed that the original image's scale is 1.0, but the scale of context.currentImage is 3.0. I'm not sure where this 3.0 number is coming from. This probably explains the 216 PPI, though, since 3 x 72 = 216.
How can I fix the PPI of the images being rendered? Should I apply a scale factor to the context or something?
Upvotes: 3
Views: 796
Reputation: 31
Logan's answer is correct!
Here is additional information and code that will make it easier for you to fix this problem. When you create a new UIImage using a renderer the default scale is 3. Here is some sample code to change the scale to 1.0:
let sourceImage = UUImage(yourImage)
let imageSize = CGSize(width: sourceImage.size.width, height:
sourceImage.size.height)
let imageFormat = UIGraphicsImageRendererFormat(for:
UITraitCollection(displayScale: 1.0))
let imageRenderer = UIGraphicsImageRenderer(size: imageSize, format:
imageFormat)
let newImage = renderer.image { (context) in
sourceImage.draw(in: CGRect(origin: .zero, size: imageSize))
}
Upvotes: 0
Reputation: 5103
I figured it out on my own - UIGraphicsImageRendererFormat has a 'scale' property which defaults to the same scale as the main screen. I had to explicitly set the scale to 1.0 in order to get an image with the correct PPI.
Upvotes: 3