Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jacobsapps/d36b4a85ab6cb80cea7a9a97ac5d3688 to your computer and use it in GitHub Desktop.

Select an option

Save jacobsapps/d36b4a85ab6cb80cea7a9a97ac5d3688 to your computer and use it in GitHub Desktop.
private func downscaleImageData(_ data: Data, maxPixelSize: CGFloat = 800) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
return nil
}
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
let exifOrientationRaw = properties?[kCGImagePropertyOrientation] as? UInt32
let uiOrientation = exifOrientationRaw.flatMap { UIImage.Orientation(rawValue: Int($0)) } ?? .up
let options: [NSString: Any] = [
kCGImageSourceShouldCache: false,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
return nil
}
return UIImage(cgImage: cgImage, scale: 1.0, orientation: uiOrientation)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment